基于Java的深入微服务原理改造房产销售平台
--------3、引入内嵌容器
1、引入Tomcat:直接引入spring-boot-starter-web,默认Tomcat
2、引入jetty:还需添加spring-boot-starter-jetty,并移除starter-tomcat
package com.mooc.house.fliter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ResourceProperties.Chain;
public class LogFilter implements Filter {
private Logger logger = LoggerFactory.getLogger(LogFilter.class);
public void init(FilterConfig filterConfig) throws ServletException{
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info(“Request–coming”);
chain.doFilter(request, response);
}
public void destroy(){
}
}
package com.mooc.house.fliter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ch.qos.logback.core.filter.Filter;
@Configuration
public class FilterBeanConfig {
/**
* 1.构造filter
* 2.配置拦截urlPattern
* 3.利用FilterRedistrationBean进行包装
* @return
/
@SuppressWarnings(“unchecked”)
@Bean
public FilterRegistrationBean logFilter(){
FilterRegistrationBean<javax.servlet.Filter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new LogFilter());
List urList = new ArrayList();
urList.add("");
filterRegistrationBean.setUrlPatterns(urList);
return filterRegistrationBean;
}
}
运行application
3、内嵌容器的优势
(1)减少外部容器依赖,可移植性高
(2)易测试易部署
(3)Spring boot提供了可插拔的内嵌容器方案
4、Tomcat容器切换jetty
Spring网址:http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#howto-use-jetty-instead-of-tomcat
把pom.xml中的spring-boot-starter-web替换成文中图片
5、浏览器查看是否成功