SpringBoot-定制Web容器Tomcat,请求头增加traceid参数
通过特定Web容器工厂TomcatServletWebServerFactory定制
1、Pom.xml文件
10年积累的成都网站制作、成都网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有瑶海免费网站建设让你可以放心的选择与我们合作。
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE
com.jane
tralink
0.0.1-SNAPSHOT
tralink
Demo project for Spring Boot
1.8
Greenwich.SR2
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
2、Controller文件Test
package com.jane.tralink.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/test")
public class Test {
@PostMapping("/hello")
public String hello(HttpServletRequest request) {
System.out.println( request.getHeader("traceid"));
return "hello";
}
}
3、自定义Web容易定制器
package com.jane.tralink.controller;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class MyTomcatCustomize implements WebServerFactoryCustomizer {
@Override
public void customize(TomcatServletWebServerFactory factory) {
//TraceValve 是实际的增加Header的类
factory.addEngineValves(new TraceValve());
}
}
4、TraceValve
package com.jane.tralink.controller;
import org.apache.catalina.Valve;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.UUID;
public class TraceValve extends ValveBase {
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
request.getCoyoteRequest().getMimeHeaders().addValue("traceid").setString(uuid);
Valve next = getNext();
if(null == next) return;
next.invoke(request, response);
}
}
5、运行结果:http://127.0.0.1:8081/test/hello
网页题目:SpringBoot-定制Web容器Tomcat,请求头增加traceid参数
标题来源:http://pwwzsj.com/article/giihoj.html