Spring Boot Best Practices (ii) Integrated JSP and production environment deployment

Source: Internet
Author: User
Tags windows download
I, Introduction

Mention Java has to say that a development scenario is the Web development, is also one of the most popular Java development scenarios, when it comes to web development is not open to a technology is JSP, because there are still many companies in the market using JSP, so this article to introduce the spring Boot How to integrate JSP development, and the detailed deployment method of the production environment.

II, integrated JSP development environment
    • Spring Boot 2.0.4 RELEASE
    • Tomcat 9.0.10
    • Idea (Intellij idea abbreviation, unified use below) 2018.2
    • Windows 10
JSP Integration steps
    1. Create a JSP directory
    2. Application.properties Configuring JSP Information
    3. Pom.xml Adding dependent components
    4. Writing Spring MVC Code
    5. Run the program

The specific integration methods are as follows:

1. Create a JSP directory

Create a directory under the Src/main directory webapp/web-inf/jsp for JSP pages, such as:

2.application.properties Configuring JSP Information

Application.properties is a global configuration file, which can set up a lot of information, such as set the log, set the cache, set spring, spring session and other information, we only need to set the JSP directory file, as well as the file suffix, the code is as follows:


More application.properties setup Information, view official documents: docs.spring.io/spring-boot/docs/current/reference/htmlsingle/# Common-application-properties

3.pom.xml Adding a JSP configuration

You need to add 3 components to the Pom.xml:

    • Spring-boot-starter-web (for running Web projects)
    • JSTL (JavaServer Pages standard tag library,jsp tag library for parsing JSPs in programs)
    • Tomcat-embed-jasper (built-in tocat dependency on JSP support for compiling JSPs)

The specific code is as follows:

<!--web support -->

<!--JavaServer Pages Standard Tag Library, JSP Standard Tag Library -->

<!-- Built-in tocat dependency on Jsp support, used to compile Jsp-->

Note: the scope (scope) value of Tomcat-embed-jasper is provided, which means that the package does not have to be packaged, other devices will provide, and if packaged in will conflict with the jar provided by external Tomcat, the project fails to start.

The scope (scope) value list represents the meanings explained below:
    • Compile: Default value He indicates that the dependent project needs to be involved in the compilation of the current project, as well as follow-up testing, and that the run cycle is also involved, is a relatively strong dependency. It usually needs to be included in the package.
    • Test: Dependent projects participate only in testing-related work, including the compilation and execution of test code, and are not packaged, for example: JUnit
    • Runtime: Indicates that the dependent project does not need to participate in the compilation of the project, but later testing and running cycles require its participation. The compilation was skipped compared to compile. For example, JDBC driver, suitable for run and test phase
    • Provided: packaging will not be included, other facilities will be provided. In fact, the dependency theory can be involved in compiling, testing, running and other cycles. Equivalent to compile, but the packaging phase did a exclude operation
    • System: In terms of engagement, the same as provided, but the dependencies are not downloaded from the Maven repository, but are taken from the local file system. You need to add Systempath properties to define the path
4. Writing Spring MVC Code

After the first 3 steps of configuration, the project configuration section has been completed almost, followed by code writing, code writing and spring MVC, like two parts of Java class Writing and identification annotations, JSP template creation and writing. In order to better demonstrate the functionality of Spring Boot, we will simplify the business logic as much as possible, in this example we create a Cat class, set the label hi= "Hello Cat", on the page Output tab.

a). Cat.java Code

Package com.hellospringboot.hellospringboot;
Import org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import org.springframework.web.servlet.ModelAndView;
@RequestMapping("/cat") //Create a routing rule http://xxxx/cat
Public class Cat {
      * Default routing method
      * @return
     Public ModelAndView index() {
         ModelAndView modelAndView = new ModelAndView("/index"); //Set the template file corresponding to JSP
         modelAndView.addObject("hi", "Hello,Cat"); //Set the value of the ${hi} tag to Hello, Cat
         Return modelAndView;

Spring MVC Annotation Interpretation

    • @Controller identified on a class, the class identified is the controller class for spring MVC, and the distribution processor scans whether the class using the annotation uses the @requestmapping annotation, @Controller just defines a controller class, Using only @requestmapping annotations is the processor that really handles the request;
    • The @RequestMapping identifies the annotations on the class or method used to process the request address, with a total of 6 attributes:
      1. Value corresponds to the actual address of the request
      2. Type of method Request: Get, post, put, delete, etc., ex: @RequestMapping (value = "/test", method = Requestmethod.put)
      3. Consumes specifies the type of content on the request, such as Application/json, text/html, etc.
      4. produces specifies the data type to be returned, type must be the type contained in request headers
      5. The params filter request is executed only if the request contains a parameter, such as @requestmapping (value = "", params = "flag"), which is only executed if the parameter contains flag, otherwise it cannot be accessed, http://localhost : 8080/cat?true=flag This address is not accessible, the correct address is http://localhost:8080/cat?flag=true to be able to access the normal
      6. Headers and params are similar, only the request headers contains a key in order to access the method

b). JSP-Side Code

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

This JSP only does one thing and displays the value of the ${hi} tag inside the Java class.

5. Running the program

So far, if you're using the idea development tool, you can now run the debugger, run the index.jsp or boot file directly, or start the file (Application.java), and then enter it in the browser: http://localhost : 8080/cat can be viewed.

III. production Environment Deployment deployment steps

  1. Download Install Tomcat
  2. Ingress class inheritance Springbootservletinitializer overriding Configure method
  3. Configure Pom.xml
  4. Idea generates a war file
  5. Configure the Tomcat Run project

1. Download and install Tomcat

: tomcat.apache.org/download-90.cgi

As shown in the following:

Windows Download: 64-bit Windows Zip | Linux Downloads: tar.gz

Note: If it is a Windows version of the download version of the free installation if you put in the C-drive, note that the folder is assigned

sufficient permissions, or after the start of the Access page display 400 or 505 similar problems.

2. Ingress class inheritance Springbootservletinitializer overriding Configure method

If you are deploying a production environment, you need to configure the spring Boot entry class separately, you need to inherit the Springbootservletinitializer class, override the Configure method, Because the default external tomcat cannot read to the Spring boot entry class, the main method starts the program load, using the need to inherit the code as follows:

package com.hellospringboot.hellospringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
 * Startup class, program entry
public class HelloSpringBootApplication  extends SpringBootServletInitializer{
     * Override the configure method, load the startup class
     * @param application
     * @return
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(HelloSpringBootApplication.class);
     * Spring Boot default main method
     * @param args
    public static void main(String[] args) {
        SpringApplication.run(HelloSpringBootApplication.class, args);

 3. Configure Pom.xml 

Need to configure pom.xml, to exclude the built-in Tomcat jar package, to prevent the package after the collision with the outer Tomcat jar package, resulting in project start failure, configured as follows:

<!--Exclude the built-in tomcat jar package-->

The main code isprovided, and the provisioning package will not be included, provided by other facilities.

4.IDEA Build War file Step one: Modify the Build jar to the war format

Found it:


Modified to:


Why do I need to modify the jar package format as a war, because if the package is packaged as a jar, the JSP file will not be included, so when the access is back to 404, and the package as a war back contains the JSP file, so the packaging format needs to be modified to war.

What is the difference between jar and war?

    • Jar (Java application archive) Java application Library, typically a generic class for developing references
    • War (Web application archive) Web application

So from the difference between jar and war, it is also appropriate to package the Web program into a war format.

If you need to modify the file name of the generated file, you can set the Finalname property under Build, with the following code:

Step two: Use idea to generate a war package

Select Menu Bar Build + = build artifacts. +-click Rebuild to generate the war package,

After the build, the build war file is found under the target directory of the project, such as:

5. Configure the Tomcat Run Project Step one: Copy the war file to the WebApps directory of Tomcat Step two: Configure Conf/server.xml

To add a context setting to the host tag, docbase the name of the war file, configured as follows:

<Host name="localhost"  appBase="webapps" unpackWARs="true" autoDeploy="true">    
    <Context path="" docBase="springbootjsp" debug="0" privileged="true" reloadable="true" />
    other code

Step three: Start Tomcat

Run the Bin/shutdown.bat file to start Tomcat

Input address: Http://localhost:8080/cat access.

The deployment to this project was successful, and although I deployed it to Windows Server, Linux was the same step.

Iv. knowledge Extension: Spring Boot template Recommendation

Although we described the JSP in detail above in spring boot, it is not recommended to use JSP for spring boot (see below for reasons).

Spring boot recommended template engine:
    • Thymeleaf
    • Freemarker
    • Mustache
    • Groovy Templates

As shown in the following:

Why does spring not recommend using JSPs?

There are several reasons why spring officially does not recommend using JSPs:

    1. Official document JSP is not thymeleaf good;
    2. Thymeleaf Healthy Open source projects, almost every month has been updated, and JSP has not been substantial progress for several years;
    3. Thymeleaf has a fast-responding user forum.

For more details, click to view: Spring.io/blog/2012/10/30/spring-mvc-from-jsp-and-tiles-to-thymeleaf

Summary: According to the official statement, if you have hundreds of JSP pages, we don't recommend that you abandon them immediately and reuse thymeleaf, but if you start developing a new project, you are strongly encouraged to compare other template engines and JSPs to confirm which one is better for you.

V. References

JSP for developing Web applications: http://tengj.top/2017/03/13/springboot5/

Welcome to Sweep code, join the circle discussion Exchange

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.