我有一個關于@GetMappingSpring Boot 的問題。
如果我有 20 個靜態網頁作為.html檔案。我可以只使用一個@GetMapping來獲取每一頁嗎?
例如:
@GetMapping("/{static_webpages}")
public String getWeb() { return "{static_webpages}";}
然后,當路徑變為 時/page1,它將獲得第 1 頁,以此類推。
uj5u.com熱心網友回復:
從 URL 中提取網頁的名稱。
通過向您的方法添加引數并使用注釋對其進行@PathVariable注釋,您可以提取網頁的名稱。
@GetMapping("/{static_webpage}")
public String getWeb(@PathVariable("static_webpage") String webpage) {
...
}
回傳網頁而不是回傳字串
您可能不想以字串的形式回傳網頁內容。
通過使用ModelAndView物件作為方法的回傳型別,您的方法將回傳正確的網頁。
@GetMapping("/{static_webpage}")
public ModelAndView getWeb(@PathVariable("static_webpage") String webpage) {
...
}
現在我們可以構造ModelAndView物件以重定向到給定的網頁。
@GetMapping("/{static_webpage}")
public ModelAndView getWeb(@PathVariable("static_webpage") String static_webpage) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("webpages/" static_webpage);
return modelAndView;
}
在此示例中,靜態網頁被保存在resources/static/webpages目錄中,以便將它們分組到一個目錄中。
如果您不想將它們分組到一個目錄中,則只需將它們存盤在resources/static/,盡管您必須小心,因為該ModelAndView物件隨后會嘗試加載其自己的休息端點,這將導致錯誤。
[可選] 洗掉 url 中所需的 html 擴展名
使用您的spring.mvc.view.suffix屬性,您application.properties可以提供一個后綴,該后綴附加到您創建的每個 ModelAndView 網頁。
spring.mvc.view.suffix = .html
這意味著您不必訪問該網頁/myexamplepage.html
,您只需訪問/myexamplepage.
資源
- 模型和視圖
- @PathVariable
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/464394.html
上一篇:SpringAuthorizationServer在使用它進行身份驗證(和授權)時有哪些可能性?
下一篇:由于無法為公共抽象java.util.optional創建查詢而導致創建beanuserController時出錯
