实现拦截器自定义
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...");
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;
}
|