Chuyển tới nội dung
Home » Spring Boot Tomcat Maven | Common Embedded Tomcat Configurations

Spring Boot Tomcat Maven | Common Embedded Tomcat Configurations

Maven - How to integrate Apache Tomcat in IntelliJ IDEA and deploy a WAR file

Compile Dependencies (4)

Category/License Group / Artifact Version Updates
Annotation Lib

EPL 2.0GPL

jakarta.annotation » jakarta.annotation-api 1.3.5 2.1.1
Web Server

Apache 2.0

org.apache.tomcat.embed » tomcat-embed-core5 vulnerabilities 9.0.46 10.1.18

Apache 2.0

org.apache.tomcat.embed » tomcat-embed-el 9.0.46 10.1.18

Apache 2.0

org.apache.tomcat.embed » tomcat-embed-websocket 9.0.46 10.1.18

Introduction

Spring Boot is a convention over configuration framework that allows us to create a production-ready setup of a Spring project, and Tomcat is one of the most popular Java Servlet Containers.

By default, Spring Boot builds a standalone Java application that can run as a desktop application or be configured as a system service, but there are environments where we can’t install a new service or run the application manually.

In contrast to standalone applications, Tomcat is installed as a service that can manage multiple applications within the same application process, avoiding the need for a specific setup for each application.

In this tutorial, we’ll create a simple Spring Boot application and adapt it to work within Tomcat.

Maven - How to integrate Apache Tomcat in IntelliJ IDEA and deploy a WAR file
Maven – How to integrate Apache Tomcat in IntelliJ IDEA and deploy a WAR file

XML


dependency


groupId


>org.springframework.boot


groupId


artifactId


>spring-boot-starter-tomcat


artifactId


version


>2.0.0.RELEASE


version


scope


>compile


scope




dependency

The spring-boot-starter-web auto-configures the below things required for the web development:

  • Dispatcher Servlet
  • Error Page
  • Embedded servlet container
  • Web JARs for managing the static dependencies

Spring Boot also supports Jetty Server and Undertow Server. They are embedded web servers. We can also exclude spring-boot-starter-tomcat from spring-boot-starter-web as follows:

XML


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

Spring Boot Starter Tomcat

While the spring-boot-starter-tomcat has everything related to the Tomcat server. It has

It has the below dependencies

How to deploy a Maven Spring Boot Tomcat application to railway.app
How to deploy a Maven Spring Boot Tomcat application to railway.app

Deploying the WAR to Tomcat

To have our WAR file deployed and running in Tomcat, we’ll need to complete the following steps:

  1. Download Apache Tomcat and unpackage it into a tomcat folder
  2. Copy our WAR file from target/spring-boot-deployment.war to the tomcat/webapps/ folder
  3. From a terminal, navigate to the tomcat/bin folder and execute

    1. catalina.bat run (on Windows)
    2. catalina.sh run (on Unix-based systems)
  4. Go to http://localhost:8080/spring-boot-deployment/hello

This has been a quick Tomcat setup, so please check the guide on Tomcat Installation for a complete setup guide. There are also additional ways of deploying a WAR file to Tomcat.

Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web

Version Vulnerabilities Repository Usages Date

3.2.x

3.2.2 Central Jan 19, 2024
3.2.1 Central Dec 21, 2023
3.2.0 Central Nov 23, 2023

3.1.x

3.1.8 Central Jan 19, 2024
3.1.7 Central Dec 21, 2023
3.1.6 Central Nov 23, 2023
3.1.5 Central Oct 19, 2023
3.1.4 Central Sep 21, 2023
3.1.3 Central Aug 24, 2023
3.1.2 Central Jul 20, 2023
3.1.1 Central Jun 22, 2023
3.1.0 Central May 19, 2023

3.0.x

3.0.13 Central Nov 23, 2023
3.0.12 Central Oct 19, 2023
3.0.11 Central Sep 21, 2023
3.0.10 Central Aug 24, 2023
3.0.9 Central Jul 20, 2023
3.0.8 Central Jun 22, 2023
3.0.7 Central May 18, 2023
3.0.6 Central Apr 20, 2023
3.0.5 Central Mar 23, 2023
3.0.4 Central Mar 03, 2023
3.0.3 Central Feb 23, 2023
3.0.2 Central Jan 20, 2023
3.0.1 Central Dec 23, 2022
3.0.0 Central Nov 24, 2022

2.7.x

2.7.18 Central Nov 23, 2023
2.7.17 Central Oct 19, 2023
2.7.16 Central Sep 21, 2023
2.7.15 Central Aug 24, 2023
2.7.14 Central Jul 20, 2023
2.7.13 Central Jun 22, 2023
2.7.12 Central May 18, 2023
2.7.11 Central Apr 20, 2023
2.7.10 Central Mar 23, 2023
2.7.9 Central Feb 23, 2023
2.7.8 Central Jan 19, 2023
2.7.7 Central Dec 22, 2022
2.7.6 Central Nov 24, 2022
2.7.5 Central Oct 20, 2022
2.7.4 Central Sep 22, 2022
2.7.3 Central Aug 18, 2022
2.7.2 Central Jul 21, 2022
2.7.1 Central Jun 23, 2022
2.7.0 Central May 19, 2022

2.6.x

2.6.15 Central May 18, 2023
2.6.14 Central Nov 24, 2022
2.6.13 Central Oct 20, 2022
2.6.12 Central Sep 22, 2022
2.6.11 Central Aug 18, 2022
2.6.10 Central Jul 21, 2022
2.6.9 Central Jun 23, 2022
2.6.8 Central May 19, 2022
2.6.7 Central Apr 21, 2022
2.6.6 Central Mar 31, 2022
2.6.5 Central Mar 24, 2022
2.6.4 Central Feb 24, 2022
2.6.3 Central Jan 20, 2022
2.6.2 Central Dec 22, 2021
2.6.1 Central Nov 29, 2021
2.6.0 Central Nov 19, 2021

2.5.x

2.5.15 Central May 18, 2023
2.5.14 Central May 19, 2022
2.5.13 Central Apr 21, 2022
2.5.12 Central Mar 31, 2022
2.5.11 Central Mar 24, 2022
2.5.10 Central Feb 24, 2022
2.5.9 Central Jan 20, 2022
2.5.8 Central Dec 21, 2021
2.5.7 Central Nov 18, 2021
2.5.6 Central Oct 21, 2021
2.5.5 Central Sep 23, 2021
2.5.4 Central Aug 19, 2021
2.5.3 Central Jul 22, 2021
2.5.2 Central Jun 25, 2021
2.5.1 Central Jun 10, 2021
2.5.0 Central May 22, 2021

2.4.x

2.4.13 Central Nov 18, 2021
2.4.12 Central Oct 21, 2021
2.4.11 Central Sep 23, 2021
2.4.10 Central Aug 19, 2021
2.4.9 Central Jul 22, 2021
2.4.8 Central Jun 24, 2021
2.4.7 Central Jun 10, 2021
2.4.6 Central May 21, 2021
2.4.5 Central Apr 15, 2021
2.4.4 Central Mar 18, 2021
2.4.3 Central Feb 18, 2021
2.4.2 Central Jan 15, 2021
2.4.1 Central Dec 11, 2020
2.4.0 Central Nov 12, 2020

2.3.x

