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
- Create a JSP directory
- Application.properties Configuring JSP Information
- Pom.xml Adding dependent components
- Writing Spring MVC Code
- 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:
spring.mvc.view.prefix=/WEB-INF/jspspring.mvc.view.suffix=.jsp
More application.properties setup Information, view official documents: https://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 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--JavaServer Pages Standard Tag Library, JSP Standard Tag Library -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Built-in tocat dependency on Jsp support, used to compile 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") //Create a routing rule http://xxxx/cat
Public class Cat {
/**
* Default routing method
*
* @return
*/
@RequestMapping("")
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:
-
- Value corresponds to the actual address of the request
- Type of method Request: Get, post, put, delete, etc., ex: @RequestMapping (value = "/test", method = Requestmethod.put)
- Consumes specifies the type of content on the request, such as Application/json, text/html, etc.
- produces specifies the data type to be returned, type must be the type contained in request headers
- 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
- 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
Download Install Tomcat
Ingress class inheritance Springbootservletinitializer overriding Configure method
Configure Pom.xml
Idea generates a war file
Configure the Tomcat Run project
1. Download and install Tomcat
: https://tomcat.apache.org/download-90.cgi
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, overriding the Configure method, because by default external Tomcat cannot read to spring The main method of the boot entry class starts the program load, using the need to inherit, the code is 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
*/
@SpringBootApplication
Public class HelloSpringBootApplication extends SpringBootServletInitializer{
/**
* Rewrite the configure method, load the startup class
* @param application
* @return
*/
@Override
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 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
The main code is <SCOPE>PROVIDED</SCOPE>, 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:
<packaging>jar</packaging>
Modified to:
<packaging>war</packaging>
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:
<build>
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
-->
</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:
Official document JSP is not thymeleaf good;
Thymeleaf Healthy Open source projects, almost every month has been updated, and JSP has not been substantial progress for several years;
Thymeleaf has a fast-responding user forum.
For more details, click to view: Https://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
Spring Boot Best Practices (ii) Integrated JSP and production environment deployment