Loading

SpringBoot+拦截器

实现登录拦截器:

  1. 用户未登录时访问/logout或/center会被拦截
  2. 用户已登录时访问/logout或/center不会被拦截
  3. 用户登录后访问过/logout后再次访问/center会被拦截
  4. 被拦截后,将会被redirect至/error页面

1. UserController

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private User user;
	@RequestMapping("/login/{username}/{password}")
	public String login(
			@PathVariable("username") String username,
			@PathVariable("password") String password,
			HttpServletRequest request){
		user.setName(username);
		//将user对象存入session中
	   request.getSession().setAttribute("user",user);
		return user.getName()+" login success";
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request){
		//从session中获取user对象
		User logoutUser = (User) request.getSession().getAttribute("user");
		request.getSession().removeAttribute("user");
		return logoutUser.getName()+" logout success";
	}

	@RequestMapping("/center")
	public String center(HttpServletRequest request){
		//从session中获取user对象
		User centerUser = (User) request.getSession().getAttribute("user");
		return "User center: "+centerUser.getName();
	}

	@RequestMapping("/error")
	public String error(){
		return "error, you haven't login";
	}
}

2. 实现拦截器UserInterceptor

public class UserInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//从本地获取cookie,判断是否已经存在user
		User user = (User) request.getSession().getAttribute("user");
		if (user == null) {
			// 如果session中没有user,则重定向至error
			response.sendRedirect("/user/error");
			return false;
		}
		return true;
	}
}

3. @Configuration配置拦截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
	@Override
	public void addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry registry) {
		String[] addpath = {
				"/user/**"
		};
		String[] excludePath={
				"/user/login/**",//login若不被排除,那么无法登录
				"/user/error",//error若不被排除,那么进入error后会再次被拦截,形成死循环
		};
		registry.addInterceptor(new UserInterceptor()).addPathPatterns(addpath).excludePathPatterns(excludePath);
	}
}
posted @ 2022-04-08 22:50  吉比特  阅读(52)  评论(0编辑  收藏  举报