1. 程式人生 > >【轉載】spring-boot 專案跳轉到JSP頁面

【轉載】spring-boot 專案跳轉到JSP頁面

原路徑:https://blog.csdn.net/qq_36820717/article/details/80008225

1、新建spring-boot專案  目錄結構如下

2、新建TestController.java檔案,內容如下

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";
}
}
3、新建webapp資料夾,與resources同級。

 

4、新建JSP頁面,此時發現New裡面沒有JSP頁面。需要設定一下才會出現喲。

 

 

5、點選File->Project Structure...

 

 

6、點選Modules->綠色加號->Web

 

 

7、雙擊此處

 

 

8、選擇剛剛新建的webapp,點選OK,繼續OK。

 

 

9、此時webapp上有個藍色圓點表示設定成功。

 

 

10、在webapp上單擊右鍵New,此時出現JSP檔案。

 

 

11、新建index.jsp

 

 

12、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>
13、新建MyWebAppConfigurer類

 

14、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;
}

}
15、在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>
16、啟動Application,訪問127.0.0.1:8080/index

 

 

17、跳轉完成。

 

以上就是spring-boot跳轉JSP頁面的過程,下面說說跳轉遇到的坑。

一、缺少依賴JAR包

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
跳轉失敗

 


提示還算明確,缺少jstl標籤

二、使用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版本的不行,感興趣的小夥伴可以深究下,留言給我。

綜上所述,兩個依賴JAR包一個都不能少。
---------------------
作者:黃粱大夢
來源:CSDN
原文:https://blog.csdn.net/qq_36820717/article/details/80008225