天天看點

springboot加載templates下html

建議直接複制粘貼

目錄

​​LoginController​​

​​ login.html​​

​​application.properties ​​

LoginController

package com.example.demo.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

//http://localhost:8090/login
@Controller
public class LoginController {
    /**
     * 登入頁面
     * @return
     */
    @GetMapping("/login")
    public String login() {
        // 這裡傳回的login指的是src/main/resources/templates目錄下的login.html
        // 是以,我們需要在src/main/resources/templates目錄下建立一個login.html
        // 當我們通過浏覽器通路localhost:8080/login時即可通路到我們編寫的login.html
        return "login";
    }
}      
springboot加載templates下html

 login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登入頁面</title>
</head>
<body>
<h2>登入頁面</h2>
<form>
    賬号: <input type="text" name="username"><br>
    密碼: <input type="password" name="password"><br>
    <input type="submit" value="登入">
</form>
</body>
</html>      

application.properties 

server.port= 8090
mybatis.mapper-locations= classpath:mapping/*.xml

spring.datasource.name= miaosha
spring.datasource.url= jdbc:mysql://127.0.0.1:3306/miaosha?serverTimezone=Asia/Shanghai
spring.datasource.username= root
spring.datasource.password= 123456


spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName= com.mysql.cj.jdbc.Driver
spring.thymeleaf.prefix=classpath:/templates/      
springboot加載templates下html
springboot加載templates下html

為什麼換了controller注解就好了呢?

@RestController is a stereotype annotation that combines @ResponseBody and @Controller.

意思是:

@RestController注解相當于@ResponseBody + @Controller合在一起的作用。

1)如果隻是使用@RestController注解Controller,則Controller中的方法無法傳回jsp頁面,配置的視圖解析器InternalResourceViewResolver不起作用,傳回的内容就是Return 裡的内容。

例如:本來應該到login.html頁面的,則其顯示login.

2)如果需要傳回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。

3)如果需要傳回json或者xml或者自定義mediaType内容到頁面,則需要在對應的方法上加上@ResponseBody注解

@ResponseBody:

作用:

該注解用于将Controller方法傳回的對象,通過适當的HttpMessageConverter轉換為指定格式後(如:json格式),寫入到Response對象的body資料區。

使用時機: