Spring MVC——拦截器
1. 自定义拦截器,并实现org.springframework.web.servlet.HandlerInterceptor接口
public class CustomerHandlerInterceptor implements HandlerInterceptor {
//方法调用之前
//返回值 true 放行 false 禁止访问
//预处理操作,比如登录权限验证
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {return false}
//进入方法之后,返回ModelAndView之前
//在方法执行过程中,保存一些公用数据,比如在modelAndView中保存导航菜单,
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView modelAndView)
throws Exception {}
//方法调用完之后
//处理异常,日志记录
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception ex)
throws Exception {}
}
2.在spring-mvc.xml中配置全局拦截器
<!-- 配置全局拦截器 -->
<mvc:interceptors>
<!-- 登录权限认证 -->
<mvc:interceptor>
<!-- 匹配项目根下所有路径 *匹配一级目录 **匹配一级及以下所有子目录 -->
<mvc:mapping path="/**"/><!-- 注意:只是在Spring中配置了拦截器,所以当静态访问页面时不会被拦截 -->
<bean class="com.neuedu.interceptor.CustomerHandlerInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
3. 在自定义拦截CustomerHandlerInterceptor中,实现登录权限验证
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
System.out.println("preHandle...."+request.getRequestURI());
//如果用户正在登录过程中,放行
if(request.getRequestURI().contains("login.action"))
{
return true;
}
//当用户名不为空,代表用户已登录,放行
String username = (String)request.getSession().getAttribute("username");
if(username != null && !"".equals(username))
{
return true;
}
//未正常登录,返回登录界面
request.getRequestDispatcher("/index.jsp").forward(request, response);
return false;
}
4. 编写测试页面index.jsp
<a href="login.action?username=tomcat&password=123456">登录-进入主页</a><br/><br/>
<a href="main.action">未登录-直接进入主页</a>
5. 编写控制器代码UserController.java
@Controller
public class UserController {
@RequestMapping("/login")
public String login(HttpSession session,String username,String password)
{
//用户名、密码登录校验
System.out.println("login:"+username + password);
session.setAttribute("username", username);
return "main";
}
@RequestMapping("/main")
public String main()
{
System.out.println("main....");
return "main";
}
}
6. 测试路径
http://localhost:8088/springMvc_10_interceptor/index.jsp