博主在使用sring-boot跳轉HTML頁面後,因爲好奇心就想跳轉到JSP頁面,就在網上搜相關信息,結果不是跳轉500錯誤就是下載JSP文件。各類坑啊,在博主跳了N多坑後,終於跳轉JSP頁面成功。故寫此文章便於使用到的小夥伴再也不進坑。html
一、新建spring-boot項目 目錄結構以下java
二、新建TestController.java文件,內容以下web
package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { @RequestMapping("/index") public String index(){ return "index"; } }
三、新建webapp文件夾,與resources同級。spring
四、新建JSP頁面,此時發現New裏面沒有JSP頁面。須要設置一下才會出現喲。apache
五、點擊File->Project Structure...tomcat
六、點擊Modules->綠色加號->Webapp
七、雙擊此處webapp
八、選擇剛剛新建的webapp,點擊OK,繼續OK。jsp
九、此時webapp上有個藍色圓點表示設置成功。ide
十、在webapp上單擊右鍵New,此時出現JSP文件。
十一、新建index.jsp
十二、index.jsp內容
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1 style="color: red">Hello World</h1> </body> </html>
1三、新建MyWebAppConfigurer類
1四、MyWebAppConfigurer內容
package com.example.controller; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; } }
1五、在pom.xml中加入依賴JAR包
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>7.0.59</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
1六、啓動Application,訪問127.0.0.1:8080/index
1七、跳轉完成。
以上就是spring-boot跳轉JSP頁面的過程,下面說說跳轉遇到的坑。
1、缺乏依賴JAR包
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
跳轉失敗
提示還算明確,缺乏jstl標籤
2、使用provided版本JSP解析器JAR包,
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency>
下載JSP文件
改成
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>7.0.59</version> </dependency>
問題解決,至於爲何provided版本的不行,感興趣的小夥伴能夠深究下,留言給我。