天天看点

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数据区。

使用时机: