2017-03-08 124 views
0

我正在開發一個使用Thymeleaf作爲視圖技術的Spring啓動應用程序。我在src/main/resources/templates文件夾中有一個html頁面dashboard.html,它是從控制器內部調用的。Thymeleaf - 如何從靜態html頁面調用模板html頁

enter image description here

@PostMapping("https://stackoverflow.com/users/register") 
public String registerUser(@Validated @ModelAttribute User user, Model model) { 
    User registeredUser = usersDAO.registerUser(user); 

    if (registeredUser == null) { 
     return "500error"; 
    } 

    model.addAttribute("name", user.getName()); 
    model.addAttribute("username", user.getUsername()); 
    model.addAttribute("emailId", user.getEmailId()); 

    return "dashboard"; 
} 

static文件夾內的一些靜態HTML文件。我想從靜態html文件中調用dashboard.html,比如使用錨定標記<a/>。如何才能做到這一點?

當我的應用程序在本地運行時,我無法直接鏈接到此文件。例如:localhost:8080/templates/dashboard.html將不起作用。

+0

這裏不是真的你的問題,但重要的是:在用戶爲'null'的情況下,你不應該只顯示一個正確的錯誤頁面,而是確保使用正確的HTTP代碼。使用當前的代碼,您仍然會返回200 OK。最簡單的方法是拋出一個用'@ ResponseStatus'註釋的異常。 –

+0

src/main/resources不是存儲html頁面的好地方 –

+0

@Gurkanİlleez如果您在Thymeleaf啓動器中使用Spring Boot,src/main/resources/templates是默認位置。我同意在'static'子目錄中有一些html頁面是很奇怪的。大多數情況下,這用於CSS,JS和/或圖像文件。 –

回答

2

您應該爲您的thymeleaf html模板創建一個控制器。例如:

@Controller 
@RequestMapping("/templates") 
public class DashboardController { 

    @GetMapping("/dashboard") 
    public ModelAndView dashboard() { 
     DashboardModel dashboardModel = new DashboardModel(); 
     return new ModelAndView("dashboard", "dashboard", dashboardModel); 
    } 

} 

然後你就可以鏈接到http://localhost:8080/templates/dashboard,讓你的dashboard.html頁。

當然,您可以根據需要更改@RequestMapping("/templates")@GetMapping("/dashboard")以控制網址。

+0

請注意,你不需要在控制器的@ RequestMapping中使用'/ templates',這可以是你喜歡的任何東西,它仍然可以工作。 –

+0

@WimDeblauwe,當然:)我使用'/ templates/dashboard',因爲他提到的url模式是一個例子。和你一起編輯我的回答。 – Tom