Placing dynamic contents like JSP pages into static locations does not work.
In a war project, JSP pages are served from src/main/webapp/WEB-INF/ .
In a Jar project, JSP pages cannot simply be served from webapp location or from src/main/resources/ . That's because of the limitation stated in boot ref docs.
The location src/main/webapp/WEB-INF may work in exploded form but should be avoided. From boot ref docs:
Do not use the src/main/webapp directory if your application will be packaged as a jar. Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar.
Fortunately we have another option for a Jar project: Servlet 3.0 specification allows to have dynamic pages in src/main/resources/META-INF/resources/ (Please check out an example here).
Let's explore both options with examples.
Serving JSPs with Jar Packaging
Creating Controller
@Controller
public class MyController {
@RequestMapping("/")
public String handler (Model model) {
model.addAttribute("msg",
"a jar packaging example");
return "myView";
}
}
The JSP page
Save the following page at location: src/main/resources/META-INF/resources/WEB-INF/views/myView.jsp
<h2>From JSP page </h2>
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
Message : ${msg}
</body>
</html>
The view resolver
Boot auto-configuration implicitly adds many view resolvers including InternalResourceViewResolver . This resolver is used to locate and render JSP pages. A boot application client just need to add spring.mvc.view.prefix and spring.mvc.view.suffix properties:
src/main/resources/application.properties:
spring.mvc.view.prefix= /WEB-INF/views/
spring.mvc.view.suffix= .jsp
Specifying Jar packaging in pom.xml
<project ....>
<modelVersion>4.0.0</modelVersion>
<groupId>com.logicbig.example</groupId>
<artifactId>boot-jar-serving-jsp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
.......
</project>
We can also skip the packaging element because maven default packaging type is 'jar'.
JSP related maven dependencies
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
Running application
The easiest way to run application successfully add Spring Boot Maven plugin and run it from IDE or command line:
mvn spring-boot:run
Output
Example ProjectDependencies and Technologies Used: - Spring Boot 1.4.2.RELEASE
Corresponding Spring Version 4.3.4.RELEASE - spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring
MVC. Uses Tomcat as the default embedded container.
- tomcat-embed-jasper 8.5.6: Core Tomcat implementation.
- jstl 1.2 javax.servlet:jstl
- JDK 1.8
- Maven 3.3.9
|