servlet反向代理
2018-12-28 本文已影响0人
东方欲晓_莫道君行早
一、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 -->
需要引入jar包
<dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId>
<version>1.6</version>
</dependency>
访问localhost:8080/s
即展示百度的页面
二、通过代码注册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;
}
}