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

Source: Internet
Author: User
First, 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.

Second, 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支持--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency><!--JavaServer Pages Standard Tag Library,JSP标准标签库--><dependency>    <groupId>javax.servlet</groupId>    <artifactId>jstl</artifactId></dependency><!--内置tocat对Jsp支持的依赖,用于编译Jsp--><dependency>    <groupId>org.apache.tomcat.embed</groupId>    <artifactId>tomcat-embed-jasper</artifactId>    <scope>provided</scope></dependency>

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;@Controller@RequestMapping("/cat") //创建路由规则http://xxxx/catpublic class Cat {    /**     * 默认路由方法     *     * @return     */    @RequestMapping("")    public ModelAndView index() {        ModelAndView modelAndView = new ModelAndView("/index"); //设置对应JSP的模板文件        modelAndView.addObject("hi", "Hello,Cat"); //设置${hi}标签的值为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" %><html><head>    <title>Title</title></head><body><h1>    ${hi}</h1></body></html>

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;/** * 启动类,程序入口 */@SpringBootApplicationpublic class HelloSpringBootApplication  extends SpringBootServletInitializer{    /**     * 重写configure方法,加载启动类     * @param application     * @return     */    @Override    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {        return application.sources(HelloSpringBootApplication.class);    }    /**     * Spring Boot 默认main方法     * @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:

<!--排除内置tomcat jar包--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-tomcat</artifactId>    <scope>provided</scope></dependency>

The main code is provided , 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" />    <!--    其他代码    --></Host>
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

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.

Tags Index: