Important: recommend you to use JSP views with WAR file, JAR file will have many problems, one of which I have encountered is deploying JAR file using Docker Container… The following tutorial is only for someone who must use JSP views with JAR files in Spring Boot.
JSP files, normally used with InternalResourceViewResolver, have some limitations when used in Spring Boot applications. According to Spring Boot documentation https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.developing-web-applications.embedded-container.jsp-limitations the JSP file will only work with Tomcat and Jetty server and will only work with WAR files, not with JAR files. However, in fact, we also have a way to make it work with JAR files. In this tutorial, I will show you how to configure JSP views in InternalResourceViewResolver with Spring Boot JAR file.
I will create a new Spring Boot project:
and use InternalResourceViewResolver for this example.
I will add tomcat-embed-jasper dependency:
1 2 3 4 5 |
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> |
and a controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava.springboot.internalresourceviewresolver; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("/hello") public String home() { return "home"; } } |
The view file home.jsp with the following content:
1 |
Hello World! |
will no longer be created in the /src/main/webapp/WEB-INF/views directory, Spring Boot when building will not include this directory in the JAR file. You need to create it in the src/main/resources/META-INF/resources/WEB-INF/views directory as follows:
The src/main/resources/META-INF/resources/ directory will work like the src/main/webapp directory!
Now I will declare in application.properties as follows:
1 2 |
spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp |
Result when running the application: