Springmvc入门基础(六) ---拦截器应用demo
1.拦截器定义
Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。
2.拦截器demo
demo需求:
- 拦截用户请求,判断用户是否登录(登录请求不能拦截)
- 如果用户已经登录。放行
- 如果用户未登录,跳转到登录页面。
2.1 编写登录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>
<form action="${pageContext.request.contextPath }/user/login.action">
<label>用户名:</label>
<br>
<input type="text" name="username">
<br>
<label>密码:</label>
<br>
<input type="password" name="password">
<br>
<input type="submit">
</form>
</body>
</html>
2.2 编写用户controller
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("/login")
public String login(String username, String password, HttpSession session) {
// 校验用户登录
System.out.println(username);
System.out.println(password);
// 把用户名放到session中
session.setAttribute("username", username);
return "redirect:/item/itemList.action";
}
}
2.3 编写拦截器
public class Interceptor1 implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
// 从request中获取session
HttpSession session = request.getSession();
// 从session中获取username
Object username = session.getAttribute("username");
// 判断username是否为null
if (username != null) {
// 如果不为空则放行
return true;
} else {
// 如果为空则跳转到登录页面
response.sendRedirect(request.getContextPath() + "/user/toLogin.action");
}
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2.4 配置拦截器
在springmvc.xml文件中配置拦截器
<!-- SPringmvc的拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<!-- 自定义的拦截器类 -->
<bean class="cn.springmvc.interceptor.Interceptor1"/>
</mvc:interceptor>
<!-- <mvc:interceptor>
<mvc:mapping path="/**"/>
自定义的拦截器类
<bean class="cn.springmvc.interceptor.Interceptor2"/>
</mvc:interceptor> -->
</mvc:interceptors>
生命很短,请让生活更精彩一些!