SpringBoot番外篇之JSP使用
阿新 • • 發佈:2019-01-12
官方不推薦使用jsp作為前端頁面開發,jar包專案不支援jsp使用,jsp需要執行在servletContext中,war包需要執行在server伺服器中如tomcat;官方推薦使用thymeleaf,freemarker等模版引擎。這裡僅作為了解。
1、建立一個maven且web專案,新增pom依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!--使用外部tomcat,排除內建tomcat--> <!--<exclusions>--> <!--<exclusion>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-starter-tomcat</artifactId>--> <!--</exclusion>--> <!--</exclusions>--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--外接tomcat訪問時war使用,spring boot tomcat jsp 支援開啟,idea的pom裡面識別不了provided的,所以必須註釋掉--> <!--<dependency>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-starter-tomcat</artifactId>--> <!--<!–<scope>provided</scope>–>--> <!--</dependency>--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> </dependencies>
2、在classpath下建立application.properties或者application.yml,新增:
application.yml:
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
這樣controller就會去找/WEB-INF/jsp/目錄下的jsp檔案
3、編寫一個controller:
@Controller public class PageController { @RequestMapping(value = {"/","index"},method = RequestMethod.GET) public String index(Map<String, Object> model){ model.put("time", new Date()); model.put("message", "hello world springboot!"); return "page"; } }
4、在WEB-INF/page/下編寫一個page.jsp:
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Spring Boot Sample</title> </head> <body> <h2 align="center"> Time: ${time} <br> Message: ${message} </h2> </body> </html>
5、從瀏覽器訪問:http://localhost:8080 或 http://localhost:8080/index