1.写一个类实现HandlerInterceptor接口
package com.spring.intercepter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginIntercepter implements HandlerInterceptor {
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion");
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("postHandle");
//可以通过ModelAndView参数来改变显示的视图,或修改发往视图的方法
arg3.setViewName("home");
arg3.addObject("msg", "这是返回的数据!");
}
/*
* 返回值
* true 请求继续
* false 请求终止
* arg2 被拦截的请求的目标对象
*/
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("preHandle");
//为请求设置编码
arg0.setCharacterEncoding("utf-8");
//对用户是否登录进行判断
if(arg0.getSession().getAttribute("user") == null){
arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
return false;
}
return true;
}
}
2。在spring配置文件注册
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"></mvc:mapping>
<bean class="com.spring.intercepter.LoginIntercepter"</bean>
</mvc:interceptor>
</mvc:interceptors>