上手spring boot項目(一)之如何在controller類中返回到頁面

題記:在學習了springboot和thymeleaf以後,想完成一個項目練練手,因而使用springboot+mybatis和thymeleaf完成一個博客系統,在完成的過程當中出現的一些問題,將這些問題記錄下來,做爲本身的學習心得。在這先感謝羣主TyCoding的Tumo項目,雖然本人實在太菜了,好些地方看不懂,但仍是使我受益不淺。html


在controller類中返回到頁面中一共有兩種方式,使用thymeleaf模板引擎的方式和不使用模板的方式(即controller的返回值爲ModelAndView或者String)。在controller類中返回值爲ModelAndView或者String,兩者的區別就在於ModelAndView可以像session同樣存儲一些屬性。spring

1.不使用模板

1.1使用ModelAndView做爲返回值

@Controller
public class LoginController {

    @RequestMapping(value = "/login")
    public ModelAndView login(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/login.html");
        return mv;
    }
}

資源路徑以下:springboot

 

 啓動項目後結果以下:session

1.2使用String做爲返回值

@Controller
public class HelloController {

@RequestMapping("/hello")
public String hello() {
return "/hello.html";
}
}

資源路徑以下:mybatis

 

 啓動項目後結果以下:app

 經過這兩種方式能夠發現controller類中返回的是在static中的login.html和hello.html。學習

結論:springboot中靜態資源默認是放在static路徑下的,換而言之就是html等頁面的根路徑是staticspa

2.使用thymeleaf模板引擎

2.1 在pom文件中引入依賴

 2.2 在application.yml文件中添加配置信息

# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false

2.3 編寫controller類&html代碼

因爲這裏的controller類和html頁面路徑與前面的同樣,我就不貼上代碼了。因爲只是演示展現頁面,因此就未在html標籤中添加thymeleaf網址了code

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2.4 啓動項目

 

經過這兩種方式能夠發現controller類中返回的是在templates中的login.html和hello.html。xml

結論:springboot中整合templates以後靜態資源默認是放在templates路徑下的,也就是html等頁面的根路徑是templates。

相關文章
相關標籤/搜索