如何使用tuckey's UrlRewriteFilter重写Spring MVC中的url:
这
http://localhost:8080/demo/api.do?method=getUser&uid=1001
到
http://localhost:8080/demo/api/user/1001
控制器片段:
@Controller
@RequestMapping("/api.do")
public class APIController {
@RequestMapping(params = "method=getUser")
public String methodName(HttpServletRequest request) {
//CODE BLOCK
}
}
答案 0 :(得分:3)
如果您正在使用maven
,请添加相关性<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>4.0.3</version>
</dependency>
在 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>
将以下规则添加到 WEB-INF / urlrewrite.xml
<urlrewrite>
<rule>
<from>^/demo/api.do?method=getUser&uid=(.*)$</from>
<to>/demo/api/user/$1</to>
</rule>
</urlrewrite>
答案 1 :(得分:2)
您真的需要使用URL重写文件管理器吗?为什么不为这两种类型的URL定义两种方法,并且路由到单一方法来处理处理
@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
}
答案 2 :(得分:1)
在SpringMVC中,您只需
即可@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
如果您只发送对象值
您也可以发送user_id
作为参数
public String methodName(@RequestParam("user_id") String userid, Model model)
重要的是你为视图解析器添加了Bean
,这里是基于注释的示例
@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;
}