準備學習SpringBoot,但是配置好項目後發現可以給前臺傳輸json數據,就是不能跳轉jsp頁面,查找好多資料發現SpringBoot官網強烈不推薦使用jsp,但是可以使用jsp。官方文檔:https://docs.spring.io/spring-boot/docs/1.5.5.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-template-engines
可是自己怎麼配置都訪問不到jsp,可以走到後臺。
啓動類配置如下:
@Configuration
@EnableAutoConfiguration
@ComponentScan
//@SpringBootApplication
/*相當於上面三個註解 @SpringBootApplication = (默認屬性)@Configuration + @EnableAutoConfiguration + @ComponentScan。*/
public class ApplicationMain {
@RequestMapping("/")
//@ResponseBody
String home() {
return "index";
}
public static void main(String[] args) {
SpringApplication.run(ApplicationMain.class, args);
}
}
pom.xml 配置如下:
<!-- springBoot版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<!-- spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
application.properties配置如下:
#內嵌tomcat配置
server.port=8089
server.tomcat.uri-encoding=UTF-8
#springmvc 頁面跳轉
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
項目結構如下:
Controller內容如下:
@Controller
@RequestMapping(value = "/freeMarkerController")
public class FreeMarkerController {
@GetMapping("index")
public String index() {
System.out.println("------index------");
return "index";
}
@RequestMapping("HelloWorld")
@ResponseBody
public String HelloWorld() {
System.out.println("-------HelloWorld------");
return "HelloWorld";
}
}
訪問http://localhost:8088/mark/HelloWorld 有數據
訪問 http://localhost:8088/mark/index 會出現
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Jan 02 11:53:32 CST 2018
There was an unexpected error (type=Not Found, status=404).
No message available
於是,查找官方文檔
在官方文檔中找到官方JSP示例 其中:
pom.xml 必須添加對jsp的支持:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
其中出現非常坑的問題:在Myeclipse 配置好了很快就能運行成功。在idea中怎麼配置都運行失敗,然後稀裏糊塗的又好了。很坑,浪費了好長時間在這。
訪問 http://localhost:8088/mark/index 就好跳轉到jsp頁面。
以上就是springBoot跳轉jsp 的配置。後續進行學習thymeleaf模板,另外
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
有模板這個jar的時候 SpringBoot會去找模板 默認路徑是classpath:/templates/*.html。