SpringBoot學習筆記4-SpringBoot 使用 JSP

【Android免費音樂下載app】【佳語音樂下載】建議最少2.0.3版本。最新版本:
https://gitlab.com/gaopinqiang/checkversion/raw/master/Music_Download.apk

在Spring boot中使用jsp,按如下步驟進行:
1、在pom.xml文件中配置依賴項

	<!--引入Spring Boot內嵌的Tomcat對JSP的解析包-->
	<dependency>
		<groupId>org.apache.tomcat.embed</groupId>
		<artifactId>tomcat-embed-jasper</artifactId>
	</dependency>

	<!-- servlet依賴的jar包start -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
	</dependency>
	<!-- servlet依賴的jar包start -->

	<!-- jsp依賴jar包start -->
	<dependency>
		<groupId>javax.servlet.jsp</groupId>
		<artifactId>javax.servlet.jsp-api</artifactId>
		<version>2.3.1</version>
	</dependency>
	<!-- jsp依賴jar包end -->

	<!--jstl標籤依賴的jar包start -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
	</dependency>
	<!--jstl標籤依賴的jar包end -->

2、在application.properties文件配置spring mvc的視圖展示爲jsp:

	#前端視圖展示使用jsp
	spring.mvc.view.prefix=/
	spring.mvc.view.suffix=.jsp

3、在src/main 下創建一個webapp目錄,然後在該目錄下新建index.jsp頁面

<html>
    <p>${msg}</p>
</html>

4、編寫Controller
新建一個JSPController

package com.springboot.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class JSPController {

	@GetMapping("/index")
	public String index(Model model){
		model.addAttribute("msg","Spring Boot 集成JSP");

		return "index";
	}
}

備註:一定要在**@Controller這個註解的類裏面才能識別成index.jsp,如果是@RestController中使用就直接json數據返回了**。

5、測試
去瀏覽器中請求:http://localhost:8081/index
正常輸出結果:Spring Boot 集成JSP

遇到2個問題
a.遇到一個找不到頁面問題,如下圖:
在這裏插入圖片描述

解決方法:
如果不加下面這個可能會出現部署的時候找不到JSP提示404,在pom.xml的build標籤中添加

	<resources>

		<resource>
			<directory>src/main/java</directory>
			<includes>
				<include>**/*.xml</include>
			</includes>
		</resource>

		<resource>
			<directory>src/main/resources</directory>
			<includes>
				<include>**/*.*</include>
			</includes>
		</resource>

		<resource>
			<directory>src/main/webapp</directory>
			<targetPath>META-INF/resources</targetPath>
			<includes>
				<include>**/*.*</include>
			</includes>
		</resource>

	</resources>

b、遇到一個瀏覽器出現中文亂碼問題,如下圖
在這裏插入圖片描述

解決方法:
在application.properties中設置下:

#解決中文編碼問題
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章