首先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
<!-- 对url进行简单的过滤 --><filter><filter-name>servletRequest</filter-name><filter-class>cn.tomcat.quickstart.common.filter.ServletRequestFilter</filter-class></filter><filter-mapping><filter-name>servletRequest</filter-name><url-pattern>/*</url-pattern></filter-mapping>ServletRequestFilter.javaimport java.io.IOException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.filter.OncePerRequestFilter;/*** * 对进来的url进行处理,放在filter最前面,springmvc <url-pattern>/</url-pattern>* 默认拦截所有请求,ex:a/b/c.do,a/b/c.html,a/b/c.action,a/b/c* 去掉带后缀的访问,模仿restful风格,只接受a/b/c的请求* */public class ServletRequestFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {String requestPath = request.getServletPath();//不用担心会把静态文件给拦截了,例如*.js,*.css类似于这样的,在web.xml做处理了//所有请求带有后缀【.】的直接去404,不接受这样的请求if(requestPath.lastIndexOf(".")!=-1){request.getRequestDispatcher("/WEB-INF/pages/error/404.jsp").forward(request, response);}else{filterChain.doFilter(request, response);}}}
带有.结尾的直接go 404,哈哈,也许你会问要是这样静态文件不是也会被过滤掉了吗?类似于*.js,*.css,.....N多这样类型的文件