拦截各种请求,并对请求进行处理(类似于AOP的思想)。
1.拦截器的配置
applicationContext.xml
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截包括这个请求下的所有请求-->
<mvc:mapping path="/**"/>
<!-- 配置拦截器-->
<bean class="com.ming.config.LoginIntercepter"></bean>
</mvc:interceptor>
</mvc:interceptors>
2.案例引入
例:登录验证
要求:
1.想进入主页必须先进入登录页面
2.登录完后,主页获取登录名
3.进入主页后可以注销用户,注销后返回登录页面
3.案例分析图
4.拦截器编写
public class LoginIntercepter implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
//准许登录请求通过
if (request.getRequestURI().contains("goLogin")) {
return true;
}
//准许登录请求通过
if (request.getRequestURI().contains("login")) {
return true;
}
//判断用户是否存在,存在则通过
if (session.getAttribute("userLoginInfo") != null) {
return true;
}
//除以上条件都被拦截,执行如下代码
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
}
}
- 拦截器:继承HandlerInterceptor
- preHandle():请求处理前执行,返回true,代表通过,程序正常执行;返回false,代表程序需按照拦截器的处理去执行。
5.Controller编写
@Controller
@RequestMapping("/user")
public class loginController {
@RequestMapping("/login")
public String login(HttpSession session, String username, String password, Model model){
session.setAttribute("userLoginInfo",username);
model.addAttribute("username",username);
return "main";
}
@RequestMapping("/main")
public String main(){
return "main";
}
@RequestMapping("/goLogin")
public String login(){
return "login";
}
@RequestMapping("/goOut")
public String goOut(HttpSession session,String username, String password){
session.removeAttribute("userLoginInfo");
return "main";
}
}
6.相关页面
- index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1><a href="${pageContext.request.contextPath}/user/goLogin">登录页面</a></h1>
<h1><a href="${pageContext.request.contextPath}/user/main">首页</a></h1>
</body>
</html>
- login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名:<input type="text" name="username"/>
密码:<input type="text" name="password"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
- main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<span>${username}</span>
<p>
<a href="${pageContext.request.contextPath}/user/goOut">注销</a>
</p>
</body>
</html>