Reputation: 522
I am trying to use jsp in my project, but it is difficult. I put these two dependencies in the pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- If you want to use JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
Then I put these two lines in the aplication.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
I created a page with the name "index.jsp" and put that
<h1>
INDEX
</h1>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Aspernatur nam, nisi, repudiandae illum
ab a aut maxime deleniti voluptas praesentium dicta delectus. Voluptatibus consequuntur
necessitatibus hic eum suscipit, sequi autem.
</p>
And my controller:
package com.example.curso.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}
And the error when I try to access the route
Upvotes: 5
Views: 2136
Reputation: 25156
Based on your stacktrace, it looks Thymeleaf is configured as rendering engine/view resolver. It might be because you have spring-boot-starter-thymeleaf
in your classpath and spring boot auto configured it.
JSP support has been dropped from Spring Boot in newer versions. So, you will need manually configure few things to make it work.
If you want to use jsp instead of thymeleaf as your primary rendering engine, remove the spring-boot-starter-thymeleaf
from your dependency and copy your .jsp files under webapp folder as below:
application.properties:
spring.mvc.view.prefix:/jsp/
spring.mvc.view.suffix:.jsp
Folder structure:
├── pom.xml
├── src
│ └── main
│ ├── java
│ │ └── gt
│ │ └── SpringBootWebApplication.java
│ ├── resources
│ │ └── application.properties
│ └── webapp
│ ├── css
│ │ └── main.css
│ └── jsp
│ └── welcome.jsp
Required dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
welcome.jsp
<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
<c:url value="/css/main.css" var="jstlCss"/>
<link href="${jstlCss}" rel="stylesheet"/>
</head>
<body>
<h2>Message: ${msg}</h2>
</body>
</html>
@Controller:
@RequestMapping("/")
String welcome(Model m) {
m.addAttribute("msg", "Hello");
return "welcome";
}
Run using mvn spring-boot:run
Running the @SpringBootApplication's main method might not work
Upvotes: 7