Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add and delete Header in HttpServletRequest

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to add and delete Header in HttpServletRequest". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "how to add and delete Header in HttpServletRequest".

HttpServletRequest does not provide modified / deleted Api

The operations on Header defined in HttpServletRequest are all read-only and have not been modified.

Public interface HttpServletRequest extends ServletRequest {... Public long getDateHeader (String name); public String getHeader (String name); public Enumeration getHeaders (String name); public Enumeration getHeaderNames (); public int getIntHeader (String name);...}

HttpServletRequest is just an interface, and the implementation is provided by the Servlet container. No matter whether it is any container, the implementation class is sure to store the requested Header somewhere, so you can add or delete the container storing Header through reflection.

Define a Controller for a test first

This Controller is very simple, all the Header of the client is JSON-like response to the client.

Import java.util.ArrayList;import java.util.Enumeration;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping ("/ demo") public class DemoController {/ / traverses all request Header and responds to the client. Map @ GetMapping public Object demo (HttpServletRequest request) {Map headers = new LinkedHashMap (); Enumeration nameEnumeration = request.getHeaderNames (); while (nameEnumeration.hasMoreElements ()) {String name = nameEnumeration.nextElement (); List values = headers.get (name) If (values = = null) {values = new ArrayList (); headers.put (name, values);} Enumeration valueEnumeration = request.getHeaders (name) While (valueEnumeration.hasMoreElements ()) {values.add (valueEnumeration.nextElement ());}} return headers;}} use Tomcat as container Tomcat to implement HttpServletRequest

Tomcat uses the appearance pattern (Facade), which is a slightly more complicated implementation

Org.apache.catalina.connector.RequestFacade |-org.apache.catalina.connector.Request |-org.apache.coyote.Request |-org.apache.tomcat.util.http.MimeHeaders

The first is the org.apache.catalina.connector.RequestFacade implementation, which has an object of org.apache.catalina.connector.Request. This object has another org.apache.coyote.Request object, and this object has another org.apache.tomcat.util.http.MimeHeaders field, which is the container that stores the client request header. Just get the MimeHeaders through reflection and modify it.

Org.apache.catalina.connector.RequestFacadepublic class RequestFacade implements HttpServletRequest {protected org.apache.catalina.connector.Request request = null;...} org.apache.catalina.connector.Requestpublic class Request implements HttpServletRequest {protected org.apache.coyote.Request coyoteRequest;...} org.apache.coyote.Request coyoteRequestpublic final class Request {private final org.apache.tomcat.util.http.MimeHeaders headers = new MimeHeaders ();} add or delete the request Header through reflection in Filter

The hypothetical scenario is that you need to add a unified x-request-id to the request Header and use this ID to locate each request from the log.

