把spring-boot项目部署到外部tomcat环境下
想要把spring-boot
项目按照平常的web
项目一样发布到tomcat
容器下需要进行下列几个步骤:
一、修改打包形式
在pom.xml
里设置
<packaging>war</packaging>
二、移除嵌入式tomcat插件
在pom.xml
里找到spring-boot-starter-web
依赖节点,在其中进行如下修改:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 移除嵌入式tomcat插件 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
三、添加本地调试Tomcat
为了本地调试方便,在pom.xml
文件中,dependencies
下面添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
四、修改启动类,并重写初始化方法
我们平常用main
方法启动的方式,都有一个Application
的启动类,代码如下:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我们需要类似于web.xml
的配置方式来启动spring上下文,在Application
类的同级添加一个SpringBootStartApplication
类,其代码如下:
/**
* 修改启动类,继承 SpringBootServletInitializer 并重写 configure 方法
*/
public class SpringBootStartApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// 注意这里要指向原先用main方法执行的Application启动类
return builder.sources(Application.class);
}
}
五、打包部署
在项目根目录下(即包含pom.xml
的目录),在命令行里输入:
mvn clean package
即可, 等待打包完成,出现[INFO] BUILD SUCCESS
即为打包成功。然后把target
目录下的war包放到tomcat
的webapps
目录下,启动tomcat
,即可自动解压部署。 最后在浏览器中输入:
http://localhost:[端口号]/[打包项目名]/
发布成功。
六、总结
这样,只需要以上5步就可以打包成war
包,并且部署到tomcat
中了。需要注意的是这样部署的request url
需要在端口后加上项目的名字才能正常访问。spring-boot
更加强大的一点就是:即便项目是以上配置,依然可以用内嵌的tomcat来调试,启动命令和以前没变,还是:mvn spring-boot:run
。如果需要在springboot中加上request前缀,需要在application.properties
中添加server.contextPath=/prefix/
即可。其中prefix
为前缀名。这个前缀会在war
包中失效,取而代之的是war
包名称,如果war
包名称和prefix
相同的话,那么调试环境和正式部署环境就是一个request
地址了。
注意点:
我测试的时候,使用的相关环境版本如下:jdk:
jdk1.7.0_71
tomcat:
apache-tomcat-8.5.8
spring boot:
1.4.0.RELEASE
最开始我使用的spring boot
版本是1.3.0.RELEASE
,部署到tomcat
中出现找不到类等各种问题,后来把spring boot
版本升级。
接管Spring Boot的Web配置
如果Spring Boot提供的Spring MVC默认配置不符合你的要求,则可以通过一个配置类(注解有@Configuration
的类)加上@EnableWebMvc
注解来实现完全自己控制的MVC配置。
当然,通常情况下,Spring Boot的自动配置是符合我们的大多数需求的。在你既要保留Spring Boot提供的便利,又要增加自己的额外的配置的时候,可以定义一个配置类并继承WebMvcConfigureAdapter
,无须使用@EnableWebMvc
注解,然后参考之前讲解Spring MVC的文章SpringMvc4.x基本配置(四):快捷的ViewController来配置方法来添加Spring Boot为我们所做的其他配置,例如:
@Configuration
public class WebMvcConfig extends WebMvcConfigureAdapter{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("/index");
}
}
值得指出的,在这里重写addViewControllers
方法,并不会覆盖WebMvcAutoConfiguration
中的addViewController
,在此方法中,Spring Boot将”/index”映射至index.html,这也就意味着我们自己的配置和Spring Boot的自动配置同时有效,这也是我们推荐自己添加的MVC配置的方式。
注册Servlet,Filter,Listener
当使用嵌入式的Servlet
容器(Tomcat
,Jetty
等)时,我们通过将Servlet
,Filter
和Listener
声明为Spring Bean而达到注册的效果;或者注册ServletRegistrationBean
,FilterRegistrationBean
,ServletListenerRegistrationBean
的Bean。
1. 直接注册Bean示例,代码如下:
@Bean
public XxServlet xxServlet(){
return new XxServlet;
}
@Bean
public YyFilteryyFilter(){
return new YyFilter;
}
@Bean
public ZzListener zzListener (){
return new ZzListener ;
}
2.通过RegistrationBean示例
@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new XxServlet(),"/xx/*");
}
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new YyFilter());
registrationBean.setOrder(2);
return registrationBean;
}
@Bean
public ServletListenerRegistrationBean<ZzListener> zzListenerRegistrationBean(){
return new ServletListenerRegistrationBean<ZzListener>(new ZzListener());
}
spring-boot jar方式启动,切换到后台运行
spring-boot jar 包方式启动:
平时进行测试的时候,启动方式如下:
Java -jar xxx.jar
然而,上面的这种方式,只要控制台关闭,服务就不能访问了。下面我们使得 jar 包在后台运行。
java -jar xxx.jar &
如果这个时候,想要关掉后台运行的Spring Boot的服务,要这样做:
ps aux | grep spring | xargs kill -9
Tomcat配置和Tomcat替换
下面虽然要说的是Tomcat
的配置,但其实对Tomcat
,Jetty
和Undertow
都是通用的。
一. 配置Tomcat
—-关于Tomcat的所有属性都在org.springframework.boot.autoconfigure.web.ServerProperties
配置类中做了定义,我们只需要在application.properties
配置属性做配置即可。通用的Servlet容器配置都以”server”作为前缀,而Tomcat特有配置都以”server.tomcat
“作为前缀。下面举些常用的例子:
1. 配置Servlet容器
server.port= #配置程序端口,默认为8080
server.session-timeout= #用户会话session过期时间,以秒为单位
server.context-path= #配置访问路径,默认为/
2.配置Tomcat
server.tomcat.uri-encoding= #配置Tomcat编码,默认为UTF-8
server.tomcat.compression= #Tomcat是否开启压缩,默认为关闭off
更为详细的Servlet容器配置以及Tomcat配置,请查看官网文档。
二. 代码配置Tomcat
如果需要通过代码的方式配置servlet
容器,则可以注册一个实现EmbeddedServletContainerCustomizer
接口的Bean;若想直接配置Tomcat
,Jetty
,Undertow
,则可以直接定义TomcatEmbeddedServletContainerFactory
,JettyEmbeddedServletContainerFactory
,UndertowEmbeddedServletContainerFactory
。
1. 通用配置
1.1 新建类的配置
package org.light4j.springBoot.web.tomcat;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class CustomServletContainer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(8888);
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
container.setSessionTimeout(10, TimeUnit.MINUTES);
}
}
1.2 当前配置文件的配置。
若要在当前已有的配置文件内部添加类的Bean的话,则在Spring配置中,注意当前类要声明为static
:
package org.light4j.springBoot.web.tomcat;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
@Component
public static class CustomServletContainer implements EmbeddedServletContainerCustomizer{
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(8888);//①
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));//②
container.setSessionTimeout(10,TimeUnit.MINUTES);//③
}
}
}
2. 特定配置
下面以Tomcat为例,(Jetty
使用JettyEmbeddedServletContainerFactory
,Undertow
使用UndertowEmbeddedServletContainerFactory
):
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setPort(8888);//①
factory.setSessionTimeout(10, TimeUnit.MINUTES);
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));//②
return factory;//③
}
代码解释:
上面两个例子的代码都实现了这些功能:
① 配置端口号
② 配置错误页面,根据HttpStatus
中的错误状态信息,直接转向错误页面,其中404.html
放置在src/main/resources/static
下即可。
③ 配置Servlet容器用户会话(session
)过期时间。
二. 替换Tomcat
Spring Boot默认使用Tomcat
作为内嵌的Servlet容器,查看spring-boot-starter-web
依赖,如下图所示:
如果要使用Jetty
或者Undertow
为Servlet容器,只需修改spring-boot-starter-web
即可。
1. 替换为Jetty
在pom.xml中,将spring-boot-starter-web
的依赖由spring-boot-starter-tomcat
替换为spring-boot-starter-Jetty
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
此时启动Spring Boot
,控制台输出效果如下图所示:
2. 替换为Undertow
在pom.xml中,将spring-boot-starter-web
的依赖由spring-boot-starter-tomcat
替换为spring-boot-starter-undertow
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
SSL配置
SSL
的配置也是我们在实际应用中经常遇到的场景。SSL
(Secure Sockets Layer
),安全套接层)是为网络通信提供安全以及数据完整性的一种安全协议,SSL
在网络传输层对网络连接进行加密。SSL协议位于TCP/IP协议与各种应用层协议之间,为数据通信提供安全支持。SSL协议可以分为两层:SSL记录协议(SSL Record Protocol
),它建立在可靠的传输协议(如TCP
)之上,为高层协议提供数据封装,压缩,加密等基本功能的支持。SSL握手协议(SSL Handshaker Protocol
),它建立在SSL记录协议之上,用于在实际数据传输开始前,通信双方进行身份认证,协商加密算法,交换加密密钥等。SSL的加密过程如下图所示:
而在基于B/S
的Web应用中,是通过HTTPS
来实现SSL的。HTTPS
是以安全为目标的HTTP通道,简单讲是HTTP
的安全版,即在HTTP下加入SSL
层,HTTPS
的安全基础设施是SSL。
因为Spring Boot用的是内嵌的Tomcat
,因而需要做SSL配置的时候需要做如下的操作/
1. 生成证书
使用SSL首先需要一个证书,这个证书既可以是自签名的,也可以是从SSL证书授权中心获得的。下面为了演示方便,演示自授权证书的生成。
每个JDK
或者JRE
里面都有一个工具叫keytool
,它是一个证书管理工具,可以用来生成自签名的证书,
jdk的bin目录,如下图所示:
jre的bin目录如下图所示:
在配置了JAVA_HOME
,并将JAVA_HOME
的bin
目录加入到Path后,即可在控制台使用该命令,如下图所示:
在控制台输入如下命令,然后按照提示操作,如下图所示:
keytool -genkey -alias tomcat
这时候就在当前目录下生成了一个.keystore
文件,这就是我们要用到的证书文件,如下图所示:
2.Spring Boot配置SSL
添加一个index.html
到src/main/resources/static下,作为测试。
将.keystore
文件复制到项目的根目录下,然后在application.properties
中做如下的SSL配置:
server.port = 8443
server.ssl.key-store = .keystore
server.ssl.key-store-password= 123456
server.ssl.keyStoreType= JKS
server.ssl.keyAlias: tomcat
此时启动Spring Boot,控制台输出效果如下图所示:
此时访问:https://localhost:8443,效果如下图所示:
3. http转向https
很多时候我们在地址栏输入的是http,但是会自动转向到https,例如我们访问百度的时候,如下图所示:
要实现这个功能,需要配置TomcatEmbeddedServletContainerFactory
,并且添加Tomcat的connector来实现。
这时候代码需要做如下的配置编写:
package org.light4j.springBoot.web.ssl;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoSSLApplication {
public static void main(String[] args) {
SpringApplication.run(DemoSSLApplication.class, args);
}
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
此时启动Spring Boot,控制台输出效果如下图所示:
Favicon配置
一. 默认的Favicon
Spring Boot
提供了一个默认的Favicon
,每次访问应用的时候都能看到,如下图所示:
二. 关闭Favicon
我们可以在application.properties
中设置关闭Favicon,默认为开启,如下图所示:
spring.mvc.favicon.enabled=false
三.设置自己的Favicon
若需要设置自己的Favicon,则只需要将自己的favicon.ico
(文件名不能变动)文件放置在类路径根目录,类路径/META-INF/resources/
下,类路径resources/下,类路径static/
下或类路径public/
下。这里将favicon.ico
放置在src/main/resources/static
下