搭建页面我就不详细的说了,只是简单的把要配置文件说一下
- 主要配置beans.xml文件和 spring-servlet.xml文件
beans.xml
<bean id="timeBasedAccessInterceptor" class="zttc.itat.web.TestInterceptor">
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="timeBasedAccessInterceptor"/>
</list>
</property>
</bean>
spring-servlet.xml
**注意:配置中一定要去掉<mvc:annotation-driven />,去掉其默认配置,否则会实例化两个,自己写的那个TestInterceptor就不会拦截成功,获取的request和response为空**
DefaultAnnotationHandlerMapping ,所以用下面这个就好了。
<context:component-scan base-package="zttc.itat.web"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
- TestInterceptor页面代码,这里是继承HandlerInterceptorAdapter,然后在里面preHandle要处理的代码,我这里是是把request和response的值保存起来
package zttc.itat.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import zttc.itat.model.RequestResponseContext;
public class TestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
RequestResponseContext.setResponse(response);
RequestResponseContext.setRequest(request);
return super.preHandle(request, response, handler);
}
}
- 这里是RequestResponseContext.java里的代码,主要是为了线程安全写的来保存response和request
package zttc.itat.model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestResponseContext {
private static ThreadLocal<HttpServletRequest> request_threadLocal = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> reponse_threadLocal = new ThreadLocal<HttpServletResponse>();
public static void setRequest(HttpServletRequest request) {
request_threadLocal.set(request);
}
public static HttpServletRequest getRequest() {
return request_threadLocal.get();
}
public static void removeRequest() {
request_threadLocal.remove();
}
public static void setResponse(HttpServletResponse response) {
reponse_threadLocal.set(response);
}
public static HttpServletResponse getResponse() {
return reponse_threadLocal.get();
}
public static void removeResponse() {
reponse_threadLocal.remove();
}
}
- 在其它页面就可以直接RequestResponseContext.getResponse()这样获取response了