1. 程式人生 > >兩種簡單的servlet實現反向代理

兩種簡單的servlet實現反向代理

以下兩種方法都需要引入jar包:

 <dependency>
    <groupId>org.mitre.dsmiley.httpproxy</groupId>
    <artifactId>smiley-http-proxy-servlet</artifactId>
    <version>1.6</version>
 </dependency>
一、web.xml實現(tomcat,預設埠)(Spring專案可以,簡單地web專案可能會有問題,正在探索中)
<!-- 反向代理 begin -->
<servlet>
    <servlet-name>poxyHttpRequest</servlet-name>
    <servlet-class>org.mitre.dsmiley.httpproxy.ProxyServlet</servlet-class>
    <init-param>
        <param-name>targetUri</param-name>
        <param-value>https://www.baidu.com/s</param-value>
    </init-param>
    <init-param>
        <param-name>log</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>poxyHttpRequest</servlet-name>
    <url-pattern>/s/*</url-pattern>
</servlet-mapping>
<!-- 反向代理 end -->

訪問localhost:8080/s即展示百度的頁面
servlet.png

二、通過程式碼註冊bean(基於Spring boot)

可以通過setName來設定多個bean,從而代理多個url

package *.*.*;

import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by czz on 2018/11/13.
 */
@Configuration
public class SolrProxyServletConfiguration {
    @Bean
    public ServletRegistrationBean servletRegistrationBaiduBean(){
        ServletRegistrationBean baidu= new ServletRegistrationBean(new ProxyServlet(), "/s/*");
        baidu.setName("baidu");
        baidu.addInitParameter("targetUri", "http://www.baidu.com/s");
        baidu.addInitParameter(ProxyServlet.P_LOG, "false");
        return baidu;
    }

    @Bean
    public ServletRegistrationBean servletRegistrationRunoobBean(){
        ServletRegistrationBean runoob= new ServletRegistrationBean(new ProxyServlet(), "/bootstrap/*");
        runoob.setName("runoob");
        runoob.addInitParameter("targetUri", "http://www.runoob.com/bootstrap");
        runoob.addInitParameter(ProxyServlet.P_LOG, "false");
        return runoob;
    }
}