1. 程式人生 > >上手spring boot專案(一)之如何在controller類中返回到頁面

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

題記:在學習了springboot和thymeleaf之後,想完成一個專案練練手,於是使用springboot+mybatis和thymeleaf完成一個部落格系統,在完成的過程中出現的一些問題,將這些問題記錄下來,作為自己的學習心得。在這先感謝群主TyCoding的Tumo專案,雖然本人實在太菜了,好些地方看不懂,但還是使我受益匪淺。


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

1.不使用模板

1.1使用ModelAndView作為返回值

@Controller
public class LoginController {

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

資源路徑如下:

 

 啟動專案後結果如下:

1.2使用String作為返回值

@Controller
public class HelloController {

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

資源路徑如下:

 

 啟動專案後結果如下:

 通過這兩種方式可以發現controller類中返回的是在static中的login.html和hello.html。

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

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網址了

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

2.4 啟動專案

 

通過這兩種方式可以發現controller類中返回的是在templates中的login.html和hello.html。

結論:springboot中整合templates之後靜態資源預設是放在templates路徑下的,也就是html等頁面的根路徑是template