springmvc restful配置有一个小小的坑坑
首先web.xml配置
<!-- spring-mvc --> <servlet> <servlet-name>springServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
url-pattern 配置/即可,如果配置/*的话会出问提,连返回视图jsp也会拦截,具体原因请看翻看源码
问提:这样配置的话,大家都会忽略一个问题,就是a/b/c可以访问,但是a/b/c.do;a/b/c.mm;a/b/c.zz都可以访问a/b/c的controller,在不修改源码源码的情况下,我们来
解决这个问题,虽然都是拦截了/这样的请求,但是我们只让a/b/c这样的请求进入controller,带有【.】的后缀的不让他进入,直接去404页面
解决办法:
web.xml加入filte
1 <!-- 对url进行简单的过滤 --> 2 <filter> 3 <filter-name>servletRequest</filter-name> 4 <filter-class>cn.tomcat.quickstart.common.filter.ServletRequestFilter</filter-class> 5 </filter> 6 <filter-mapping> 7 <filter-name>servletRequest</filter-name> 8 <url-pattern>/*</url-pattern> 9 </filter-mapping>
ServletRequestFilter.java
1 import java.io.IOException; 2 3 import javax.servlet.FilterChain; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 import org.springframework.web.filter.OncePerRequestFilter; 9 10 /** 11 * 12 * 对进来的url进行处理,放在filter最前面,springmvc <url-pattern>/</url-pattern> 13 * 默认拦截所有请求,ex:a/b/c.do,a/b/c.html,a/b/c.action,a/b/c 14 * 去掉带后缀的访问,模仿restful风格,只接受a/b/c的请求 15 * 16 */ 17 public class ServletRequestFilter extends OncePerRequestFilter { 18 19 @Override 20 protected void doFilterInternal(HttpServletRequest request, 21 HttpServletResponse response, FilterChain filterChain) 22 throws ServletException, IOException { 23 String requestPath = request.getServletPath(); 24 //不用担心会把静态文件给拦截了,例如*.js,*.css类似于这样的,在web.xml做处理了 25 //所有请求带有后缀【.】的直接去404,不接受这样的请求 26 if(requestPath.lastIndexOf(".")!=-1){ 27 request.getRequestDispatcher("/WEB-INF/pages/error/404.jsp").forward(request, response); 28 }else{ 29 filterChain.doFilter(request, response); 30 } 31 } 32 33 }
带有.结尾的直接go 404,哈哈,也许你会问要是这样静态文件不是也会被过滤掉了吗?类似于*.js,*.css,.....N多这样类型的文件
请去看上一篇文章,已经解决这个问题了,同样吧静态文件交给了servlet来处理,根本不用进入springMVC的servlet
连接:http://www.cnblogs.com/ppli/p/5669260.html
哈哈,网上找了很多,但是很不幸没找到解决方案,有大神有更好的方案麻烦请告诉我哦哦哦哦哦哦,我好改正