2.3.12.RELEASE Central Jun 10, 2021
2.3.11.RELEASE Central May 21, 2021
2.3.10.RELEASE Central Apr 15, 2021
2.3.9.RELEASE Central Feb 18, 2021
2.3.8.RELEASE Central Jan 15, 2021
2.3.7.RELEASE Central Dec 11, 2020
2.3.6.RELEASE Central Dec 10, 2020
2.3.5.RELEASE Central Oct 31, 2020
2.3.4.RELEASE Central Sep 17, 2020
2.3.3.RELEASE Central Aug 13, 2020
2.3.2.RELEASE Central Jul 24, 2020
2.3.1.RELEASE Central Jun 12, 2020
2.3.0.RELEASE Central May 15, 2020

2.2.x

2.2.13.RELEASE Central Jan 14, 2021
2.2.12.RELEASE Central Dec 10, 2020
2.2.11.RELEASE Central Oct 31, 2020
2.2.10.RELEASE Central Sep 17, 2020
2.2.9.RELEASE Central Jul 24, 2020
2.2.8.RELEASE Central Jun 11, 2020
2.2.7.RELEASE Central May 07, 2020
2.2.6.RELEASE Central Mar 26, 2020
2.2.5.RELEASE Central Feb 27, 2020
2.2.4.RELEASE Central Jan 20, 2020
2.2.3.RELEASE Central Jan 16, 2020
2.2.2.RELEASE Central Dec 06, 2019
2.2.1.RELEASE Central Nov 06, 2019
2.2.0.RELEASE Central Oct 16, 2019

2.1.x

2.1.18.RELEASE Central Oct 29, 2020
2.1.17.RELEASE Central Sep 17, 2020
2.1.16.RELEASE Central Jul 24, 2020
2.1.15.RELEASE Central Jun 11, 2020
2.1.14.RELEASE Central May 07, 2020
2.1.13.RELEASE Central Feb 27, 2020
2.1.12.RELEASE Central Jan 16, 2020
2.1.11.RELEASE Central Dec 06, 2019
2.1.10.RELEASE Central Nov 06, 2019
2.1.9.RELEASE Central Oct 02, 2019
2.1.8.RELEASE Central Sep 06, 2019
2.1.7.RELEASE Central Aug 06, 2019
2.1.6.RELEASE Central Jun 19, 2019
2.1.5.RELEASE Central May 15, 2019
2.1.4.RELEASE Central Apr 04, 2019
2.1.3.RELEASE Central Feb 15, 2019
2.1.2.RELEASE Central Jan 12, 2019
2.1.1.RELEASE Central Nov 30, 2018
2.1.0.RELEASE Central Oct 30, 2018

2.0.x

2.0.9.RELEASE Central Apr 03, 2019
2.0.8.RELEASE Central Jan 12, 2019
2.0.7.RELEASE Central Nov 30, 2018
2.0.6.RELEASE Central Oct 16, 2018
2.0.5.RELEASE Central Sep 12, 2018
2.0.4.RELEASE Central Jul 30, 2018
2.0.3.RELEASE Central Jun 14, 2018
2.0.2.RELEASE Central May 09, 2018
2.0.1.RELEASE Central Apr 05, 2018
2.0.0.RELEASE Central Mar 01, 2018

1.5.x

1.5.22.RELEASE Central Aug 06, 2019
1.5.21.RELEASE Central May 14, 2019
1.5.20.RELEASE Central Apr 03, 2019
1.5.19.RELEASE Central Jan 11, 2019
1.5.18.RELEASE Central Nov 29, 2018
1.5.17.RELEASE Central Oct 16, 2018
1.5.16.RELEASE Central Sep 11, 2018
1.5.15.RELEASE Central Jul 30, 2018
1.5.14.RELEASE Central Jun 14, 2018
1.5.13.RELEASE Central May 09, 2018
1.5.12.RELEASE Central Apr 10, 2018
1.5.11.RELEASE Central Apr 05, 2018
1.5.10.RELEASE Central Jan 31, 2018
1.5.9.RELEASE Central Nov 28, 2017
1.5.8.RELEASE Central Oct 17, 2017
1.5.7.RELEASE Central Sep 12, 2017
1.5.6.RELEASE Central Jul 27, 2017
1.5.5.RELEASE Central Jul 26, 2017
1.5.4.RELEASE Central Jun 08, 2017
1.5.3.RELEASE Central Apr 21, 2017
1.5.2.RELEASE Central Mar 03, 2017
1.5.1.RELEASE Central Jan 30, 2017
1.5.0.RELEASE Central Jan 30, 2017

1.4.x

1.4.7.RELEASE Central Jun 08, 2017
1.4.6.RELEASE Central Apr 20, 2017
1.4.5.RELEASE Central Mar 03, 2017
1.4.4.RELEASE Central Jan 26, 2017
1.4.3.RELEASE Central Dec 23, 2016
1.4.2.RELEASE Central Nov 08, 2016
1.4.1.RELEASE Central Sep 21, 2016
1.4.0.RELEASE Central Jul 28, 2016

1.3.x

1.3.8.RELEASE Central Sep 20, 2016
1.3.7.RELEASE Central Jul 28, 2016
1.3.6.RELEASE Central Jul 04, 2016
1.3.5.RELEASE Central May 10, 2016
1.3.4.RELEASE Central May 06, 2016
1.3.3.RELEASE Central Feb 26, 2016
1.3.2.RELEASE Central Jan 22, 2016
1.3.1.RELEASE Central Dec 18, 2015
1.3.0.RELEASE Central Nov 16, 2015

1.2.x

1.2.8.RELEASE Central Dec 17, 2015
1.2.7.RELEASE Central Oct 16, 2015
1.2.6.RELEASE Central Sep 16, 2015
1.2.5.RELEASE Central Jul 02, 2015
1.2.4.RELEASE Central Jun 04, 2015
1.2.3.RELEASE Central Mar 31, 2015
1.2.2.RELEASE Central Feb 27, 2015
1.2.1.RELEASE Central Jan 08, 2015
1.2.0.RELEASE Central Dec 11, 2014

1.1.x

1.1.12.RELEASE Central Mar 31, 2015
1.1.11.RELEASE Central Feb 26, 2015
1.1.10.RELEASE Central Dec 11, 2014
1.1.9.RELEASE Central Nov 12, 2014
1.1.8.RELEASE Central Oct 10, 2014
1.1.7.RELEASE Central Sep 26, 2014
1.1.6.RELEASE Central Sep 04, 2014
1.1.5.RELEASE Central Aug 07, 2014
1.1.4.RELEASE Central Jul 08, 2014
1.1.3.RELEASE Central Jun 27, 2014
1.1.2.RELEASE Central Jun 24, 2014
1.1.1.RELEASE Central Jun 11, 2014
1.1.0.RELEASE Central Jun 10, 2014

1.0.x

1.0.2.RELEASE Central Apr 24, 2014
1.0.1.RELEASE Central Apr 07, 2014
1.0.0.RELEASE Central Apr 01, 2014

The Spring Boot starters bring a default embedded container for you:


spring-boot-starter-webbrings Tomcat with


spring-boot-starter-tomcat, but


spring-boot-starter-jettyand


spring-boot-starter-undertowcan be used instead.


spring-boot-starter-webfluxbrings Reactor Netty with


spring-boot-starter-reactor-netty, but


spring-boot-starter-tomcat,


spring-boot-starter-jettyand


spring-boot-starter-undertowcan be used instead.

Note

Many starters only support Spring MVC, so they transitively bring

If you choose to use a different HTTP server, you need to exclude those dependencies and include the one you chose instead. Spring Boot provides separate starters for HTTP servers to help make this process as easy as possible.

