spring boot 同時支援jsp和freemarker的配置
專案採用spring boot框架,而且需要jsp開發,但spring boot預設不支援 jsp頁面,官網也提到不建議使用jsp頁面,至於什麼原因還沒來得及研究。由於對框架不 熟悉,在配置的時候花費了一天時間,現在把個人配置支援jsp頁面的方式記錄下來,供遇到同樣問題的小夥伴參考。
0.首先在application.yml中註釋掉 以下內容
#freemarker:
# suffix: .html#request-context-attribute: request
1.在WebConfig.java中新增以下程式碼
/**
* 新增對jsp的支援
*
* @return
*/
@Bean
public ViewResolver getJspViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
internalResourceViewResolver.setSuffix(".jsp");
internalResourceViewResolver.setOrder(1);
return internalResourceViewResolver;
}
/**
* 新增對Freemarker支援
*
* @return
*/
@Bean
public FreeMarkerViewResolver getFreeMarkerViewResolver() {
FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
freeMarkerViewResolver.setCache(true);
freeMarkerViewResolver.setPrefix("");
freeMarkerViewResolver.setSuffix(".html");
freeMarkerViewResolver.setRequestContextAttribute("request");
freeMarkerViewResolver.setOrder(0);
freeMarkerViewResolver.setContentType("text/html;charset=UTF-8");
return freeMarkerViewResolver;
}
2.在pom.xml新增對jsp的支援
<!-- Spring Boot支援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>
3.在Controller中返回頁面就可以了
希望對大家有用!