Spring Boot应用中JSP文件的正确存放位置及视图渲染故障排查
Hey there! I totally get how confusing this can be when you're just starting out with Spring Boot. Let's walk through the common fixes for your JSP rendering problem step by step:
1. Add Missing JSP Dependencies
Spring Boot doesn't include JSP support out of the box, so you need to add these critical dependencies to your pom.xml first—this is probably the most common culprit:
<!-- Required for compiling JSP files --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- JSTL for using tag libraries (if you need them) --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
If you're running the app directly with mvn spring-boot:run, you can change the scope of tomcat-embed-jasper to compile—the provided scope works best when deploying the war to an external Tomcat server.
2. Stick with WAR Packaging for JSPs
Here's a key detail: JSPs don't play nicely with JAR packaging in Spring Boot. The src/main/webapp directory isn't included in the final JAR by default, so your views will never be found even if you configure everything else correctly.
Set your packaging to war in pom.xml:
<packaging>war</packaging>
If you really need to use JAR packaging, you'll have to move your JSPs to src/main/resources/META-INF/resources/WEB-INF/jsp/—but this is not recommended by Spring Boot's official docs, so WAR is the safer, more reliable choice.
3. Double-Check Your View Configuration
Make sure your application.properties has no typos (small mistakes here are easy to miss!):
# Correct configuration for JSP views spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
Ensure there's a space after the colon, and the prefix path exactly matches where your JSP files are stored.
4. Verify Your Controller Setup
A common slip-up is accidentally using @ResponseBody on your controller method—this tells Spring to return the string as raw text instead of rendering a view. Your controller should look like this:
@Controller public class MyController { @GetMapping("/hello") public String showHelloPage() { // No @ResponseBody here! return "hello"; // Matches /WEB-INF/jsp/hello.jsp } }
Also, double-check that your JSP filename exactly matches the string you're returning (it's case-sensitive!).
5. Clean and Rebuild Your Project
Sometimes old build artifacts can cause hidden issues. Run these commands to wipe old files and rebuild fresh:
mvn clean mvn package
Then run your app again with mvn spring-boot:run or deploy the war to your server.
Give these steps a try—most likely one of these fixes will get your JSPs rendering properly. If you're still stuck, feel free to share your full pom.xml and controller code, and we can dig deeper!
内容的提问来源于stack exchange,提问作者Sunil Keshari

