用springboot+mybatis+MySQL+thymeleaf做前后端交互的增删改查
遇到的小问题记录一下
1,前后端写的都没问题,当输入网址后跳转不到页面,只return了一个字符串,要跳转的页面的地址名称,如下图,页面不出现数据,只有"findAll"
/* 查询全部 */
@RequestMapping("/findAll")
public String UserList(Model model) {
List<User> users = userService.findAll();
model.addAttribute("u", users);
return "findAllba";
}
原因:HTML页面用了thymeleaf框架但没有配置pom依赖和没有进行yaml配置
解决办法:要进行两步
第一步.在pom文件导入依赖包代码如下
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
第二步.在yaml文件配置,代码如下
thymeleaf:
cache: false
encoding: utf-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
这样就可以从后端跳转至前端页面啦。
2.<form>的action和<a>的href的问题
这是查看全部数据的页面代码,添加数据的按钮我是用<a>标签写的
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<title>列表展示</title>
</head>
<body>
<h2>用户列表</h2>
<a href="/insert">添加</a>
<table border="1">
<thead>
<tr>
<td>编号</td>
<td>用户名</td>
<td>密码</td>
<td>操作</td>
</tr>
</thead>
<!-- <th:forEach items="${user}" var="s" varStatus="st">-->
<tr th:each="s:${u}">
<td th:text="${s.id}"></td>
<td th:text="${s.username}"></td>
<td th:text="${s.password}"></td>
<td>
<a th:href="@{'/delete/'+${s.id}}">删除</a>
<a th:href="@{'/updateUser/'+${s.id}}">修改</a>
</td>
</tr>
</table>
</body>
</html>
可以跳转到添加数据的页面
添加数据的页面代码如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<title>添加新用户</title>
</head>
<body>
<div>
<form action="/adduser" method="post">
ID:<input class="form-control" type="text" th:value="${id}" name="id"><br>
用户名:<input class="form-control" type="text" th:value="${username}" name="username"><br>
密码:<input class="form-control" type="text" th:value="${password}" name="password"><br>
<button>保存</button>
</form>
</div>
</body>
</html>
开始我没有用<form>表单,直接用的a标签的href,页面跳转到了我要的页面,然而所添加的数据并没有进入到数据库,数据库为空。
原因:
form可以指定是get还是post方式提交 a标签只能是get方式。post可以传递更多内容而且更安全,form表单也可以使用get方式提交。
1.href是a元素的链接,表示点击a元素需要跳转到哪里。href 网页链接; 静态的 html。href只能get一些参数
2.action是form表单的地址,表示表单需要提交到哪个地址。action是form表单的属性,提交到后台处理[处理后再跳转];动态的。而action既能get参数又能post参数。
你可以把href理解为一个页面的动作,表示点击超链接后去了哪里!
而action可以理解为事件的行为,具体是在后台做了些什么。
我理解的是,href只能跳转到指定页面,不能传递数据,action可以带数据跳转。