欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Springmvc restful配置遇到的小坑

程序员文章站 2024-03-13 13:10:33
首先web.xml配置 spr...

首先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.java
import 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 {
@override
protected 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多这样类型的文件