Import java.io.IOException;import java.lang.reflect.Field;import java.util.UUID;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpFilter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.catalina.connector.Request;import org.apache.catalina.connector.RequestFacade;import org.apache.tomcat.util.http.MimeHeaders;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component Import org.springframework.util.ReflectionUtils;@WebFilter (urlPatterns = "/ *") @ Component@Order (- 999) public class RequestIdGenFilter extends HttpFilter {/ * / private static final long serialVersionUID = 1787347739651657706L @ Override protected void doFilter (HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {try {/ / get org.apache.catalina.connector.Request Field connectorField = ReflectionUtils.findField (RequestFacade.class, "request", Request.class) from RequestFacade; connectorField.setAccessible (true) Request connectorRequest = (Request) connectorField.get (req); / / get org.apache.coyote.Request Field coyoteField = ReflectionUtils.findField (Request.class, "coyoteRequest", org.apache.coyote.Request.class) from org.apache.catalina.connector.Request; coyoteField.setAccessible (true) Org.apache.coyote.Request coyoteRequest = (org.apache.coyote.Request) coyoteField.get (connectorRequest); / / get MimeHeaders Field mimeHeadersField = ReflectionUtils.findField (org.apache.coyote.Request.class, "headers", MimeHeaders.class) from org.apache.coyote.Request MimeHeadersField.setAccessible (true); MimeHeaders mimeHeaders = (MimeHeaders) mimeHeadersField.get (coyoteRequest); this.mineHeadersHandle (mimeHeaders);} catch (Exception e) {throw new RuntimeException (e) } super.doFilter (req, res, chain);} protected void mineHeadersHandle (MimeHeaders mimeHeaders) {/ / add a Header and randomly generate the request ID mimeHeaders.addValue ("x-request-id") .setString (UUID.randomUUID (). ToString ()) / / remove a header mimeHeaders.removeHeader ("User-Agent");}} request Controller to get the response result

You can see that the x-request-id header was successfully added and the User-Agent header was removed.

The default Servlet container for SpringBoot is Tomcat

Use Undertow as a container

More and more people are using Undertow as a Servlet container, which is said to perform much better than Tomcat

SpringBoot replaces Tomcat with Undertow

Just exclude the spring-boot-starter-tomcat from the spring-boot-starter-web and add the spring-boot-starter-undertow manually

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat HttpServletRequest implementation in org.springframework.boot spring-boot-starter-undertow Undertow

Its implementation is relatively simple.

Io.undertow.servlet.spec.HttpServletRequestImpl |-io.undertow.server.HttpServerExchange |-io.undertow.util.HeaderMap

In the io.undertow.servlet.spec.HttpServletRequestImpl implementation class, there is a property object io.undertow.server.HttpServerExchange, which in turn contains an io.undertow.util.HeaderMap,HeaderMap that is the storage container for the request Header, which can be retrieved by reflection.

Io.undertow.servlet.spec.HttpServletRequestImplpublic final class HttpServletRequestImpl implements HttpServletRequest {private final io.undertow.server.HttpServerExchange exchange;} io.undertow.server.HttpServerExchangepublic final class HttpServerExchange extends AbstractAttachable {private final HeaderMap requestHeaders;} adds or deletes import java.io.IOException;import java.lang.reflect.Field;import java.util.UUID;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpFilter;import javax.servlet.http.HttpServletRequest to the request Header through reflection in Filter Import javax.servlet.http.HttpServletResponse;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;import org.springframework.util.ReflectionUtils;import io.undertow.server.HttpServerExchange;import io.undertow.servlet.spec.HttpServletRequestImpl;import io.undertow.util.HeaderMap;import io.undertow.util.HttpString;@WebFilter (urlPatterns = "/ *") @ Component@Order (- 999) public class RequestIdGenFilter extends HttpFilter {/ * / private static final long serialVersionUID = 1787347739651657706L @ Override protected void doFilter (HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {try {/ / get HttpServerExchange Field exchangeField = ReflectionUtils.findField (HttpServletRequestImpl.class, "exchange", HttpServerExchange.class) from HttpServletRequestImpl; exchangeField.setAccessible (true) HttpServerExchange httpServerExchange = (HttpServerExchange) exchangeField.get (req); / / get HeaderMap Field headerMapField = ReflectionUtils.findField (HttpServerExchange.class, "requestHeaders", HeaderMap.class) from HttpServerExchange; headerMapField.setAccessible (true) HeaderMap requestHeaderMap = (HeaderMap) headerMapField.get (httpServerExchange); this.handleRequestHeaderMap (requestHeaderMap);} catch (Exception e) {throw new RuntimeException (e);} super.doFilter (req, res, chain) } private void handleRequestHeaderMap (HeaderMap requestHeaderMap) {/ / add Header requestHeaderMap.add (new HttpString ("x-request-id"), UUID.randomUUID () .toString (); / / remove Header requestHeaderMap.remove ("User-Agent");}} request Controller to get the result

Thank you for your reading, the above is the content of "how to add and delete Header in HttpServletRequest". After the study of this article, I believe you have a deeper understanding of how to add and delete Header in HttpServletRequest, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report