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

靜態(tài)頁(yè)面:

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






spring boot項(xiàng)目只有src目錄,沒(méi)有webapp目錄,會(huì)將靜態(tài)訪問(wèn)(html/圖片等)映射到其自動(dòng)配置的靜態(tài)目錄,如下

/static

/public

/resources

/META-INF/resources

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

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

動(dòng)態(tài)頁(yè)面:

使用Thymeleaf來(lái)做動(dòng)態(tài)頁(yè)面,在pom.xml 中添加Thymeleaf組件

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

templates目錄為spring boot默認(rèn)配置的動(dòng)態(tài)頁(yè)面路徑

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頁(yè)面:

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

訪問(wèn)地址:http://localhost:8080/templates

問(wèn)題來(lái)了

第一個(gè)是:?jiǎn)?dòng)項(xiàng)目之后,不需要進(jìn)過(guò)后臺(tái),直接localhost:8080就可以直接訪問(wèn)templates中的index.html頁(yè)面,不是訪問(wèn)static中的index.html頁(yè)面,這個(gè)要怎么設(shè)置?

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

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

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

標(biāo)簽是view-controller
屬性:path
屬性:view-name

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

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