SpringBoot拦截器实现登录拦截
程序员文章站
2022-04-17 18:23:28
...
SpringBoot拦截器可以做什么
可以对URL路径进行拦截,可以用于权限验证、解决乱码、操作日志记录、性能监控、异常处理等。
SpringBoot拦截器实现登录拦截
pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> </parent> <groupId>com.wyj</groupId> <artifactId>springboot-interceptor01</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-interceptor01</name> <description>springboot拦截器</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- springboot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <build> <finalName>springboot-interceptor01</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
WebMvcConfigurer:继承WebMvcConfigurationSupport类,重写addInterceptors方法
/** * 在springboot2.0.0之后,WebMvcConfigurerAdapter已经过时了 * 会使用WebMvcConfigurer或者WebMvcConfigurationSupport替代 * * @author wyj * @create 2019-06-01 21:48 */ @Configuration public class WebMvcConfigurer extends WebMvcConfigurationSupport { /** * 在springboot2.0.0之前继承WebMvcConfigurerAdapter类,重写addInterceptors方法 * * @param registry */ // @Override // public void addInterceptors(InterceptorRegistry registry) { // /** // * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行 // */ // registry.addInterceptor(new AuthorityInterceptor()) // .addPathPatterns("/user/**"); // super.addInterceptors(registry); // } /** * 在springboot2.0.0之后实现WebMvcConfigurer接口,重写addInterceptors方法 * * @param registry */ // @Override // public void addInterceptors(InterceptorRegistry registry) { // /** // * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行 // */ // registry.addInterceptor(new AuthorityInterceptor()) // .addPathPatterns("/user/**"); // } /** * 在springboot2.0.0之后继承WebMvcConfigurationSupport类,重写addInterceptors方法 * * @param registry */ @Override protected void addInterceptors(InterceptorRegistry registry) { /** * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行 */ registry.addInterceptor(new AuthorityInterceptor()) .addPathPatterns("/user/**"); super.addInterceptors(registry); } }
AuthorityInterceptor:实现HandlerInterceptor接口,重写preHandle、postHandle、afterCompletion方法
preHandle:在请求处理之前进行调用(Controller方法调用之前)
postHandle:请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
afterCompletion:在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
@Slf4j public class AuthorityInterceptor implements HandlerInterceptor { private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();//不拦截的URI static { NOT_INTERCEPT_URI.add("/user/login.html"); NOT_INTERCEPT_URI.add("/user/login"); } /** * 在请求处理之前进行调用(Controller方法调用之前) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { String uri = request.getRequestURI(); if (NOT_INTERCEPT_URI.contains(uri)) { log.info("不拦截" + uri); return true; } log.info("拦截" + uri); HttpSession session = request.getSession(); UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session"); if (userInfo == null) { throw new RuntimeException("用户未登陆"); } return true; } /** * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception { } /** * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行 * (主要是用于进行资源清理工作) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception { } }
UserController:
@Controller @RequestMapping(value = "/user") public class UserController { @RequestMapping(value = "/login.html") public String index() { return "login"; } @RequestMapping(value = "/login") public String login(User user) { //查询数据库,我这里直接写死 User dbUser = new User(1, "zhangsan", "123456", "admin"); if (dbUser.getPassword().equals(user.getPassword())) { UserInfo userInfo = new UserInfo(dbUser.getId(), dbUser.getUsername(), dbUser.getRole()); HttpSession session = getRequest().getSession(); session.setAttribute("user_info_in_the_session", userInfo); return "admin"; } return "login"; } @RequestMapping(value = "/userInfo") @ResponseBody public String userInfo() { HttpSession session = getRequest().getSession(); UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session"); return userInfo.toString(); } private HttpServletRequest getRequest() { return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); } }
User:
@Data @NoArgsConstructor @AllArgsConstructor public class User implements Serializable { private int id; private String username; private String password; private String role; }
UserInfo: 用于存在用户信息储存在session中
@Data @NoArgsConstructor @AllArgsConstructor public class UserInfo implements Serializable { private int id; private String username; private String role; }
login.html:只是一个很简单的登录表单
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登陆页面</title> </head> <body> <form action="/user/login" method="post"> 登陆:<br/> 用户名:<input name="username" id="username" type="text"/><br/> 密 码:<input name="password" id="password" type="password"/><br/> <input type="submit" value="登陆"/> </form> </body> </html>
admin.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <form action="/user/userInfo" method="get"> <input type="submit" value="用户信息"/></form> </body> </html>
以上就是SpringBoot拦截器实现登录拦截的详细内容,更多请关注其它相关文章!
上一篇: JAVA8的分页工具
下一篇: Djangoz中文乱码的问题_MySQL
推荐阅读
-
Asp.net Core 3.1基于AspectCore实现AOP实现事务、缓存拦截器功能
-
简单的实现登录拦截及统一异常处理(自定义异常)
-
vue拦截器实现统一token,并兼容IE9验证功能
-
axios拦截器,登录超时跳转到login页面
-
SpringBoot + Shiro 实现微博登录
-
Spring mvc 实现用户登录的方法(拦截器)
-
SpringBoot + SpringSecurity 短信验证码登录功能实现
-
SpringMVC拦截器实现监听session是否过期详解
-
Spring Boot使用过滤器和拦截器分别实现REST接口简易安全认证示例代码详解
-
详解SpringBoot 解决拦截器注入Service为空问题