JSP deployment strategy in Spring Boot Jar project
In modern Java enterprise application development, the Spring Boot framework is popular for its simplified configuration and rapid deployment. However, for those who want to use it in Spring Boot projectsJSP pageFor developers, they may encounter some challenges, especially when the project needs to be deployed in the form of Jar packages. This article will explore in detail how to effectively deploy and run JSP pages in Spring Boot Jar projects.
Background knowledge
In traditional WAR projects, JSP pages are usually placed insrc/main/webapp/WEB-INF/
In the directory. However, when the project is packaged into a Jar file, this directory structure is no longer applicable. Spring Boot official documentation recommends not to use it in Jar projectssrc/main/webapp
Directory, because this will be mostBuild Toolsneglect.
Servlet 3.0 specification solution
Fortunately, the Servlet 3.0 specification provides a solution: allowing dynamic pages to be placed onsrc/main/resources/META-INF/resources/
In the directory. This provides the possibility for us to use JSP pages in our Jar project.
Example Demonstration
Create a controller
First, we need to create a Spring MVC controller to handle the request and addModeldata.
@Controller
public class MyController {
@RequestMapping("/")
public String handler(Model model) {
model.addAttribute("msg", "Jar packaged JSP example");
return "myView";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
JSP page
Next, we place the JSP page insrc/main/resources/META-INF/resources/WEB-INF/views/
In the directory.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>JSP Example</title>
</head>
<body>
<h2>From JSP page</h2>
<p>Message: ${msg}</p>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
View parser configuration
Spring Boot automatically configures many view resolvers, includingInternalResourceViewResolver
. We need toThe specified view in the filePrefix andsuffix.
=/WEB-INF/views/
=.jsp
- 1
- 2
MavenConfiguration
existIn the file, make sure the package type of the project is
jar
and add necessary dependencies.
<project>
<!-- ... Other configurations ... -->
<packaging>jar</packaging>
<!-- ... Other configurations ... -->
</project>
- 1
- 2
- 3
- 4
- 5
Run the application
Using the Spring Boot Maven plugin to run applications is an easy and effective way.
mvn spring-boot:run
- 1
Technology stack
- Spring Boot 1.4.
- Spring Framework 4.3.
- spring-boot-starter-web
- tomcat-embed-jasper 8.5.6
- jstl 1.2 :jstl
- JDK 1.8
- Maven 3.3.9
Through the above steps, you can successfully deploy and run JSP pages in your Spring Boot Jar project. This not only demonstrates the flexibility of Spring Boot, but also provides a viable solution for developers who need to use JSP.