Example in Maven, for Spring MVC:



org.springframework.boot


spring-boot-starter-web





org.springframework.boot


spring-boot-starter-tomcat







org.springframework.boot


spring-boot-starter-jetty

Example in Gradle, for Spring WebFlux:

configurations { // exclude Reactor Netty compile.exclude module: ‘spring-boot-starter-reactor-netty’ } dependencies { compile ‘org.springframework.boot:spring-boot-starter-webflux’ // Use Undertow instead compile ‘org.springframework.boot:spring-boot-starter-undertow’ // … }

Note

Generally you can follow the advice from
Section 73.8, “Discover built-in options for external properties” about

@ConfigurationProperties

(

ServerProperties

is the main one here), but also look at

ServletWebServerFactoryCustomizer

. The Jetty APIs are quite rich so once you have
access to the

JettyServletWebServerFactory

you can modify it in a number
of ways. Or the nuclear option is to add your own

JettyServletWebServerFactory

.

There are two ways to add

Servlet

,

Filter

,

ServletContextListener

and the other
listeners supported by the Servlet spec to your application. You can either provide
Spring beans for them, or enable scanning for Servlet components.

To add a

Servlet

,

Filter

, or Servlet

*Listener

provide a

@Bean

definition for it.
This can be very useful when you want to inject configuration or dependencies. However,
you must be very careful that they don’t cause eager initialization of too many other
beans because they have to be installed in the container very early in the application
lifecycle (e.g. it’s not a good idea to have them depend on your

DataSource

or JPA
configuration). You can work around restrictions like that by initializing them lazily
when first used instead of on initialization.

In the case of

Filters

and

Servlets

you can also add mappings and init parameters by
adding a

FilterRegistrationBean

or

ServletRegistrationBean

instead of or as well as
the underlying component.

Note

If no

If you are migrating a filter that has no

@Bean public FilterRegistrationBean myFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setDispatcherTypes(DispatcherType.REQUEST); …. return registration; }

As described above any

Servlet

or

Filter

beans will be registered with the servlet container automatically. To disable
registration of a particular

Filter

or

Servlet

bean create a registration bean for it
and mark it as disabled. For example:

@Bean public FilterRegistrationBean registration(MyFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(filter); registration.setEnabled(false); return registration; }


@WebServlet

,

@WebFilter

, and

@WebListener

annotated classes can be automatically
registered with an embedded servlet container by annotating a

@Configuration

class
with

@ServletComponentScan

and specifying the package(s) containing the components
that you want to register. By default,

@ServletComponentScan

will scan from the package
of the annotated class.

In a standalone application the main HTTP port defaults to

8080

, but can be set with

server.port

(e.g. in

application.properties

or as a System property). Thanks to
relaxed binding of

Environment

values you can also use

SERVER_PORT

(e.g. as an OS
environment variable).

To switch off the HTTP endpoints completely, but still create a

WebApplicationContext

,
use

server.port=-1

(this is sometimes useful for testing).

For more details look at Section 27.4.4, “Customizing embedded servlet containers”
in the ‘Spring Boot features’ section, or the

ServerProperties

source
code.

To scan for a free port (using OS natives to prevent clashes) use

server.port=0

.

You can access the port the server is running on from log output or from the

ServletWebServerApplicationContext

via its

EmbeddedWebServer

. The best way to get
that and be sure that it has initialized is to add a

@Bean

of type

ApplicationListener

and pull the container
out of the event when it is published.

Tests that use

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

can
also inject the actual port into a field using the

@LocalServerPort

annotation. For
example:

@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) public class MyWebIntegrationTests { @Autowired ServletWebServerApplicationContext server; @LocalServerPort int port; // … }

Note

SSL can be configured declaratively by setting the various

server.ssl.*

properties,
typically in

application.properties

or

application.yml

. For example:

server.port=8443 server.ssl.key-store=classpath:keystore.jks server.ssl.key-store-password=secret server.ssl.key-password=another-secret

See

Ssl

for details of all of the
supported properties.

Using configuration like the example above means the application will no longer support
plain HTTP connector at port 8080. Spring Boot doesn’t support the configuration of both
an HTTP connector and an HTTPS connector via

application.properties

. If you want to
have both then you’ll need to configure one of them programmatically. It’s recommended
to use

application.properties

to configure HTTPS as the HTTP connector is the easier of
the two to configure programmatically. See the

spring-boot-sample-tomcat-multi-connectors

sample project for an example.

Access logs can be configured for Tomcat, Undertow and Jetty via their respective namespaces.

For instance, the following logs access on Tomcat with a custom pattern.

server.tomcat.basedir=my-tomcat server.tomcat.accesslog.enabled=true server.tomcat.accesslog.pattern=%t %a “%r” %s (%D ms)

Note

The default location for logs is a

Access logging for undertow can be configured in a similar fashion

server.undertow.accesslog.enabled=true server.undertow.accesslog.pattern=%t %a “%r” %s (%D ms)

Logs are stored in a

logs

directory relative to the working directory of the
application. This can be customized via

server.undertow.accesslog.directory

.

Finally, access logging for jetty can also be configured that way:

server.jetty.accesslog.enabled=true server.jetty.accesslog.filename=/var/log/jetty-access.log

By default, logs will be redirected to

System.err

. For more details, please refer to
the documentation.

Your application might need to send

302

redirects or render content with absolute links
back to itself. When running behind a proxy, the caller wants a link to the proxy, and not
to the physical address of the machine hosting your app. Typically such situations are
handled via a contract with the proxy, which will add headers to tell the back end how to
construct links to itself.

If the proxy adds conventional

X-Forwarded-For

and

X-Forwarded-Proto

headers (most do
this out of the box) the absolute links should be rendered correctly as long as

server.use-forward-headers

is set to

true

in your

application.properties

.

Note

If your application is running in Cloud Foundry or Heroku the

If you are using Tomcat you can additionally configure the names of the headers used to carry “forwarded” information:

server.tomcat.remote-ip-header=x-your-remote-ip-header server.tomcat.protocol-header=x-your-protocol-header

Tomcat is also configured with a default regular expression that matches internal
proxies that are to be trusted. By default, IP addresses in

10/8

,

192.168/16

,

169.254/16

and

127/8

are trusted. You can customize the valve’s configuration by
adding an entry to

application.properties

, e.g.

server.tomcat.internal-proxies=192\\.168\\.\\d{1,3}\\.\\d{1,3}

Note

The double backslashes are only required when you’re using a properties file for
configuration. If you are using YAML, single backslashes are sufficient and a value
that’s equivalent to the one shown above would be

Note

You can trust all proxies by setting the

You can take complete control of the configuration of Tomcat’s

RemoteIpValve

by
switching the automatic one off (i.e. set

server.use-forward-headers=false

) and adding
a new valve instance in a

TomcatServletWebServerFactory

bean.

Generally you can follow the advice from
Section 73.8, “Discover built-in options for external properties” about

@ConfigurationProperties

(

ServerProperties

is the main one here), but also look at

ServletWebServerFactoryCustomizer

and various Tomcat-specific

*Customizers

that you
can add in one of those. The Tomcat APIs are quite rich so once you have access to the

TomcatServletWebServerFactory

you can modify it in a number of ways. Or the
nuclear option is to add your own

TomcatServletWebServerFactory

.

Add an

org.apache.catalina.connector.Connector

to the

TomcatServletWebServerFactory

which can allow multiple connectors, e.g. HTTP and
HTTPS connector:

@Bean public ServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addAdditionalTomcatConnectors(createSslConnector()); return tomcat; } private Connector createSslConnector() { Connector connector = new Connector(“org.apache.coyote.http11.Http11NioProtocol”); Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler(); try { File keystore = new ClassPathResource(“keystore”).getFile(); File truststore = new ClassPathResource(“keystore”).getFile(); connector.setScheme(“https”); connector.setSecure(true); connector.setPort(8443); protocol.setSSLEnabled(true); protocol.setKeystoreFile(keystore.getAbsolutePath()); protocol.setKeystorePass(“changeit”); protocol.setTruststoreFile(truststore.getAbsolutePath()); protocol.setTruststorePass(“changeit”); protocol.setKeyAlias(“apitester”); return connector; } catch (IOException ex) { throw new IllegalStateException(“can’t access keystore: [” + “keystore” + “] or truststore: [” + “keystore” + “]”, ex); } }

The embedded Tomcat used by Spring Boot does not support “Version 0” of the Cookie format out of the box, and you may see the following error:

java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value

If at all possible, you should consider updating your code to only store values
compliant with later Cookie specifications. If, however, you’re unable to change the
way that cookies are written, you can instead configure Tomcat to use a

LegacyCookieProcessor

. To switch to the

LegacyCookieProcessor

use an

ServletWebServerFactoryCustomizer

bean that adds a

TomcatContextCustomizer

:

@Bean public WebServerFactoryCustomizer

cookieProcessorCustomizer() { return (serverFactory) -> serverFactory.addContextCustomizers( (context) -> context.setCookieProcessor(new LegacyCookieProcessor())); }

Generally you can follow the advice from
Section 73.8, “Discover built-in options for external properties” about

@ConfigurationProperties

(

ServerProperties

and

ServerProperties.Undertow

are the
main ones here), but also look at

ServletWebServerFactoryCustomizer

. Once you have access to the

UndertowServletWebServerFactory

you can use an

UndertowBuilderCustomizer

to
modify Undertow’s configuration to meet your needs. Or the nuclear option is to add your
own

UndertowServletWebServerFactory

.

Add an

UndertowBuilderCustomizer

to the

UndertowServletWebServerFactory

and
add a listener to the

Builder

:

@Bean public UndertowServletWebServerFactory servletWebServerFactory() { UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory(); factory.addBuilderCustomizers(new UndertowBuilderCustomizer() { @Override public void customize(Builder builder) { builder.addHttpListener(8080, “0.0.0.0”); } }); return factory; }

If you want to use

@ServerEndpoint

in a Spring Boot application that used an embedded
container, you must declare a single

ServerEndpointExporter


@Bean

:

@Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }

This bean will register any

@ServerEndpoint

annotated beans with the underlying
WebSocket container. When deployed to a standalone servlet container this role is
performed by a servlet container initializer and the

ServerEndpointExporter

bean is
not required.

HTTP response compression is supported by Jetty, Tomcat, and Undertow. It can be enabled
via

application.properties

:

server.compression.enabled=true

By default, responses must be at least 2048 bytes in length for compression to be
performed. This can be configured using the

server.compression.min-response-size

property.

By default, responses will only be compressed if their content type is one of the following:


text/html


text/xml


text/plain


text/css

This can be configured using the

server.compression.mime-types

property.

Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web

License Apache 2.0
Tags serverspringwebserverframeworktomcatstarter
Organization Pivotal Software, Inc.
HomePage https://spring.io/projects/spring-boot
Date May 22, 2021
Files pom (3 KB) jar (4 KB) View All
Repositories CentralMulesoft
Ranking #723 in MvnRepository (See Top Artifacts)
Used By 664 artifacts
Vulnerabilities Vulnerabilities from dependencies:

CVE-2023-46589

CVE-2023-45648

CVE-2023-44487

View 2 more …

Note: There is a new version for this artifact

New Version 3.2.2

Technical details about the provided scope in Maven dependency management

There is one more devilish detail that I discovered when we packaged this Spring Boot application.

I originally thought that as long as the dependent package was set to


provided


, it would only be used during

compile

and

test

, but not actually loaded during

runtime

. So if it won’t be loaded, shouldn’t it theoretically be excluded from the final package

*.war

file, so that the overall file size of

*.war

can be reduced and deployed more quickly?

I found that the size of the overall

*.war

file does not decrease at all, and all Tomcat Embedded related files are still packed in.

I also found that the

app1.war

file can not only be deployed to the Tomcat application server, but it can also be run independently via

java -jar app1.war

. In fact, it is quite convenient to think about this design, you can run it locally at any time and deploy it remotely at the same time, but the only drawback is that the file is relatively large.

I’ve spent a lot of time trying to automatically exclude Tomcat Embedded related files through the Maven build process. Then I found a way to “skip the

spring-boot-maven-plugin

plugin to execute the

repackage

target”. You just need to adjust the

spring-boot-maven-plugin

plugin settings.

If you want to switch the settings automatically via Spring Profiles, the complete settings are as follows.

From now on, you can run different commands and generate different WAR files based on different profiles.

  1. To build the WAR file for the test environment, you can execute the following command.


    mvn clean package

    The output of


    app1.war

    is about 17MB in size

  2. To build a WAR file for the production environment, you can run the following command.


    mvn clean package -Pprod

    The output of


    app1.war

    is about 12MB in size

Deploying Spring Boot application on External Tomcat Server | Spring Boot tutorial
Deploying Spring Boot application on External Tomcat Server | Spring Boot tutorial

Developers

Name Dev Id Roles Organization
Pivotal info

pivotal.io
Pivotal Software, Inc.

spring-boot-starter-tomcat

Used in

components

  • OverviewOverview
  • VersionsVersions
  • DependentsDependents
  • DependenciesDependencies



org.springframework.boot


spring-boot-starter-tomcat


3.2.2







4.0.0


org.springframework.boot


spring-boot-starter-tomcat


3.2.2


spring-boot-starter-tomcat


Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web


https://spring.io/projects/spring-boot



VMware, Inc.


https://spring.io


Apache License, Version 2.0


https://www.apache.org/licenses/LICENSE-2.0



Spring


[email protected]


VMware, Inc.


https://www.spring.io





scm:git:git://github.com/spring-projects/spring-boot.git


scm:git:ssh://[email protected]/spring-projects/spring-boot.git


https://github.com/spring-projects/spring-boot




GitHub


https://github.com/spring-projects/spring-boot/issues





jakarta.annotation


jakarta.annotation-api


2.1.1


compile




org.apache.tomcat.embed


tomcat-embed-core


10.1.18


compile




tomcat-annotations-api


org.apache.tomcat






org.apache.tomcat.embed


tomcat-embed-el


10.1.18


compile




org.apache.tomcat.embed


tomcat-embed-websocket


10.1.18


compile




tomcat-annotations-api


org.apache.tomcat




Embedded Tomcat’s Version

We can’t change Tomcat’s version being used by configuring our application.properties file. It’s a bit more complicated and mainly depends on whether we use spring-boot-starter-parent or not.

Before we proceed, however, we must be aware that each Spring Boot release is designed and tested against the specific Tomcat version. If we change it, we may face some unexpected compatibility issues.

3.Using spring-boot-starter-parent

If we use Maven and configure our project to inherit from the spring-boot-starter-parent, we can override individual dependencies by overwriting a specific property in our pom.xml.

With that in mind, to update the Tomcat version, we must use the tomcat.version property:


9.0.44

3.Using spring-boot-dependencies

There are situations when we don’t want to or can’t use the spring-boot-starter-parent. For example, if we use a custom parent in our Spring Boot project. In such cases, there’s a great chance we use spring-boot-dependency to still benefit from the dependency management.

This setup, however, doesn’t let us override individual dependencies by using Maven properties, as shown in the preceding section.

To achieve the same goal and still use a different Tomcat version, we need to add an entry in the dependencyManagement section of our pom file. The crucial thing to remember is that we must place it before the spring-boot-dependencies:






org.apache.tomcat.embed


tomcat-embed-core


9.0.44




org.springframework.boot


spring-boot-dependencies


2.4.5


pom


import




Deploy Spring Boot REST API Application.war in Tomcat Server
Deploy Spring Boot REST API Application.war in Tomcat Server

Starting Tomcat Application Server

The following are the steps to start the Tomcat Application Server locally.

  1. First download the 64-bit Windows zip archive from Apache Tomcat 9 Software Downloads


    apache-tomcat-9.0.65-windows-x64.zip

  2. Unzip to any folder

    Suppose we extract the zip to the


    G:\apache-tomcat-9.0.65

    folder.

  3. Starting Tomcat Server


    G:\apache-tomcat-9.0.65\bin\catalina.bat run

    By default, it will listen to port 8080.

Creating a Spring Boot WAR

Servlet containers expect the applications to meet some contracts to be deployed. For Tomcat the contract is the Servlet API 3.0.

To have our application meet this contract, we have to perform some small modifications in the source code.

First, we need to package a WAR application instead of a JAR. For this, we’ll change pom.xml with the following content:

war

Next, we’ll modify the final WAR file name to avoid including version numbers:




${artifactId}

...

Then we’ll add the Tomcat dependency:




org.springframework.boot


spring-boot-starter-tomcat


provided


Finally, we’ll initialize the Servlet context required by Tomcat by implementing the SpringBootServletInitializer interface:


@SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
}

To build our Tomcat-deployable WAR application, we’ll execute the mvn clean package. After that, our WAR file is generated at target/spring-boot-deployment.war (assuming the Maven artifactId is “spring-boot-deployment”).

We should consider that this new setup makes our Spring Boot application a non-standalone application (if we want to have it working in standalone mode again, we can remove the provided scope from the tomcat dependency).

Spring Boot Tutorial for Beginners #20 - Deploy Step by Step Spring Boot WAR File to External Tomcat
Spring Boot Tutorial for Beginners #20 – Deploy Step by Step Spring Boot WAR File to External Tomcat

Setting up a Spring Boot Application

Let’s set up a simple Spring Boot web application using one of the available starter templates:


org.springframework.boot


spring-boot-starter-parent


2.4.0



org.springframework.boot


spring-boot-starter-web



There’s no need for additional configurations beyond the standard @SpringBootApplication, since Spring Boot takes care of the default setup.

Then we’ll add a simple REST EndPoint to return some valid content for us:


@RestController
public class TomcatController {
@GetMapping("/hello")
public Collection

sayHello() {
return IntStream.range(0, 10)
.mapToObj(i -> "Hello number " + i)
.collect(Collectors.toList());
}
}

Finally, we’ll execute the application with mvn spring-boot:run, and start a browser at http://localhost:8080/hello to check the results.

Related links

  • Example program for this article: https://github.com/doggy8088/spring-boot-deploy-tomcat-demo
  • Apache Tomcat® – Welcome!
  • Stack Overflow
  • Baeldung
  • Apache Maven
  • YouTube

Reference https://blog.miniasp.com/post/2022/09/21/How-to-deploy-Spring-Boot-to-Apache-Tomcat

Embedded Tomcat Server in Maven Project || Java Web Application Using Embedded Tomcat Server
Embedded Tomcat Server in Maven Project || Java Web Application Using Embedded Tomcat Server

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

Spring Boot 1.0 RC4 just dropped and 1.0 can’t be too far behind, and there are all sort of cool features coming!

One of the many questions I get around this concerns deployment strategies for Boot applications. Spring Boot builds on top of Spring and serves wherever Spring can serve. It enjoys Spring’s portability. Spring Boot lets the developer focus on the application’s development first, and removes the need to be overly concerned with every other aspect of its lifecycle, including deployment and management.

It aims to be production ready, out of the box. As part of this, Spring Boot does a few things differently, by default, that may be at first alien to some. In this post, I hope to briefly cover some of the common strategies for deploying a Spring Boot applications. I’ll ever so briefly introduce it, and some sample code, before we dive deeper. Feel free to skip this section and start at the Embedded Web Server Deployment section.

If you haven’t used Spring Boot yet, do! There are many ways to get started, including the Spring Initializr at start.spring.io webservice and – if you’re using Spring Tool Suite – there’s a more familiar, integrated wizard that ultimately invokes that same webservice. I usually start by checking the Actuator, and Web checkboxes, then choosing to generate a Maven Project. This will give you two starter classes, Application.java, and ApplicationTests.java, as well as a ready-to-use Maven

pom.xml

file.

Here is the unzipped starter project:


➜ pwd /Users/jlong/Downloads/starter ➜ starter tree . ├── pom.xml └── src ├── main │ └── java │ └── demo │ └── Application.java └── test └── java └── demo └── ApplicationTests.java 7 directories, 3 files ➜ starter

The Maven build depends on Spring Boot started dependencies. These dependencies are opinionated. They bring in known, ready-to-use stacks aligned with the the task before you, not the technology stacks you might use: put another way, if you want to build a web application, then simple depend on the Spring Boot starter web dependency, like this:




org.springframework.boot


spring-boot-starter-web


The Maven build inherits information about which dependency versions to use from its parent

pom

, also provided by Spring Boot. You don’t need to worry about lining up common Spring project versions and third party dependencies.

The generated Java classes are boilerplate (this is why they’re generated!). You won’t often change the classes themselves, though you can. By the end of this blog you’ll have a common recipe for deploying Spring Boot applications. This is (hopefully!) the only boilerplate you’ll encounter in Spring Boot. Here is the

Application.java

class that Spring Boot provides:


package demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

For the purpose of demonstration during post, we’ll add in a RESTful Spring MVC controller. Here’s the revised

Application.java

code page complete with a Spring MVC REST controller that responds with “Hello, World” when a request to

/hello/World

is made:


package demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } @RestController class GreetingController { @RequestMapping("/hello/{name}") String hello(@PathVariable String name) { return "Hello, " + name + "!"; } }

Out of the box, Spring Boot uses a

public static void main

entry-point that launches an embedded web server for you.

If you use the Maven build (

mvn clean install

) provided by the Spring Boot Initialzr, you’ll get a fat jar. This

jar

is handy because it includes all the other dependencies and things like your web server inside the archive. You can give anybody this one

.jar

and they can run your entire Spring application with no fuss: no build tool required, no setup, no web server configuration, etc: just

java -jar ...your.jar

.

When you run your application, Spring Boot will detect that you have a Spring MVC controller and start up an embedded Apache Tomcat 7 instance, by default. You should be able to test the REST endpoint by opening up your browser and hitting

http://localhost:8080/hello/World

.

There are lots of configuration options for the embedded Tomcat. You can enable HTTPS (SSL/TLS termination) for your webservice fairly easily by providing an

EmbeddedServletContainerCustomizer

, as I do in this example. The module described there is a turnkey web application that can run on HTTPS, requires only a SSL/TLS certificate, and embeds its own webserver. Running that particular application is dead simple:

java -Dspring.profiles.active=production -Dkeystore.file=file:///$PWD/src/main/resources/keystore.p12 -jar target/oauth-1.0.0.BUILD-SNAPSHOT.jar

.

This

EmbeddedServletContainerCustomizer

configuration SPI lets you tap most of the power of explicit XML configuration for a standalone Apache Tomcat instance. Smaller things, like which port the server runs on, can be configured by specifying properties either through the command line (as

--D

-style arguments) or through a loaded property file (Spring Boot will automatically consult any properties in a file named

application.properties

on the

CLASSPATH

, for example). Thus, to change the port on which Tomcat listens, you might specify

--Dserver.port=8081

, to have it listen on port 8081. If you specify

server.port=0

, it’ll automatically find an unused port to listen on, instead.

By default, Spring Boot uses Tomcat 7. If you want to use Tomcat 8, just say so! You need only override the Maven build’s

tomcat.version

property and this will trigger the resolution of later builds of Apache Tomcat.


8.0.3

Of course, some of you may want to use the Jetty embedded servlet container. Jetty’s a fine choice, as well. You can simply exclude the Spring Boot starter Tomcat module and then import the Spring Boot Starter Jetty module. Spring Boot will automatically delegate to that, instead. Here’s the revised

dependencies

section of our Maven build:





org.springframework.boot


spring-boot-starter-web




org.springframework.boot


spring-boot-starter-tomcat






org.springframework.boot


spring-boot-starter-jetty




org.springframework.boot


spring-boot-starter-test


test



If you want to switch to Jetty 9, that’s easy as well. Ensure you have the following

properties

in your Maven build.


1.7


9.1.0.v20131115


3.1.0

But, I imagine you wondering, “how do I deploy it to an existing Tomcat installation, or to the classic Java EE application servers (some of which cost a lot of money!) like WebSphere, WebLogic, or JBoss?” Easy! It’s still just Spring, after all, so very little else is required. You’ll need to make three intuitive changes: move from a

jar

build to a

war

build in Maven: comment out the declaration of the

spring-boot-maven-plugin

plugin in your

pom.xml

file, then change the Maven

packaging

type to

war

. Finally, add a web entry point into your application. Spring configures almost everything for you using Servlet 3 Java configuration. You just need to give it the opportunity. Modify your

Application

entry-point class thusly:


package demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Configuration @ComponentScan @EnableAutoConfiguration public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(applicationClass, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(applicationClass); } private static Class

applicationClass = Application.class; } @RestController class GreetingController { @RequestMapping("/hello/{name}") String hello(@PathVariable String name) { return "Hello, " + name + "!"; } }

This new base class –

SpringBootServletInitializer

– taps into a Servlet 3 style Java configuration API which lets you describe in code what you could only describe in

web.xml

before. Such configuration classes are discovered and invoked at application startup. This gives Spring Boot a chance to tell the web server about the application, including the reqired

Servlet

s,

Filter

s and

Listener

s typically required for the various Spring projects.

This new class can now be used to run the application using embeddedd Jetty or Tomcat, internally, and it can be deployed to any Servlet 3 container. You may experience issues if you have classes that conflict with those that ship as parter of a larger application server. In this case, use your build tool’s facilities for excluding or making

optional

the relevant APIs. Here are the changes to the Maven build that I had to make to get the starter Spring Boot REST service up and running on JBoss WildFly (the AS formerly known as JBoss AS):



4.0.0


org.demo


demo


0.0.1-SNAPSHOT
war
Demo project

org.springframework.boot


spring-boot-starter-parent


1.0.0.BUILD-SNAPSHOT



org.springframework.boot


spring-boot-starter-web




org.springframework.boot


spring-boot-starter-tomcat






org.springframework.boot


spring-boot-starter-test


test



demo.Application
UTF-8 UTF-8
1.7



spring-snapshots


Spring Snapshots


http://repo.spring.io/snapshot



true





spring-milestones


Spring Milestones


http://repo.spring.io/milestone



false




spring-snapshots


Spring Snapshots


http://repo.spring.io/snapshot



true


spring-milestones


Spring Milestones


http://repo.spring.io/milestone



false

I was then able to re-run the build and

cp

the built

.war

to the

$WILDFLY_HOME/standalone/deployments

directory.

Start the application server if it’s not already running, and you should then be able to bring the application up at

http://localhost:8080/$YOURAPP/hello/World

. Again, I’ve substituted

$YOURAPP

for the name of your application, as built.

No story about deployments would be complete without touching on the fastest growing deployment target today: the cloud! Of course, when we talk about cloud it helps to be specific: if you’re talking about deploying to an Amazon Web Services or a Google Compute Engine, directly, then it’s business as usual, just as though you were running the application on a Linux box on your own datacenter. Because, basically, that’s what you’re doing.

If you’re trying to deploy the application to a Platform-as-a-service, Spring’s vaunted portability buys you a lot of options here. Deployment to Heroku, especially with the fat-jar approach, is the status quo for Heroku since that platform as a service expects you to bring-your-own-container, anyway! Simply put the

java -jar

incantation in your

Procfile

and you’re off to the races.

With Cloud Foundry you can deploy the application either standalone or as a

.war

-style web application. Once you’ve built your application (using, for example,

mvn clean install

) and installed the

cf

command line tool, simply answer the

cf push

command’s prompts as I have below:


➜ cf push --path target/demo-0.0.1-SNAPSHOT.jar Name> $YOURAPP Instances> 1 1: 128M 2: 256M 3: 512M 4: 1G Memory Limit> 256M Creating $YOURAPP... OK 1: $YOURAPP 2: none Subdomain> $YOURAPP 1: cfapps.io 2: none Domain> cfapps.io Creating route $YOURAPP.cfapps.io... OK Binding $YOURAPP.cfapps.io to $YOURAPP... OK Create services for application?> n Bind other services to application?> n Save configuration?> y Saving to manifest.yml... OK Uploading $YOURAPP... OK Preparing to start $YOURAPP... OK -----> Downloaded app package (8.7M) -----> Java Buildpack source: system -----> Downloading Open JDK 1.7.0_51 from http://d2vm4m9hl67ira.cloudfront.net/openjdk/lucid/x86_64/openjdk-1.7.0_51.tar.gz (1.4s) Expanding Open JDK to .java-buildpack/open_jdk (1.3s) -----> Downloading Spring Auto Reconfiguration 0.8.7 from http://d2vm4m9hl67ira.cloudfront.net/auto-reconfiguration/auto-reconfiguration-0.8.7.jar (0.0s) -----> Uploading droplet (43M) Checking status of app '$YOURAPP'... 0 of 1 instances running (1 starting) 0 of 1 instances running (1 starting) 1 of 1 instances running (1 running) Push successful! App '$YOURAPP' available at http://$YOURAPP.cfapps.io

The application shoud be up and running, and accessible from

http://$YOURAPP.cfapps.io/hello/Cloud%20Foundry

where, again, I’ve used

$YOURAPP

as a placeholder for the name of your application.

Not bad for one little

Application

class and a few tweaks to a build-file!

Spring Boot aims to be production ready, by default. This means that it ships with useful defaults out of the box that may be overriden, if necessary. By default, Spring Boot provides an embedded Apache Tomcat build. By default, Spring Boot configures everything for you in a way that’s most natural from development to production in today’s platforms, as well as in the leading platforms-as-a-service.

Spring Boot provides plenty of opportunities to override the configuration, including configurable properties and customization callbacks.

