上手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等頁面的根路徑是templates。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM