java - 如何在 spring boot 到达 Controller 之前修改请求体

标签 java spring spring-boot

我有一个 spring boot 应用程序。 我更改每个发布请求的请求正文。 是否可以在请求到达 Controller 之前修改请求主体。 请包括一个例子。

最佳答案

另一种方法是向 HttpServletRequest 对象添加一个属性。之后,您可以使用 @RequestAttribute 注释在 Controller 类中读取该属性。

在拦截器中

@Component
    public class SimpleInterceptor extends HandlerInterceptorAdapter {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws ServletException, IOException {
            String parameter = request.getParameter("parameter");
            if (parameter == "somevalue") {
                request.setAttribute("customAttribute", "value");
            }

            return true;
        }

    }

在 Controller 中

@RestController
@RequestMapping("")
public class SampleController {


    @RequestMapping(value = "/sample",method = RequestMethod.POST)
    public String work(@RequestBody SampleRequest sampleRequest, @RequestAttribute("customAttribute") String customAttribute) {
        System.out.println(customAttribute);
        return "This works";
    }
}

这具有不修改请求正文的优点。

关于java - 如何在 spring boot 到达 Controller 之前修改请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932518/

相关文章:

java - 如何使用 Intellij Idea 的异常断点

java - 如何在 Java 中健全地检查日期

Java:如何立即将文本字段中的更改发送到文件?

java - spring boot 应用程序运行,但我在网络浏览器中收到错误 404

java - Spring boot RestTemplate 发布 400 错误

spring - java.lang.NoClassDefFoundError 在谷歌应用引擎上使用 spring security

spring-boot - Spring Boot + Tomcat Embedded + Struts 2 - 不调用 JSP

java - Spring 启动 : Determining what autoconfiguration are applied to jersey?

java - SonarQube规则: "Using command line arguments is security-sensitive" in Spring Boot application

java - spring-boot 中 tomcat 的默认连接池?