Forward HttpServletRequest to a different server

前端 未结 5 1645
星月不相逢
星月不相逢 2021-01-31 15:24

I got a HttpServletRequest request in my Spring Servlet which I would like to forward AS-IS (i.e. GET or POST content) to a different server.

What would be

5条回答
  •  情深已故
    2021-01-31 16:09

    I also needed to do the same, and after some non optimal with Spring controllers and RestTemplate, I found a better solution: Smiley's HTTP Proxy Servlet. The benefit is, it really does AS-IS proxying, just like Apache's mod_proxy, and it does it in a streaming way, without caching the full request/response in the memory.

    Simply, you register a new servlet to the path you want to proxy to another server, and give this servlet the target host as an init parameter. If you are using a traditional web application with a web.xml, you can configure it like following:

    
        proxy
        org.mitre.dsmiley.httpproxy.ProxyServlet
        
          targetUri
          http://target.uri/target.path
        
    
    
      proxy
      /mapping-path/*
    
    

    or, of course, you can go with the annotation config.

    If you are using Spring Boot, it is even easier: You only need to create a bean of type ServletRegistrationBean, with the required configuration:

    @Bean
    public ServletRegistrationBean proxyServletRegistrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(
                new ProxyServlet(), "/mapping-path/*");
        bean.addInitParameter("targetUri", "http://target.uri/target.path");
        return bean;
    }
    

    This way, you can also use the Spring properties that are available in the environment.

    You can even extend the class ProxyServlet and override its methods to customize request/response headers etc, in case you need.

    Update: After using Smiley's proxy servlet for some time, we had some timeout issues, it was not working reliably. Switched to Zuul from Netflix, didn't have any problems after that. A tutorial on configuring it with Spring Boot can be found on this link.

提交回复
热议问题