SpringBoot 做代web理服務(wù)器
因公司業(yè)務(wù)需要,把多個(gè)子系統(tǒng)集成到一個(gè)平臺,但是又不希望把代碼重做一遍,子系統(tǒng)用nodejs,主平臺用java,所以不能直接融合到一起。 一個(gè)想法就是,現(xiàn)在web開發(fā)都采用的前后臺分離模式,把子平臺的前臺代碼放在主平臺的一個(gè)目錄中,然后在主平臺做一個(gè)代理,對接子平臺的后臺代碼,主平臺做個(gè)代理,這樣不同平臺代碼就打通了。 今天嘗試了下,springmvc框架,springboot提供很好用的代碼可以簡單來實(shí)現(xiàn),以下是自己測試的小例子,供自己備忘,也希望能分享有需要的朋友!
測試采用的springboot的demo模塊,從start.spring.io上下載
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns ="http://maven.apache.org/POM/4.0.0" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion > 4.0.0
</modelVersion > <groupId > com.example
</groupId > <artifactId > demo
</artifactId > <version > 0.0.1-SNAPSHOT
</version > <packaging > jar
</packaging > <name > demo
</name > <description > Demo project for Spring Boot
</description > <parent > <groupId > org.springframework.boot
</groupId > <artifactId > spring-boot-starter-parent
</artifactId > <version > 1.5.4.RELEASE
</version > <relativePath /> </parent > <properties > <project.build.sourceEncoding > UTF-8
</project.build.sourceEncoding > <project.reporting.outputEncoding > UTF-8
</project.reporting.outputEncoding > <java.version > 1.7
</java.version > </properties > <dependencies > <dependency > <groupId > org.springframework.boot
</groupId > <artifactId > spring-boot-starter
</artifactId > </dependency > <dependency > <groupId > org.springframework.boot
</groupId > <artifactId > spring-boot-starter-test
</artifactId > <scope > test
</scope > </dependency > <dependency > <groupId > org.springframework.boot
</groupId > <artifactId > spring-boot-starter-web
</artifactId > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.springframework.boot
</groupId > <artifactId > spring-boot-maven-plugin
</artifactId > </plugin > </plugins > </build > </project >
SpringBoot 下載來的例子中自帶的Demo,補(bǔ)充個(gè)RestTemplate工具
package com.example.demo;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@ServletComponentScan
@EnableAutoConfiguration
public class DemoApplication {@Autowired private RestTemplateBuilder builder;
@Bean public RestTemplate
restTemplate () {
return builder.build(); }
public static void main (String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
因?yàn)樾枰獢r截界面對子系統(tǒng)的請求,所以添加了一個(gè)過濾器,攔截到子系統(tǒng)代碼時(shí)做一次轉(zhuǎn)發(fā),代碼如下
package com.example.demo;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebFilter (filterName =
"myFilter" , urlPatterns =
"/*" )
public class MyWebFilter implements Filter {protected final Logger logger = LoggerFactory.getLogger(
this .getClass());
@Override public void destroy () {logger.debug(
"...MyWebFilter destroy..." );}
@Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse resp = (HttpServletResponse) response;String requestURI = req.getRequestURI();logger.debug(
"...MyWebFilter doFilter..." );logger.debug(
"req:" + requestURI);
if (requestURI.startsWith(
"/sub" )) {RequestDispatcher rd = req.getRequestDispatcher(
"/reset" );req.setAttribute(
"requestURI" , requestURI);rd.forward(req, resp);
return ;}chain.doFilter(req, resp);}
@Override public void init (FilterConfig arg0)
throws ServletException {logger.info(
"...MyWebFilter init..." );}}
*接下來重要一步就是寫自己如果做的代理,其實(shí)本來想用httpclient來寫,感覺有點(diǎn)復(fù)雜,后發(fā)網(wǎng)上發(fā)現(xiàn)RestTemplate是個(gè)好東西,減少了許多代碼
package
com .example .demo .action import java
.util .Enumeration
import java
.util .HashMap
import java
.util .Map import javax
.servlet .http .HttpServletRequest
import javax
.servlet .http .HttpServletResponse
import org
.slf 4j
.Logger
import org
.slf 4j
.LoggerFactory
import org
.springframework .beans .factory .annotation .Autowired
import org
.springframework .web .bind .annotation .RequestMapping
import org
.springframework .web .bind .annotation .ResponseBody
import org
.springframework .web .bind .annotation .RestController
import org
.springframework .web .client .RestTemplate @RestController
public class MyAction {protected final Logger logger = LoggerFactory
.getLogger (this
.getClass ())@Autowiredprivate RestTemplate restTemplate@RequestMapping(
"/" )public String home() {return
"Hello World!" }@RequestMapping(
"/next" )public String next(HttpServletRequest request, HttpServletResponse response) {String reqURL = request
.getRequestURI ()logger
.debug (
"reqURL:" +reqURL)return
"next!" }@RequestMapping(
"/reset" )@ResponseBodypublic Object reset(HttpServletRequest request, HttpServletResponse response) {String reqURL = request
.getRequestURI ()String queryString = request
.getQueryString ()String orgURI = (String)request
.getAttribute (
"requestURI" )logger
.debug (
"reqURL:" +reqURL)logger
.debug (
"queryString:" +queryString)//logger
.debug (
"orgURI:" +orgURI)String targetIP =
"http://172.17.7.113:1780" String targetURL = targetIP
.concat (orgURI)
.concat (
"?" )
.concat (queryString)logger
.debug (
"targetURL:" +targetURL)Enumeration<String> params = request
.getParameterNames ()Map<String,String> paramMap = new HashMap<String,String>()while(params
.hasMoreElements ()){String paraName = params
.nextElement ()paramMap
.put (paraName, request
.getParameter (paraName))} String json = restTemplate
.postForEntity (targetURL, paramMap, String
.class )
.getBody ()System
.out .println (json)return json}}
當(dāng)我請求http://localhost:8080/sub/aa?id=1,代碼restTemplate會(huì)幫我轉(zhuǎn)發(fā)到targetURL ,并轉(zhuǎn)發(fā)返回結(jié)果。
結(jié)論
當(dāng)前簡單的例子,還需要有所完善,比如說編碼問題,返回未json格式 該功能只能實(shí)現(xiàn)對前后臺有明確的ajax接口轉(zhuǎn)發(fā),具體的界面文件還不行,后面想繼續(xù)完善。
總結(jié)
以上是生活随笔 為你收集整理的用SpringBoot 做代web理服务器 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。