1.用户登录权限校验
1.1最初用户登录
@RestController
@RequestMapping("/user2")
public class User2Controller {
/**
*
* 某方法1
*/
@RequestMapping("/m")
public Object method(HttpServletRequest request){
//有session就获取,没有不会创建
HttpSession session=request.getSession(false);
if(session!=null&&session.getAttribute("userinfo")!=null){
//说明已经登录,业务处理
return true;
}else {
return false;
}
}
/**
*某方法2
*/
@RequestMapping("/m2")
public Object method2(HttpServletRequest request){
HttpSession session=request.getSession(false);
if(session!=null&&session.getAttribute("userinfo")!=null){
return true;
}else {
return false;
}
}
}
2Spring AOP用户统一登录验证的问题
@Slf4j
@Aspect//定义了一个切点
@Component //演示统一功能,先去掉
public class LoginAspect {
@Around("pointcut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object oj=null;
long start=System.currentTimeMillis();
//调用目标方法
try {
//执行连接点的方法
oj = joinPoint.proceed();
} catch (Throwable e) {
throw e;
}
log.info(joinPoint.getSignature().toString()+"耗时:"(System.currentTimeMillis()-start));
//必须要写返回结果
return oj;
}
@Before("execution(* com.example.springaopdemo.controller.TestController.* (..))")
public void before2(){
log.info("before");
}
}
3Spring拦截器
3.1自定义拦截器
/**
* 创建一个拦截器
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断是否登录
HttpSession session=request.getSession(false);
if(session!=null&&session.getAttribute("username")!=null){
//通过,不进行处理
return true;
}
//表示没有权限
response.setStatus(401);
return false;
}
}
3.2将自定义拦截器加入到系统配置
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
//添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//添加拦截器
registry.addInterceptor(loginInterceptor)
//拦截哪些url
.addPathPatterns("/**")
//放过哪些url
.excludePathPatterns("/api/user/login")
.excludePathPatterns("/api/user/reg");
}
// 所有的接⼝添加 api 前缀
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("api", c -> true);
}
}
// 拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") // 拦截所有接⼝
.excludePathPatterns("/**/*.js")
.excludePathPatterns("/**/*.css")
.excludePathPatterns("/**/*.jpg")
.excludePathPatterns("/login.html")
.excludePathPatterns("/**/login"); // 排除接⼝
}
登录拦截器:
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
@RequestMapping("/get")
//获取用户信息
public String getInfo(){
log.info("get info");
return "get info";
}
//注册
@RequestMapping("/reg")
public String reg(){
log.info("reg");
// int a=10/0;
return "reg";
}
@RequestMapping("/login")
public boolean login(HttpServletRequest request,String username,String password){
log.info("login");
//判断username和password是否为空
// if(username!=null && "".equals(username)&& password!=null &&"".equals(password)){
//
// }
//Spring
if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
return false;
}
if(!"admin".equals(username) || !"admin".equals(password)) {
return true;
}
HttpSession session = request.getSession(true);
session.setAttribute("username", username);
return true;
}
}
直接访问get会被拦截,表示拦截器创建成功
4拦截器实现原理
正常情况下的调⽤顺序:
然⽽有了拦截器之后,会在调⽤ Controller 之前进⾏相应的业务处理,执⾏的流程如下图所示:
4.1 实现原理源码分析
⽽所有⽅法都会执⾏ DispatcherServlet 中的 doDispatch 调度⽅法,doDispatch 源码如下:
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
mappedHandler = this.getHandler(processedRequest);
if (mappedHandler == null) {
this.noHandlerFound(processedRequest, response);
return;
}
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
String method = request.getMethod();
boolean isGet = HttpMethod.GET.matches(method);
if (isGet || HttpMethod.HEAD.matches(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
return;
}
}
// 调用预处理【重点】
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 执行Contorller层的逻辑
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
this.applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
} catch (Exception var20) {
dispatchException = var20;
} catch (Throwable var21) {
dispatchException = new NestedServletException("Handler dispatch failed", var21);
}
this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
} catch (Exception var22) {
this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
} catch (Throwable var23) {
this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
}
} finally {
if (asyncManager.isConcurrentHandlingStarted()) {
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
} else if (multipartRequestParsed) {
this.cleanupMultipart(processedRequest);
}
}
}
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex = i++) {
// 获取项目中使用的拦截器, 我们之前就是实现了这个类,然后添加的拦截器
// 在这里,我们自定义的拦截器就会被调用,用户登陆权限验证的方法就会实现,这就是拦截器实现的原理
HandlerInterceptor interceptor = (HandlerInterceptor)this.interceptorList.get(i);
if (!interceptor.preHandle(request, response, this.handler)) {
this.triggerAfterCompletion(request, response, (Exception)null);
return false;
}
}
return true;
}
此时⽤户登录权限的验证⽅法就会执⾏,这就是拦截器的实现原理。
4.2拦截器小结
5拓展:统一前缀访问
所有请求地址添加 api 前缀: 文章来源:https://www.toymoban.com/news/detail-638156.html
// 所有的接⼝添加 api 前缀
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("api", c -> true);
}
文章来源地址https://www.toymoban.com/news/detail-638156.html
到了这里,关于Spring Boot统一处理功能——拦截器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!