Looking forward, I can already see another few posts continuing this discussion into things like management of Spring Boot applications via monitoring and management tools (JMX and JConsole, New Relic, etc.) as well as security concerns. Spring Boot, happily, provides answers for all of these concerns, and more.

The Spring Boot documentation is coming together rapidly as it moves to 1.0, and in the meantime there are many great resources to continue exploring. Check out one of my favorite grab bag pages for tips ‘n tricks, the How To document and don’t forget to check out the Spring IO guides, most of which build on Spring Boot!

I’d love to carry this discussion forward online. I want to know what other questions you want answered in your investigation of Spring Boot, so don’t be shy. I’ll be doing a virtual JUG on Spring Boot on April 9th, 2014, live! The event is worldwide and interactive, so please bring your questions, comments and feedback.

We sometimes encounter a variety of application servers to deploy in our projects due to the different customers we work with. Although Spring Boot has a built-in Embedded Tomcat server, this is mainly used for development or microservice deployment. If you end up deploying your application to a client’s Tomcat / JBoss EAP / IBM WebSphere environment, you still need to make some adjustments. Today’s article is an in-depth look at the setup process and complete knowledge of deploying to Apache Tomcat®.

XML


dependency


groupId


>org.springframework.boot


groupId


artifactId


>spring-boot-starter-web


artifactId


version


>2.2.2.RELEASE


version




dependency

It uses Spring MVC, REST, and Tomcat as a default embedded server. The single spring-boot-starter-web dependency can pull in all dependencies related to web development. It also reduces the count of build dependency. The spring-boot-starter-web mainly depends on the following:

  • org.springframework.boot:spring-boot-starter
  • org.springframework.boot:spring-boot-starter-tomcat
  • org.springframework.boot:spring-boot-starter-validation
  • com.fasterxml.jackson.core:jackson-databind
  • org.springframework:spring-web
  • org.springframework:spring-webmvc

By default, the spring-boot-starter-web contains the below tomcat server dependency given:

How to Create a WAR File For a Spring Boot Project
How to Create a WAR File For a Spring Boot Project

XML


dependency


groupId


>org.apache.tomcat.embed


groupId


artifactId


>tomcat-embed-core


artifactId


version


>8.5.23


version


scope


>compile


scope




dependency


dependency


groupId


>org.apache.tomcat.embed


groupId


artifactId


>tomcat-embed-el


artifactId


version


>8.5.23


version


scope


>compile


scope




dependency


dependency


groupId


>org.apache.tomcat.embed


groupId


artifactId


>tomcat-embed-websocket


artifactId


version


>8.5.23


version


scope


>compile


scope




dependency

Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat

Spring Boot Starter Web

Spring Boot Starter Tomcat

Spring Boot Starter Web is used for building RESTful applications using Spring MVC. Spring Boot Starter Tomcat is the default embedded container for Spring Boot Starter Web.
We cannot exclude it while using web services. We can exclude it when we want to use another embedded container.
It also supports Jetty Server and Undertow Server. It acts as an embedded web server.
It auto-configures Dispatcher Servlet, Error Page, Embedded servlet container, and Web JARs for managing the static dependencies for web development. It has a core, el. logging, WebSocket.
It contains spring web dependencies. It contains everything related to an embedded tomcat server.
It auto-configures the features used for web development. It is used as the default embedded container.

Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated :
11 Mar, 2022

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Common Embedded Tomcat Configurations

2.Server Address and Port

The most common configuration we may wish to change is the port number:


server.port=80

If we don’t provide the server.port parameter it’s set to 8080 by default.

In some cases, we may wish to set a n


server.address=my_custom_ip

By default, the value is set to 0.0.0.0, which allows connection via all IPv4 addresses. Setting another value, for example, localhost – 127.0.0.1 – will make the server more selective.

2.Error Handling

By default, Spring Boot provides a standard error web page. This page is called the Whitelabel. It’s enabled by default, but if we don’t want to display any error information, we can disable it:


server.error.whitelabel.enabled=false

The default path to a Whitelabel is /error. We can customize it by setting the server.error.path parameter:


server.error.path=/user-error

We can also set properties that will determine which information about the error is presented. For example, we can include the error message and the stack trace:


server.error.include-exception=true
server.error.include-stacktrace=always

Our tutorials Exception Message Handling for REST and Customize Whitelabel Error Page explain more about handling errors in Spring Boot.

2.Server Connections

When running on a low resource container, we might like to decrease the CPU and memory load. One way of doing that is to limit the number of simultaneous requests that can be handled by our application. Conversely, we can increase this value to use more available resources to get better performance.

In Spring Boot, we can define the maximum amount of Tomcat worker threads:


server.tomcat.threads.max=200

When configuring a web server, it also might be useful to set the server connection timeout. This represents the maximum amount of time the server will wait for the client to make their request after connecting before the connection is closed:


server.connection-timeout=5s

We can also define the maximum size of a request header:


server.max-http-header-size=8KB

The maximum size of a request body:


server.tomcat.max-swallow-size=2MB

Or a maximum size of the whole post request:


server.tomcat.max-http-post-size=2MB

2.SSL

To enable SSL support in our Spring Boot application, we need to set the server.ssl.enabled property to true and define an SSL protocol:


server.ssl.enabled=true
server.ssl.protocol=TLS

We should also configure the password, type, and path to the key store that holds the certificate:


server.ssl.key-store-password=my_password
server.ssl.key-store-type=keystore_type
server.ssl.key-store=keystore-path

And we must also define the alias that identifies our key in the key store:


server.ssl.key-alias=tomcat

For more information about SSL configuration, visit our HTTPS using a self-signed certificate in the Spring Boot article.

2.Tomcat Server Access Logs

Tomcat access logs are beneficial when measuring page hit counts, user session activity, and so on.

To enable access logs, simply set:


server.tomcat.accesslog.enabled=true

We should also configure other parameters such as directory name, prefix, suffix, and date format appended to log files:


server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.file-date-format=yyyy-MM-dd
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.suffix=.log

Spring MVC + TomCat Setup
Spring MVC + TomCat Setup

Export the package file and deploy it to the Tomcat application server

Finally, we have to export a

*.war

