做WEB項目,一定都用過JSP這個大牌。Spring MVC里面也可以很方便的將JSP與一個View關聯起來,使用還是非常方便的。當你從一個傳統的Spring MVC項目轉入一個Spring Boot項目后,卻發現JSP和view關聯有些麻煩,因為官方不推薦JSP在Spring Boot中使用。在我看來,繼續用這種繁雜的手續支持JSP僅僅只是為了簡單兼容而已。
我們先來看看如何在SpringBoot中使用JSP ?
1. 在pom.xm中加入支持JSP的依賴
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
2. 在src/main/resources/application.properties文件中配置JSP和傳統Spring MVC中和view的關聯
# MVC spring.view.prefix=/WEB-INF/views/ spring.view.suffix=.jsp
3. 創建src/main/webapp/WEB-INF/views目錄,JSP文件就放這里
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
Hello ${name}
</body>
</html>
4. 編寫Controller
package com.chry.study;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller @EnableAutoConfiguration public class SampleController { @RequestMapping("/hello") public ModelAndView getListaUtentiView(){ ModelMap model = new ModelMap(); model.addAttribute("name", "Spring Boot"); return new ModelAndView("hello", model); } }
5. 編寫Application類
package com.chry.study; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class WebApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(WebApplication.class); } public static void main(String[] args) throws Exception { SpringApplication.run(WebApplication.class, args); } }
6. 以java application方式運行后,就可以訪問http://locahost:8080/hello
================== 分割線 ==================================
以上代碼pom.xml中的javax.servlet.jsp.jstl是用於支持JSP標簽庫的,在Web2.5的容器中沒有問題,單當你的容器是Web3.0或以上版本時,就會出問題。 這是個非常坑爹的問題。
javax.servlet.jsp.jstl會自動加載依賴servlet-api-2.5.jar, 而且會在實際運行時把支持Web3.0的3.1版本的javax.servlet-api覆蓋掉。即使你在pom.xml顯示的在加入3.1版本的javax.servlet-api也沒用。導致SpringBoot應用拋出Runtime exception運行錯誤。
這是一個不可調和的矛盾,要嗎不用javax.servlet.jsp.jstl,要嗎不用Web3.0。
但絕大多數情況下,jstl標簽庫不是必須的,而Web3.0是必須的。替代方式就是不用JSP,改用Themeleaf吧