SpringMVC有可以使用拦截器对请求进行必要的拦截验证。
其接口为HandlerInterceptor
package org.springframework.web.servlet;
public interface HandlerInterceptor {
boolean preHandle(
HttpServletRequest request, HttpServletResponse response,
Object handler)
throws Exception;
void postHandle(
HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView)
throws Exception;
void afterCompletion(
HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex)
throws Exception;
}
HandlerInterceptor 有三个方法
preHandle: (预处理)在业务处理器处理请求之前被调用,
postHandle: 在业务处理器处理请求执行完成后,生成视图之前执行,
afterCompletion: 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等 。
所以要实现对请求必要的拦截验证,需要继承HandlerInterceptorAdapter并重写其三个方法。
首先是在[spring]-servlet.xml文件对其进行配置
<!-- 配置拦截 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->
<mvc:mapping path="/" />
<mvc:mapping path="/user/**" />
<mvc:mapping path="/test/**" />
<bean class="oasystem.interceptor.CommonInterceptor"></bean>
</mvc:interceptor>
<!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 -->
</mvc:interceptors>
然后在oasystem.interceptor.CommonInterceptor类下面写自己的逻辑方法
package oasystem.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
//该普通拦截继承spring的拦截处理器
public class CommonInterceptor extends HandlerInterceptorAdapter {
//重写预处理方法
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String username = (String)request.getSession().getAttribute("user");
if(username == null){
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
}else
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO 自動生成されたメソッド・スタブ
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO 自動生成されたメソッド・スタブ
super.afterCompletion(request, response, handler, ex);
}
}
这是一个最简单的逻辑验证,即使用perHandle拦截判断访问index.jsp的请求有没有username,若果没用,就返回login.jsp页面。