1. 创建一个拦截器类并实现HandlerInterceptor接口
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user = (User)request.getSession().getAttribute("user");
if(null == user) {
response.sendRedirect(request.getContextPath() + "/error");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
2. 创建一个配置类(即SpringMVC配置文件中使用mvc:interceptors )
@Configuration
public class Interceptor implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] addPathPatterns = {
"/user/**"
};
String[] excludePathPatterns = {
"/user/login", "/user/out", "/user/error"
};
registry.addInterceptor(new UserInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
}
}
3. 创建测试类
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/login")
public Object login(HttpServletRequest request) {
User user = new User();
user.setId(11);
user.setUsername("zhangsan");
request.getSession().setAttribute("user", user);
return "login success";
}
@RequestMapping("/center")
public Object center() {
return "see center";
}
@RequestMapping("/out")
public Object out() {
return "out anytiem";
}
@RequestMapping("/error")
public Object error() {
return "error page";
}
}
package cn.atfaith.pojo;
public class User {
private Integer id;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}