Issue
I started a Spring Boot MVC project and realized that there are two folder within resources
. One is called templates
and the other static
. I really like this folder setup.
The problem is that I use JSP Templates for my views. I could not place a .jsp
template inside the templates
folder and got it to work.
What I needed to do is to create a webapp
folder on the same level as src
and resources
. Placing my JSP templates in there and then my views can be found.
What do I need to reconfigure to actually use my JSP templates within the templates
folder which lies within resources
?
Solution
According to the Maven documentation src/main/resources
will end up in WEB-INF/classes
in the WAR.
This does the trick for Spring Boot in your application.properties
:
spring.mvc.view.prefix = /WEB-INF/classes/templates
spring.mvc.view.suffix = .jsp
If you prefer Java configuration this is the way to go:
@EnableWebMvc
@Configuration
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/classes/templates/");
bean.setSuffix(".jsp");
return bean;
}
}
Update with a full example
This example was based on Spring's initializer (Gradle project with "Web" dependency). I just added apply plugin: 'war'
to the build.gradle
, added/changed the files below, built teh project with gradle war
and deployed it to my application server (Tomcat 8).
This is the directory tree of this sample project:
\---src
+---main
+---java
| \---com
| \---example
| \---demo
| ApplicationConfiguration.java
| DemoApplication.java
| DemoController.java
|
\---resources
+---static
\---templates
index.jsp
ApplicationConfiguration.java: see above
DemoApplication.java:
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(DemoApplication.class, args);
}
}
DemoController.java:
@Controller
public class DemoController {
@RequestMapping("/")
public String index() {
return "index";
}
}
index.jsp:
<html>
<body>
<h1>Hello World</h1>
</body>
</html>
Answered By - Franz Fellner