SpringBoot框架:第二章:SpringBoot中static和templates二個目錄下的頁面和靜態(tài)資源訪問的三個常見問題

靜態(tài)頁面:

在resources建立一個static目錄和index.htm靜態(tài)文件,訪問地址 http://localhost:8080/index.html
在這里插入圖片描述






spring boot項目只有src目錄,沒有webapp目錄,會將靜態(tài)訪問(html/圖片等)映射到其自動配置的靜態(tài)目錄,如下

/static

/public

/resources

/META-INF/resources

如果要從后臺跳轉(zhuǎn)到靜態(tài)index.html

@Controller
public class HtmlController {
	@GetMapping("/html")
	public String html() {
		return "/index.html";
	}

動態(tài)頁面:

使用Thymeleaf來做動態(tài)頁面,在pom.xml 中添加Thymeleaf組件

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

templates目錄為spring boot默認配置的動態(tài)頁面路徑

package hello;  
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.*;  
import org.springframework.web.bind.annotation.*;  
  
@Controller
public class TemplatesController {  
   
	@GetMapping("/templates")
	String test(HttpServletRequest request) {
		//邏輯處理
		request.setAttribute("key", "hello world");
		return "/index";
	}  
}  

index.html頁面:

 <!DOCTYPE html>
    <html>
    <span th:text="${key}"></span>
    </html>	

訪問地址:http://localhost:8080/templates

問題來了

第一個是:啟動項目之后,不需要進過后臺,直接localhost:8080就可以直接訪問templates中的index.html頁面,不是訪問static中的index.html頁面,這個要怎么設置?

回答:正常途徑應該是用nginx或apach代理服務器做跳轉(zhuǎn)

第二個是:需求是在templates目錄下的一個動態(tài)頁面index.html中有個超鏈接,訪問的是templates中另一個動態(tài)頁面cat.html頁面,而前端人員給的index.html中其中一個超鏈接是car,頁面不好改動,但是不改動,這樣寫訪問的是static中的靜態(tài)頁面,要怎么設置才能訪問同一templates目錄各個動態(tài)頁面之間的跳轉(zhuǎn)。

回答:動態(tài)頁面目錄不能用靜態(tài)方式跳轉(zhuǎn),動態(tài)頁面跳轉(zhuǎn),只能通過控制層,但是頁面上有許多要跳轉(zhuǎn)動態(tài)頁面的超鏈接,寫很多個到控制層也不是很好,所以可以使用xml配置:

標簽是view-controller
屬性:path
屬性:view-name

第三個是:訪問http://localhost:8080/templates頁面之后,頁面之后引入了static目錄中的css,js等等靜態(tài)資源,可是頁面訪問不到static里面的靜態(tài)資源

回答:如果是訪問js,css表態(tài)資源,用絕對路徑, / 斜杠開頭??刂茖佑成渎窂揭?/ 斜杠開頭