springboot使用拦截器判断是否登录
时间:2022-12-21 09:27:37|栏目:JAVA代码|点击: 次
springboot拦截器判断是否登录
实现拦截器的两个步骤
- 自定义拦截器实现HandlerInterceptor接口
- 创建一个配置类继承WebMvcConfigurerAdapter类并重写addInterceptors方法
代码:
1、自定义拦截器
@Component public class AdminLoginInterceptor implements HandlerInterceptor { // 在请求处理之前调用,只有返回true才会执行请求 @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // 得到session HttpSession session = httpServletRequest.getSession(true); // 得到对象 Object admin = session.getAttribute("admin"); // 判断对象是否存在 if(admin!=null){ return true; }else{ // 不存在则跳转到登录页 httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/adminLogin"); 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、自定义配置类继承WebMvcConfigurerAdapter
@SpringBootConfiguration public class AdminLoginAdapter extends WebMvcConfigurerAdapter { @Autowired AdminLoginInterceptor adminLoginInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/login/**"); super.addInterceptors(registry); } }
springboot 增加拦截器判断是否登录
1、创建拦截器
package com.example.demo.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 〈一句话功能简述〉<br> * 〈拦截器〉 * * @author 丶Zh1Guo * @create 2018/11/22 * @since 1.0.0 */ public class LoginInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class); // 在请求处理之前,只有返回true才会执行请求 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("[拦截器]启动登录状态拦截"); // 得到session HttpSession session = request.getSession(); logger.info("[拦截器]sessionID:" + session.getId()); // 得到用户信息 Object userInfo = session.getAttribute("userInfo"); //判断用户是否登录 if (userInfo != null) { logger.info("[拦截器]用户已经登录,用户名,密码:" + session.getAttribute("userInfo")); return true; } else { //不存在跳转至登录页 response.sendRedirect(request.getContextPath() + "/"); // 跳转到首页登录 logger.info("[拦截器]用户没有登录,已跳转到:" + request.getContextPath() + "/"); return false; } } // 视图渲染后执行 @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、继承WebMvcConfigureAdapter类
覆盖其addInterceptors接口,注册自定义的拦截器
@Configuration 注解一定要有
package com.example.demo.interceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 〈一句话功能简述〉<br> * 〈自定义配置类〉 * * @author 丶Zh1Guo * @create 2018/11/22 * @since 1.0.0 */ @Configuration public class LoginConfig implements WebMvcConfigurer { /** * 该方法用于注册拦截器 * 可注册多个拦截器,多个拦截器组成一个拦截器链 */ @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns 添加路径 // excludePathPatterns 排除路径 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/sys/*"); // 拦截sys路径下的url // .excludePathPatterns(""); } }
3、LoginController
/** * Copyright (C), 2017-2018, XXX有限公司 * FileName: LoginController * Author: 丶Zh1Guo * Date: 2018/11/22 11:10 * Description: 登录 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.example.demo.controller; import com.example.demo.dao.UserDAO; import com.example.demo.pojo.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; /** * 〈一句话功能简述〉<br> * 〈登录〉 * * @author 丶Zh1Guo * @create 2018/11/22 * @since 1.0.0 */ @Controller public class LoginController { // 日志 private Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private UserDAO userDAO; // 启动服务自动跳转登录 // @RequestMapping(value = {"/", "/login"}) @RequestMapping(value = "/") public String login() { return "login"; } // 登录 @RequestMapping(value = "/loginCheck", method = RequestMethod.POST) @ResponseBody public String loginCheck(HttpServletRequest request) { // 获取登录信息 String userName = request.getParameter("userName"); String password = request.getParameter("password"); // 封装成对象 User user = new User(); user.setUserName(userName); user.setPassword(password); // 校验用户信息 User info = userDAO.checkUser(user); if (info != null) { request.getSession().setAttribute("userInfo", userName + "-" + password); logger.info("登录成功,用户名:" + userName + "密码:" + password); return "success"; } else { logger.info("登录失败,用户名:" + userName + "密码:" + password); return "fail"; } } }
4、未登录会自动跳转到登录页面
上一篇:SpringBoot整合websocket实现即时通信聊天
栏 目:JAVA代码
下一篇:Java基础第四篇 封装与接口
本文地址:http://www.codeinn.net/misctech/221865.html