1. 程式人生 > >SpringBoot實戰之8 整合jsp模版引擎

SpringBoot實戰之8 整合jsp模版引擎

歷史文章

一、簡介

springboot支援多種模版引擎包括:
1. FreeMarker
2. Groovy
3. Thymeleaf (Spring 官網使用這個)
4. Velocity
5. JSP (貌似Spring Boot官方不推薦)

不過本文還是選擇大家都熟悉的JSP來作為研究案例。

二、導包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId
>
</dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId
>
</dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>

三、controller層

@Controller
public class ViewController {

    /**
     * @description <p></p>
     * @return
     * @author heshiyuan
     * @date
2017/12/2 20:56 */
@RequestMapping(value = {"/","/index"}) public String index(HttpServletRequest request){ request.setAttribute("content","this is index"); request.setAttribute("time", Calendar.getInstance().getTime()); // 自動對映到"/WEB-INF/jsp/"下 return "index" ; } @RequestMapping("/toPage1View") public String page1(Model model){ model.addAttribute("time",Calendar.getInstance().getTime()) ; model.addAttribute("content","this is page1"); return "page/page1" ; } @RequestMapping("/toPage2View") public ModelAndView page1(ModelAndView modelAndView){ modelAndView.setViewName("page/page2"); modelAndView.addObject("time",Calendar.getInstance().getTime()) ; modelAndView.addObject("content","this is page1") ; return modelAndView; } }

四、配置檔案

spring.thymeleaf.cache=false
spring.thymeleaf.enabled=false
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

五、配置頁面

index.html

<%@page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>主頁</title>
</head>
<body>
    ${content}
    ${time}
</body>
</html>

page/page1.jsp page/page2.jsp均是類似的頁面。

六、啟動

@SpringBootApplication
public class SpringBootJspApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootJspApplication.class,args);
    }
}

七、專案結構圖

這裡寫圖片描述

最後

此demo最後沒有執行執行成功,提示如下錯誤,正在解決當中,有線索的道友感謝提供幫助。
這裡寫圖片描述