SpringMVC url rewrite with tuckey UrlRewriteFilter

2019-02-20 08:16发布

How can I rewrite url in SpringMVC with tuckey's UrlRewriteFilter like this:

From

http://localhost:8080/demo/api.do?method=getUser&uid=1001

to

http://localhost:8080/demo/api/user/1001

The controller snippets:

@Controller
@RequestMapping("/api.do")
public class APIController {

    @RequestMapping(params = "method=getUser")
    public String methodName(HttpServletRequest request) {
        //CODE BLOCK
    }
}

3条回答
祖国的老花朵
2楼-- · 2019-02-20 08:47

Add a dependency if you're using maven

<dependency>
    <groupId>org.tuckey</groupId>
    <artifactId>urlrewritefilter</artifactId>
    <version>4.0.3</version>
</dependency>

Enable the filter in your web.xml

<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

Add the following rule to WEB-INF/urlrewrite.xml

<urlrewrite>
    <rule>
       <from>^/demo/api.do?method=getUser&amp;uid=(.*)$</from>
       <to>/demo/api/user/$1</to>
    </rule>
</urlrewrite>
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-20 08:52

Do you really need use URL rewrite filer? Why not define two methods for both types of URL and route to single method to handle processing

@RequestMapping(value = "/demo/api.do?"....)
public void method1(){
  //...
  handler();
}
@RequestMapping(value = "/demo/api/user/{user-id}"....)
public void method1(){
  //...
  handler();
}

private void handler(){
    //This method will have all the controller logic
}
查看更多
倾城 Initia
4楼-- · 2019-02-20 09:03

In SpringMVC, you can do it simply

@Controller
@RequestMapping("/api")
public class APIController {

    @RequestMapping("/user")
    public ModelAndView methodName(HttpServletRequest request) {
        //CODE BLOCK

        // to redirect other view 
        new ModelAndView("...your view page");
    }

    @RequestMapping("/user/{user_id}")
    @ResponseBody
    public String methodName(HttpServletRequest request) {
        //CODE BLOCK
    }
}

@ResponseBody if you send only object values

also you can send user_id as param

public String methodName(@RequestParam("user_id") String userid, Model model)

Important thing you have add Bean for view resolver, here is annotation based example

@Bean
public UrlBasedViewResolver setupViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/pages/");        
    resolver.setSuffix(".jsp");    // what you used 
    resolver.setViewClass(JstlView.class);
    return resolver;
}
查看更多
登录 后发表回答