file that can be deployed to Tomcat, basically the deployment steps are as follows.

  1. Run the


    mvn clean package

    command

    This command generates the


    target/app1-0.0.1-SNAPSHOT.war

    file, which is about 17MB in size.

    You can unzip this war file to see its directory structure.

    The most noteworthy point here is the


    WEB-INF/lib-provided

    folder. Since we have changed theof the spring-boot-starter-tomcat dependent package in

    pom.xml

    to provided, this package is moved from the default to WEB-INF/lib to the

    WEB-INF/lib-provided

    folder, which means that when we deploy to Tomcat This means that the

    *.jar

    file in the

    WEB-INF/lib-provided

    folder will not be loaded by default when we deploy to the Tomcat application server.

  2. Copy the


    target/app1-0.0.1-SNAPSHOT.war

    file to the

    G:\apache-tomcat-9.0.65\webapps

    directory.

    Wait about 1 to 3 seconds, Tomcat will automatically deploy the


    app1-0.0.1-SNAPSHOT.war

    file and automatically extract it to the

    app1-0.0.1-SNAPSHOT

    directory.

    And we can also see the following message from the Console screen of running Tomcat.


    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16


    19-Sep-2022 22:43:23.587 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [G:\apache-tomcat-9.0.65\webapps\app1-0.0.1-SNAPSHOT.war] 19-Sep-2022 22:43:25.458 INFO [Catalina-utility-2] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.7.3) 2022-09-19 22:43:26.340 INFO 10776 --- [alina-utility-2] com.duotify.app1.DemoApplication : Starting DemoApplication v0.0.1-SNAPSHOT using Java 17.0.2 on WILLSUPERPC with PID 10776 (G:\apache-tomcat-9.0.65\webapps\app1-0.0.1-SNAPSHOT\WEB-INF\classes started by wakau in G:\apache-tomcat-9.0.65) 2022-09-19 22:43:26.345 INFO 10776 --- [alina-utility-2] com.duotify.app1.DemoApplication : No active profile set, falling back to 1 default profile: "default" 2022-09-19 22:43:27.284 INFO 10776 --- [alina-utility-2] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 898 ms 2022-09-19 22:43:28.411 INFO 10776 --- [alina-utility-2] com.duotify.app1.DemoApplication : Started DemoApplication in 2.653 seconds (JVM running for 126.74) 19-Sep-2022 22:43:28.433 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [G:\apache-tomcat-9.0.65\webapps\app1-0.0.1-SNAPSHOT.war] has finished in [4,845] ms

    At this point, open your browser and visit


    http://localhost:8080/app1-0.0.1-SNAPSHOT/

    to see the application successfully deployed!

  3. Modify the Context Path of the application deployed to Tomcat

    Since the default WAR file name will automatically become Tomcat’s Context Path when deploying


    app1-0.0.1-SNAPSHOT.war

    to Tomcat, we can adjust thesetting in

    pom.xml

    to specify the final output file name. We can use

    ${project.artifactId}

    , a built-in Maven attribute, to get the

    artifactId

    of the project as the file name.

    Run


    mvn clean package

    again and the

    target/app1.war

    file will be output! 👍

    Addendum: If you want to specify the Context Path during the development testing phase, you can add a


    server.servlet.context-path=/app1

    property to

    src/main/resources/application.properties

    . See: Spring Boot Change Context Path.

Conclusion

In this tutorial, we’ve learned a few common Tomcat embedded server configurations. To view more possible configurations, please visit the official Spring Boot application properties docs page.

As always, the source code for these examples is available over on GitHub.

I’m developing a web application with Spring-boot and it’s all been working quite well.

I’ve been editing and testing it on my browser like it’s been deployed to a server.

But now I want to generate my war file, and according to Spring’s documentation here, I have to mark the tomcat dependecies as provided. The thing is that I don’t see this dependency anywhere in my pom.xml.

Question: Which dependency should I mark as provided?

These are the ones I actually have in my pom.xml:


org.springframework.boot


spring-boot-starter-parent


1.3.3.RELEASE



org.springframework.boot


spring-boot-starter




org.springframework


spring-web




com.fasterxml.jackson.core


jackson-databind




org.springframework.boot


spring-boot-starter-thymeleaf




org.springframework.boot


spring-boot-devtools

true



Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat

Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:

  • It allows avoiding heavy configuration of XML which is present in spring
  • It provides easy maintenance and creation of REST endpoints
  • It includes embedded Tomcat-server
  • Deployment is very easy, war and jar files can be easily deployed in the tomcat server

Spring Boot Starter Web

It is mainly used for building web applications that include RESTful applications using Spring MVC. It uses Tomcat as the default embedded container. It has two important features:

  • It is compatible with web development.
  • It can be auto-configured.

We need to add the following dependency in the pom.xml file for Spring Boot Starter Web:

🔥Deploy Spring Boot on External Tomcat Server
🔥Deploy Spring Boot on External Tomcat Server

Adjust the project

To deploy to a standalone Tomcat server, the following adjustments must be made in a total of only steps.

  1. Modify the


    @SpringApplication

    startup class

    The main class, originally annotated with


    @SpringBootApplication

    , must be modified to inherit from the

    SpringBootServletInitializer

    class.

    1 2 3 4 5 6 7 8 9 10 11 12 13 14


    package com.duotify.app1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class DemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

    In fact,


    SpringBootServletInitializer

    implements the

    WebApplicationInitializer

    interface, which is new in Servlet 3.0+ (JSR 315), and the implementation of this interface will automatically set the The implementation of this interface automatically configures the ServletContext and communicates with the Servlet Container, allowing the application to mount smoothly to any Application Server that supports the Servlet Container.

    This mechanism is only supported from Servlet 3.0 API onwards, while Apache Tomcat supports Servlet 3.0 specification from version


    7.0

    onwards. If you are using Servlet

    2.5

    or earlier, you still need to register

    ApplicationContext

    and

    DispatcherServlet

    through

    web.xml

    . However, Apache Tomcat 7.0 is a deprecated version, so it should not be easy to encounter. For more information, see Apache Tomcat® – Which Version Do I Want?

  2. Adjust


    pom.xml

    and change Packaging format to

    war

    war

  3. Adjust


    pom.xml

    and add

    spring-boot-starter-tomcat

    dependencies and setto

    provided

    .

The following is the current

pom.xml

file content.

Create sample applications

  1. Quickly building a project using the Spring Boot CLI


    spring init --dependencies=web --groupId=com.duotify app1

    It can also be built with Spring Initializr.

    Open the project using Visual Studio Code.


    code app1

  2. Add a HomeController controller

    File path:


    src/main/java/com/duotify/app1/controllers/HomeController.java

    .

    1 2 3 4 5 6 7 8 9 10 11 12 13


    package com.duotify.app1.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeController { @GetMapping("/") public String home() { return "Hello World"; } }

  3. Test


    mvn spring-boot:run

    Addendum: You can add a



    spring-boot:run


    setting under thenode in

    pom.xml

    , then you can just type

    mvn

    and Spring Boot will start running automatically! 👍

    curl http://localhost:8080/

Spring Boot Simple Project step by step using Mysql Database
Spring Boot Simple Project step by step using Mysql Database

Keywords searched by users: spring boot tomcat maven

Spring Boot - Project Deployment Using Tomcat - Geeksforgeeks
Spring Boot – Project Deployment Using Tomcat – Geeksforgeeks
Spring Boot Project Deployment Using Tomcat - Javatpoint
Spring Boot Project Deployment Using Tomcat – Javatpoint
Deploy Spring Boot Mvc Application On Aws | Elastic Beanstalk - Youtube
Deploy Spring Boot Mvc Application On Aws | Elastic Beanstalk – Youtube
Java Spring Boot Tutorial - Live Hello-World Web Application Example With  Detailed Steps • Crunchify
Java Spring Boot Tutorial – Live Hello-World Web Application Example With Detailed Steps • Crunchify
Spring Boot Tomcat | What Is Spring Boot Tomcat?
Spring Boot Tomcat | What Is Spring Boot Tomcat?
Java - Run Spring Boot With Eclipse Tomcat - Stack Overflow
Java – Run Spring Boot With Eclipse Tomcat – Stack Overflow
Spring Boot - Starters - Geeksforgeeks
Spring Boot – Starters – Geeksforgeeks
How To Run Your First Spring Boot Application In Intellij Idea? -  Geeksforgeeks
How To Run Your First Spring Boot Application In Intellij Idea? – Geeksforgeeks
Deploying A Spring Boot Application To External Tomcat | War File  Generation | Install Tomcat - Youtube
Deploying A Spring Boot Application To External Tomcat | War File Generation | Install Tomcat – Youtube
Running Spring-Boot Application On Tomcat Servlet Container - Studytonight
Running Spring-Boot Application On Tomcat Servlet Container – Studytonight

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *