1. 程式人生 > >轉:如何在SpringBoot中使用JSP ?但強烈不推薦,果斷改Themeleaf吧

轉:如何在SpringBoot中使用JSP ?但強烈不推薦,果斷改Themeleaf吧

做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吧

 

轉自:https://www.cnblogs.com/chry/p/5912870.html