实现拦截器自定义
package com.CakeCN.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor1 implements HandlerInterceptor {
//在目标方法执行之前 执行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...");
return false;
}
//目标方法执行后,视图返回前执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
//视图都已经返回后,执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
}
Spring-mvc.xml中配置拦截器
所有访问控制器的请求都会先经过这个拦截器
<!-- 配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.CakeCN.interceptor.MyInterceptor1"/>
</mvc:interceptor>
</mvc:interceptors>
在拦截器中设置先检查session中有无登录信息,如果有就正确处理请求,如果无就重定向到登陆界面
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...");
//判断用户是否登录, 通过判断session中有没有user
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if(user == null){
response.sendRedirect("/login.jsp");
return false;
}
return true;
}
注意要在配置拦截器时,将登录的请求放行
<!-- 配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/login"/>
<bean class="com.CakeCN.interceptor.MyInterceptor1"/>
</mvc:interceptor>
</mvc:interceptors>
@RequestMapping("login")
public ModelAndView login(String username, String password, HttpSession session){
ModelAndView modelAndView = new ModelAndView();
//对比数据库用户登录信息是否正确
// ......
User user = new User();
user.setUsername(username);
modelAndView.setViewName("success.jsp");
modelAndView.addObject("username",username);
session.setAttribute("user", user);
return modelAndView;
}