Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过 滤器Filter,用于对处理器进行预处理和后处理
• 定义拦截器 – 实现HandlerInterceptor接口 – 接口中提供三个方法
代码展示
public class MyHandlerInterceptor implements HandlerInterceptor{
@Override//前处理
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// 用户认证
/*1.用户如果没有登录就访问不该访问的请求,那么显示登录页面
* 2.用户如果已经登录,那么就放行
* 3.用户访问login.do请求,那么放行
*/
String uri=request.getRequestURI();
System.out.println("uri:"+uri);// uri:/springmvc-interceptor/user/update.do
if(uri==null||"".equals(uri)){
return false;//不放行
}
if(uri.contains("login.do")){
return true;//放行,请求继续
}
String username=(String) request.getSession().getAttribute("username");
System.out.println("username:"+username);
if(username==null){
//重定向到登录页面,让它登录
response.sendRedirect(request.getContextPath()+"/login.jsp");
return false;
}else{
return true;//放行
}
}
@Override//调用controller方法之后,返回ModelAndView之前处理
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("调用controller方法之后,返回ModelAndView之前处理");
}
@Override//后处理
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("后处理");
}
}
新建controller
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("/update.do")
public String update(){
System.out.println("update");
return "update";
}
}
新建登录页面 login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
登录页面
</body>
</html>
接着新建一个session.jsp 页面存放用户的登录信息
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%session.setAttribute("username", "jack"); %>
</body>
</html>
测试
1、不登录,直接访问内部资源update.do
如果不通过登录,直接访问update.do是不允许的,直接被拦截,然后重定向到登录页面
2、直接访问login.jsp
规规矩矩的访问登录页面,是给通过。
3、正常输入用户名去登录
访问save_username.jsp 拿到我要的用户名,拿着用户名去登录