SpringBoot学习(4)SSM(SpringBoot)+Thymeleaf实现简单的查询用户信息

前言

记录学习过程
前接(3)SpringBoot+Thymeleaf
(2)搭建一个完整的项目 SpringBoot+SpringMVC+MyBatis
前面已经完成了SpringBoot+SpringMVC+MyBatis+Thymeleaf的搭建,现在简单实现一个查询用户信息

步骤

完整的架构

在这里插入图片描述

数据库信息

前面已经完成了对数据库的操作,略
在这里插入图片描述

SSM框架搭建

(2)搭建一个完整的项目 SpringBoot+SpringMVC+MyBatis中实现了通过一个id查询用户信息,现在需要实现前端传递id,后端返回用户信息给前端

实现前后端结合

(3)SpringBoot+Thymeleaf中完成了Thymeleaf的布置,接下来完成前后端结合

  • 控制器接收请求并响应

创建UserController,将得到的user对象存入model中

package com.test.springboottest.controller;


import com.test.springboottest.entity.User;
import com.test.springboottest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


@Controller
@RequestMapping("/test")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getUser",method = RequestMethod.POST)
    public String GetUser(@RequestParam(name = "id") int id, Model model){
        User user=userService.Sel(id);
        model.addAttribute("user",user);
        return "index";
    }
}

  • SpringBoot+Thymeleaf设置默认界面FirstHtmlController

因为默认界面是index.html,这里改成getUser.html更方便
在这里插入图片描述

package com.test.springboottest.controller;

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

@Controller
public class FirstHtmlController  {
    @RequestMapping("/")
    public String toFirstHtml(){
        return "getUser";
    }
}

记得在属性文件application-dev.yml中改前缀后缀
在这里插入图片描述

  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
  • 查找界面getUser.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>GetUser</title>
</head>
<body>
    <form th:action="@{/test/getUser}" method="post">
        查找用户:<input type="text" name="id"><br>
        <input type="submit"  value="提交"><br>
    </form>

</body>
</html>
  • 显示信息界面index.html
    其中th:object获得后端传递的对象
    然后{user.id}根据对象的属性名得到属性值
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>index</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p style="color: red">Welcome</p>
<div th:object="${user}">
    ID:<div th:text="${user.id}">ID</div>
    userName:<div th:text="${user.userName}">userName</div>
    passWord:<div th:text="${user.passWord}">passWord</div>
</div>
</body>
</html>
  • 完成测试
    查找id=1的用户

NO BUG!!!
在这里插入图片描述
在这里插入图片描述获得信息:
在这里插入图片描述ok,完美
以上传项目
学习自取

发布了49 篇原创文章 · 获赞 0 · 访问量 1243

猜你喜欢

转载自blog.csdn.net/key_768/article/details/104145903