当前位置:网站首页>15. Interceptor - HandlerInterceptor
15. Interceptor - HandlerInterceptor
2022-08-10 23:49:00 【If you want to learn, learn Big Wolf】
15.1 基本介绍
在 Spring Boot 项目中, 拦截器是开发中常用手段,要来做登陆验证、性能检查、日志记录等
基本步骤:
① 编写一个拦截器实现 HandlerInterceptor 接口
② 拦截器注册到配置类中(实现 WebMvcConfigurer 的 addInterceptors)
③ 指定拦截规则
④ 回顾 SpringMVC ==> 文章链接
15.2 拦截器应用实例
15.2.1 需求说明
- 使用拦截器防止用户非法登录
- 如图 - 使用拦截器就不需要在每个方法验证了
- 浏览器输入 http://localhost:8080/manage.html
- 如果用户没有登录,则返回登录界面
15.2.2 代码实现
- 创建 D:\xjs_springboot\springboot-usersys\src\main\java\com\xjs\springboot\interceptor\LoginInterceptor.java
package com.xjs.springboot.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
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;
/** * @Author: 谢家升 * @Version: 1.0 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
/** * Called before the target method is executed * * @param request * @param response * @param handler * @return * @throws Exception */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//1. 获取访问的 URI
String uri = request.getRequestURI();
log.info("preHandle拦截到的请求的URI={}", uri);
//2. 进行登录校验
HttpSession session = request.getSession();
Object loginAdmin = session.getAttribute("loginAdmin");
if (null != loginAdmin) {
//Indicates that the user has successfully logged in
return true;
} else {
//It means that the user has not logged in successfully
//拦截,重新返回到登录页面
request.setAttribute("msg", "你没有登录/请登录~~");
request.getRequestDispatcher("/").forward(request, response);
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle() 执行了...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion() 执行了...");
}
}
- 创建 D:\xjs_springboot\springboot-usersys\src\main\java\com\xjs\springboot\config\WebConfig.java
package com.xjs.springboot.config;
import com.xjs.springboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** * @Author: 谢家升 * @Version: 1.0 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器LoginInterceptor
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") //这里拦截所有的请求
.excludePathPatterns("/","/login","/images/**"); //指定要放行的,根据业务需要来添加放行的请求路径
}
}
- 修改 D:\xjs_springboot\springboot-usersys\src\main\java\com\xjs\springboot\controller\AdminController.java ,去掉 session Verify that the user is logged in with the code,并完成测试,Pay attention to the page and background logs
package com.xjs.springboot.controller;
import com.xjs.springboot.bean.Admin;
import com.xjs.springboot.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
/** * @Author: 谢家升 * @Version: 1.0 */
@Controller
@Slf4j
public class AdminController {
//Respond to a user's login request
@PostMapping("/login")
public String login(Admin admin, HttpSession session, Model model) {
//验证用户是否合法
if (StringUtils.hasText(admin.getName()) && "888".equals(admin.getPassword())) {
//Save the logged in user tosession
session.setAttribute("loginAdmin", admin);
/**合法 重定向到 manage.html * 1. Not using request forwarding is to prevent refreshing the page from causing the form to be repeatedly submitted * 2. Why is it written here manage.html Because this can be more explicit which page to go to * 3. 这里的 manage.html said to find The method's mapping path is manage.html */
return "redirect:/manage.html";
} else {
//不合法 重新登录!
model.addAttribute("msg", "账号/用户名错误");
return "adminLogin";
}
}
//处理用户请求 manage.html
@GetMapping("/manage.html")
public String mainPage(Model model, HttpSession session) {
This is temporarily used in the methodsession验证,Later, we will use interceptor verification uniformly
//Object loginAdmin = session.getAttribute("loginAdmin");
//
//if (loginAdmin != null) { //说明成功登录过
// //这里集合-模拟用户数据,放入到request域中,并显示
// ArrayList<User> users = new ArrayList<>();
// users.add(new User(1, "关羽", "123456", 20, "[email protected]"));
// users.add(new User(2, "张飞", "123456", 26, "[email protected]"));
// users.add(new User(3, "赵云", "123456", 28, "[email protected]"));
// users.add(new User(4, "马超", "123456", 22, "[email protected]"));
// users.add(new User(5, "黄忠", "123456", 50, "[email protected]"));
//
// //将数据放入到request域中
// model.addAttribute("users", users);
//
// return "manage"; //This is where our view resolves to /template/manage.html
//} else {
// //Return to the login page here,并给出提示
// model.addAttribute("msg", "你没有登录/请登录");
//
// return "adminLogin"; //请求转发到 adminLogin.html
//}
log.info("进入mainPage()");
//这里集合-模拟用户数据,放入到request域中,并显示
ArrayList<User> users = new ArrayList<>();
users.add(new User(1, "关羽", "123456", 20, "[email protected]"));
users.add(new User(2, "张飞", "123456", 26, "[email protected]"));
users.add(new User(3, "赵云", "123456", 28, "[email protected]"));
users.add(new User(4, "马超", "123456", 22, "[email protected]"));
users.add(new User(5, "黄忠", "123456", 50, "[email protected]"));
//将数据放入到request域中
model.addAttribute("users", users);
return "manage"; //This is where our view resolves to /template/manage.html
}
}
15.2.3 注意事项和细节
- URI 和 URL 的区别
- URI = Universal Resource Identifier
- URL = Universal Resource Locator
- Identifier:标识符
- Locator:定位器
- 从字面上来看,URI 可以唯一标识一个资源,URL 可以提供找到该资源的路径
- 举例说明:
String requestURI = request.getRequestURI();
String requestURL = request.getRequestURL().toString();
- 注册拦截器,依然可以使用如下方式
package com.xjs.springboot.config;
import com.xjs.springboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** * @Author: 谢家升 * @Version: 1.0 */
@Configuration
public class WebConfig /*implements WebMvcConfigurer*/ {
//@Override
//public void addInterceptors(InterceptorRegistry registry) {
//
// //注册自定义拦截器LoginInterceptor
// registry.addInterceptor(new LoginInterceptor())
// .addPathPatterns("/**") //这里拦截所有的请求
// .excludePathPatterns("/","/login","/images/**"); //指定要放行的,根据业务需要来添加放行的请求路径
//
//}
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/", "/login", "/images/**");
}
};
}
}
边栏推荐
猜你喜欢
u盘数据不小心删除怎么恢复,u盘数据删除如何恢复
[C language] Detailed explanation of data storage
基于Web的疫情隔离区订餐系统
Deep Learning Transformer Architecture Analysis
Easy-to-use translation plug-in - one-click automatic translation plug-in software
SQL注入基础
11. Custom Converter
矩阵的迹(详解)
工作记录:DB2查询数据,当字段为空时,赋值
15. 拦截器-HandlerInterceptor
随机推荐
高校就业管理系统设计与实现
C language% (%d,%c...)
高性能MySQL核心整理强势来袭
线程相关知识点
翻译软件哪个准确度高【免费】
Talk预告 | 中国科学技术大学和微软亚洲研究院联合培养博士生冷燚冲:语音识别的快速纠错模型FastCorrect
Microsoft: Into Focus with Scott Guthrie Scott Hanselman Rajesh Jha and Kevin Scott | KEY11
CSDN21天学习挑战赛之折半查找
HFCTF 2021 Internal System writeup
C语言%(%d,%c...)
11. Custom Converter
虎符CTF 2022 Quest-Crash Writeup
ROS Experimental Notes - Install QPEP and Intel-MKL
Talking about jsfuck coding
SQL注入基础---order by \ limit \ 宽字节注入
2.0966 铝青铜板CuAl10Ni5Fe4铜棒
Rust从入门到精通05-语句和表达式
【C语言篇】表达式求值(隐式类型转换,算术转换)
iNFTnews | In the Web3 era, users will have data autonomy
sqlmap结合dnslog快速注入