前后端分離的架構(gòu)有其優(yōu)勢(shì),但具體情況具體分析,并不是任何時(shí)候使用前后端分離架構(gòu)都是合適的。我最近就體會(huì)到其中的坑,因?yàn)椴块T(mén)屬性的問(wèn)題,前端項(xiàng)目占比較低,所以公司前端基本上都是新手,結(jié)果就是后端接口完成了一個(gè)多月,前端還在加班加點(diǎn)的趕。前后端人員的能力和人數(shù)與工作量是匹配的,前后端都能hold住時(shí)建議使用前后端分離架構(gòu),如果前端能力有限或人員較少,那就最好不要采用,這樣才能保證項(xiàng)目進(jìn)度可控。
Spring Boot并不建議使用JSP,但是可能有習(xí)慣和人員知識(shí)面的限制,還是希望使用jsp,則可以根據(jù)下面的教程來(lái)了解如何在spring boot項(xiàng)目?jī)?nèi)使用jsp。
1、添加maven依賴
<!-- 添加對(duì)jsp視圖解析的支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
2、添加配置
在application.properties內(nèi)添加以下配置:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
3、創(chuàng)建jsp
- 創(chuàng)建src/main/webapp/WEB-INF/jsp目錄,目錄結(jié)構(gòu)不要改動(dòng)
- 在src/main/resources目錄下創(chuàng)建static目錄用于存放靜態(tài)資源,如image目錄用于存放圖片,js目錄用于存放js文件
- 創(chuàng)建jsp文件,如test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
</head>
<body>
hello,welcome to you 123!test=[${test }] test2=[${test2 }]
<br>

<c:if test="${1 == 1 }"><br>this is ShangHai,china!</c:if>
</body>
</html>
- ${pageContext.request.contextPath }用于獲取項(xiàng)目路徑,即server.context-path設(shè)置的值
- 訪問(wèn)圖片${pageContext.request.contextPath }/image/1.jpg,也就是src/main/resources/static/image/1.jpg文件,注意直接訪問(wèn)/image/1.jpg即可
- 加載js路徑為${pageContext.request.contextPath }/js/jquery.min.js,同圖片,加載靜態(tài)資源的方式類似
4、訪問(wèn)jsp
創(chuàng)建controller
@Controller
public class TestController {
@RequestMapping("/test")
public String myJsp(HttpServletRequest request,ModelMap model){
System.out.println("myjsp");
model.put("test", "test");
request.setAttribute("test2", "test2");
return "test";
}
}
啟動(dòng)項(xiàng)目后,訪問(wèn)localhost:port/test就可以看到上面的示例頁(yè)面了。