Springboot的static和templates區別


static和templates部分參考博客:https://blog.csdn.net/wangb_java/article/details/71775637

熱部署參考博客:https://www.cnblogs.com/cx-code/p/8686453.html

 

SpringBoot里面沒有我們之前常規web開發的WebContent(WebApp),它只有src目錄

在src/main/resources下面有兩個文件夾,static和templates   springboot默認  static中放靜態頁面,而templates中放動態頁面

 

靜態頁面:

 這里我們直接在static放一個hello.html,然后直接輸入http://localhost:8080/hello.html便能成功訪問

(好像可以新建一個public文件夾,也可以放靜態文件)

也可以通過controller跳轉:

復制代碼
@Controller
public class HelloController {

    @RequestMapping("/Hi")
    public String sayHello() {
        return "hello.html";
    }
    
}
復制代碼

然后輸入http://localhost:8080/Hi就可以成功訪問

 

 

動態頁面:

動態頁面需要先請求服務器,訪問后台應用程序,然后再轉向到頁面,比如訪問JSP。spring boot建議不要使用JSP,默認使用Thymeleaf來做動態頁面。

現在pom中要添加Thymeleaf組件

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency>  

 

我們先在tempates文件夾中也新建一個hello.html但內容不同,然后先試一下直接訪問該頁面。輸入http://localhost:8080/hello.html:

結果顯然訪問的是靜態問價夾里面的那個hello.html

 然后我們現在再試一下用controller:

似乎無法訪問到hello.html了。。。這是因為:

靜態頁面的return默認是跳轉到/static/index.html,當在pom.xml中引入了thymeleaf組件,動態跳轉會覆蓋默認的靜態跳轉,默認就會跳轉到/templates/index.html,注意看兩者return代碼也有區別,動態沒有html后綴。

 

也就是我們要這樣改controller:

復制代碼
@Controller
public class HelloController {

    @RequestMapping("/Hi")
    public String sayHello() {
        return "hello";
    }
    
}
復制代碼

然后就可以成功跳轉了

 

 

然后我們看看返回一點數據在前端利用Thyemleaf來拿:

復制代碼
@Controller
public class HelloController {

    @RequestMapping("/Hi")
    public ModelAndView sayHello() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("key", 12345);
        //System.out.println("test");
        return modelAndView;
    }
    
}
復制代碼
復制代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Insert title here</title>

</head>
<body>
<h1>this is the hello.html in templates</h1>
<span th:text="${key}"></span>  
</body>
</html>
復制代碼

效果:

 

 

 

如果不想返回視圖,則用@RestController

 

 

如果用了靜態模板你還想返回static中的頁面,那么就要用重定向:

如果在使用動態頁面時還想跳轉到/static/index.html,可以使用重定向return "redirect:/index.html"。

return "redirect:hello.html";  

 

 

 

幾點tips:

1.攔截的url最后不要跟視圖重合,否則會拋出Circular view path異常,我之前就是

復制代碼
@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String sayHello() {
        return "hello.html";  
    }
    
}
復制代碼

 

然后就報錯說會有個循環視圖的錯誤,反正以后注意就是。

 

2.每次改完都要重新停止應用,再重新啟動很煩~但springboot有個叫熱部署的東西,就是說在項目中修改代碼可以不用重新停止應用再重新啟動,可以自動重啟,這里我們用的是devtools:

具體見博客:https://www.cnblogs.com/cx-code/p/8686453.html


免責聲明!

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



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