SpringBoot--全局请求处理--方法/实例

原文网址: SpringBoot--全局请求处理--方法/实例_IT利刃出鞘的博客-CSDN博客

简介

说明

       本文用实例介绍SpringBoot如何进行全局请求处理。

方案简介

         @ControllerAdvice与@ModelAttribute结合可以全局处理请求,在调用Controller之前预先进行处理。

下边三种方式都可以全局处理请求(请求进来时,它们的执行顺序为从上到下):

  1. 过滤器
  2. 拦截器
  3. @ControllerAdvice+@ModelAttribute

本文介绍第三种

系列文章

SpringBoot全局处理我写了一个系列:

  1. SpringBoot--全局异常处理--方法/实例_IT利刃出鞘的博客-CSDN博客
  2. SpringBoot--全局响应处理--方法/实例_IT利刃出鞘的博客-CSDN博客
  3. SpringBoot--全局请求处理--方法/实例_IT利刃出鞘的博客-CSDN博客
  4. SpringBoot--全局格式处理--方法/实例_IT利刃出鞘的博客-CSDN博客

@ControllerAdvice介绍

说明

        @ControllerAdvice里边有@Component,用于类,可包含@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。(因此是全局的处理方法)。

        可以在多个类上使用@ControllerAdvice,可通过@Order来控制顺序。不能通过实现Order接口来控制顺序,因为这部分源码里只支持@Order这种方式。见:调整多个ControllerAdvice的执行顺序_felixu的博客-CSDN博客

        在Spring4及之后, @ControllerAdvice支持配置控制器的子集,可通过annotations(), basePackageClasses(), basePackages()方法选择控制器子集。

官网网址

springmvc 注解总结 - SpringMVC中文官网

使用场景

  1. @ControllerAdvice+@ExceptionHandler:全局异常处理
    1. 捕获Controller中抛出的指定类型异常,可对不同类型的异常区别处理
  2. @ControllerAdvice+ 实现ResponseBodyAdvice接口:全局响应处理(处理返回值)
    1. 其标注的方法将会在目标Controller方法执行之后执行。
  3. @ControllerAdvice+@ModelAttribute:全局请求处理
    1. 其标注的方法将会在目标Controller方法执行之前执行。
    2. 使用场景示例:鉴权/授权、全局处理格式
  4. @ControllerAdvice+@InitBinder:全局请求处理
    1. 其标注的方法将会在目标Controller方法执行之前执行。
    2. request中自定义参数解析方式进行注册
    3. 使用场景示例:全局处理格式
      SpringBoot--LocalDateTime--全局格式转换/前后端/前端入参/响应给前端_IT利刃出鞘的博客-CSDN博客

实例

代码

全局请求处理类 

package com.example.common.advice;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalRequestAdvice {
    @ModelAttribute
    public void authenticationUser(HttpServletRequest request) {
        System.out.println("查询的参数:" + request.getQueryString());
        System.out.println("用户名参数:" + request.getParameter("userName"));
        System.out.println("header1值:" + request.getHeader("header1"));
    }
}

Controller 

package com.example.business.controller;

import com.example.business.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class UserController {

    @GetMapping("save")
    public void save(User user) {
        System.out.println("Controller保存用户:" + user);
    }
}

测试

postman访问:http://localhost:8080/user/save?userName=Tony&age=22   

//header设置:

后端结果

postman结果(本处我没返回东西,所以是空的)

猜你喜欢

转载自blog.csdn.net/feiying0canglang/article/details/125231795