需求分析
- 现在实现如下所示的删除功能,主要亮点同样是学习 Thymeleaf 操作
UserDaoImpl
package com.lct.dao;
import com.lct.domain.Department;
import com.lct.domain.User;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Repository
public class UserDaoImpl {
@Resource
private DepartmentDaoImpl departmentDao;
/**
* 默认的用户列表数据,暂时就不通过数据库了,直接初始化一些数据进行模拟
*/
private static List<User> userList = null;
static {
userList = new ArrayList<>();
userList.add(new User(1001, "E-AA", "[email protected]", 1, new Department(101, "系统部")));
userList.add(new User(1002, "E-BB", "[email protected]", 1, new Department(102, "研发部")));
userList.add(new User(1003, "E-CC", "[email protected]", 0, new Department(103, "采购部")));
userList.add(new User(1004, "E-DD", "[email protected]", 0, new Department(104, "财务部")));
userList.add(new User(1005, "E-EE", "[email protected]", 1, new Department(105, "后勤部")));
}
/**
* 模拟查询所有员工
*/
public List<User> getAll() {
return userList;
}
/**
* 根据id 查找用户
*
* @param id
* @return
*/
public User getUserById(Integer id) {
for (User user : userList) {
System.out.println(user.getUId() + " PPPPP " + id);
if (user.getUId().equals(id)) {
return user;
}
}
return null;
}
/**
* 添加用户
*
* @param user
*/
public void saveUser(User user) {
if (user == null) {
return;
}
/**
* 动态修改主键id
*/
if (userList.size() == 0) {
user.setUId(1);
} else {
user.setUId(userList.get(userList.size() - 1).getUId() + 1);
}
/**
* 因为页面传入的 Department 只有depId,所以根据id查询它整个实体回来
*/
user.setDepartment(departmentDao.getDepartmentById(user.getDepartment().getDepId()));
userList.add(user);
}
/**
* 修改用户
*
* @param user
*/
public void updateUser(User user) {
if (user != null) {
/** 因为页面提交的用户管理的部门数据只有部门id,所以要二次查询*/
user.setDepartment(departmentDao.getDepartmentById(user.getDepartment().getDepId()));
for (int i = 0; i < userList.size(); i++) {
if (userList.get(i).getUId().equals(user.getUId())) {
userList.set(i, user);
break;
}
}
}
}
/**
* 根据用户id删除用户
*
* @param user
*/
public void delUserById(Integer userId) {
if (userId != null) {
for (int i = 0; i < userList.size(); i++) {
if (userList.get(i).getUId().equals(userId)) {
userList.remove(i);
break;
}
}
}
}
}
UserController
package com.lct.controller;
import com.lct.dao.DepartmentDaoImpl;
import com.lct.dao.UserDaoImpl;
import com.lct.domain.Department;
import com.lct.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* Created by Administrator on 2018/7/28 0028.
* 用户控制器层
*/
@Controller
@RequestMapping("user")
public class UserController {
@Resource
private UserDaoImpl userDao;
@Resource
private DepartmentDaoImpl departmentDao;
/**
* 用户登录
*
* @param username 账号
* @param password 密码
* @param httpSession 设值登录的 用户session
* @return 登录成功 重定向到 用户列表页面
* @PostMapping ("login") 相当于 @RequestMapping(value = "login",method = RequestMethod.POST) 的简写
* 同理还有 @GetMapping 、@PutMapping 、@DeleteMapping
*/
@PostMapping("login")
public String login(String username, String password, HttpSession httpSession) {
/**
* 当账号不为空,密码为 123456 时,模拟登录成功,否则失败时重定向返回登录页面
*/
if (!StringUtils.isEmpty(username) && "123456".equals(password)) {
httpSession.setAttribute("userName", username);
return "redirect:/user/users";
} else {
/** 往服务器重定向时 要以 "/" 开头表示应用根地址*/
return "redirect:/index";
}
}
/**
* 页面点击 "商品销量" 链接时 进入,然后跳转到 products.html 页面
*
* @return
*/
@GetMapping("products")
public String priduct() {
return "products";
}
/**
* 跳转到用户列表页面
*
* @param model 用户设值返回页面
* @return
*/
@GetMapping("users")
public String findAllUsers(Model model) {
List<User> userList = userDao.getAll();
model.addAttribute("userList", userList);
/** 往前端 Thymeleaf 模板引擎时,开头不要加 "/" ,因为它默认配置就是:
* 前缀:spring.thymeleaf.prefix=classpath:/templates/
* 后缀:spring.thymeleaf.suffix=.html */
return "userList";
}
/**
* 用户添加前页面跳转-----用户点击"用户添加"按钮时,进入此处进行跳转到添加页面
*
* @param model
* @return
*/
@GetMapping(value = "userCRUD")
public String toAddUser(Model model) {
/**
* 因为用户添加页面上,需要选择用户属于哪个部门,所以要将部门数据全部带出去
*/
List<Department> departmentList = departmentDao.getDepartments();
model.addAttribute("departmentList", departmentList);
/** 往前端 Thymeleaf 模板引擎时,开头不要加 "/" ,因为它默认配置就是:
* 前缀:spring.thymeleaf.prefix=classpath:/templates/
* 后缀:spring.thymeleaf.suffix=.html */
return "userAdd";
}
/**
* 用户添加-----用户添加提交时进入
* <p/>
* SpringMVC 自动将请求参数和入参对象的属性进行一一映射绑定
* 要求是请求参数的名字和 User 的属性名一样
*
* @param user
* @return
*/
@PostMapping(value = "userCRUD")
public String addUser(User user) {
/**
* 保存数据
*/
userDao.saveUser(user);
/** redirect: 表示重定向到一个后台地址 " /" 代表当前项目路径
* forward: 表示转发到一个后台地址
* 两者都是get请求方式
*/
return "redirect:/user/users";
}
/**
* 用户编辑前页面跳转-----用户点击"编辑"按钮时,进入此处进行跳转到编辑页面
* 因为编辑与添加页面一致,所以采用同一个页面,当然可以复制一份新的
*
* @param userId :待修改的用户id
* @param model
* @return
*/
@GetMapping(value = "userCRUD/{userId}")
public String toEditUser(@PathVariable(value = "userId") Integer userId, Model model) {
/**
* 查询出用户数据已经所有部门数据返回
*/
User user = userDao.getUserById(userId);
List<Department> departmentList = departmentDao.getDepartments();
model.addAttribute("departmentList", departmentList);
model.addAttribute("user", user);
/**
* 因为编辑与添加,布局标签是一样的,所以仍然跳转到添加页面
*/
/** 往前端 Thymeleaf 模板引擎时,开头不要加 "/" ,因为它默认配置就是:
* 前缀:spring.thymeleaf.prefix=classpath:/templates/
* 后缀:spring.thymeleaf.suffix=.html */
return "userAdd";
}
/**
* 用户修改-----用户修改提交时进入
* <p/>
* SpringMVC 自动将请求参数和入参对象的属性进行一一映射绑定
* 要求是请求参数的名字和 User 的属性名一样
*
* @param user
* @return
*/
@PutMapping(value = "userCRUD")
public String updateUser(User user) {
/**
* 修改数据
*/
userDao.updateUser(user);
/** redirect: 表示重定向到一个后台地址 " /" 代表当前项目路径
* forward: 表示转发到一个后台地址
* 两者都是get请求方式
* 修改之后仍然跳转到查询所有用户页面
*/
return "redirect:/user/users";
}
/**
* 用户删除
* <p/>
*
* @param user
* @return
*/
@DeleteMapping(value = "userCRUD/{userId}")
public String deleteUser(@PathVariable("userId") Integer userId) {
userDao.delUserById(userId);
/** redirect: 表示重定向到一个后台地址 " /" 代表当前项目路径
* forward: 表示转发到一个后台地址
* 两者都是get请求方式
* 修改之后仍然跳转到查询所有用户页面
*/
return "redirect:/user/users";
}
}
form 表单 delete 请求删除
userList. html
- 前台往后台发送 delete 请求删除员工数据,<a/> 标签发送的请求都是 get 请求,而 form 表单的 method 属性值只有 get 与 post 两种请求方式,所以 form 表单使用 put 或者 delete 请求方式,步骤如下:
- SpringMVC 中配置 HiddenHttpMethodFilter;(Spring Boot 已自动配置好,不用再管)
- 页面创建一个 post 请求方式的表单
- post 请求方式表单中创建一个 input 项,name 属性值强制为 "_method",value 属性值就是指定此 form 请求的方式,即 delete
<!-- 点击编辑按钮后,进入后台;路径中使用"+"号将两个运算符的结果连接起来-->
<a class="btn btn-sm btn-primary" th:href="@{/user/userCRUD/}+${user.uId}">编辑</a>
<!-- th:attr 这里自定义的标签属性赋值,为 button创建一个 del_uri 属性-->
<button th:attr="del_uri=@{/user/userCRUD/}+${user.uId}"
class="btn btn-sm btn-danger deleteBtn" type="button">删除
</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
</div>
</div>
<!--创建 delete 请求方式的表单-->
<form method="post" id="delUserForm">
<input type="hidden" name="_method" value="delete">
</form>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" th:src="@{/asserts/js/jquery-3.2.1.slim.min.js}"></script>
<script type="text/javascript" th:src="@{/asserts/js/popper.min.js}"></script>
<script type="text/javascript" th:src="@{/asserts/js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{/userList.js}"></script>
th:attr
- th:attr 同样用于设置标签的属性值,类似 th:href、th:src、th:action....等等,不过 th:attr 可以为一个或者多个属性同时赋值,可以参考官方文档
<form action="subscribe.html" th:attr="action=@{/subscribe}">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
<!--等价于-->
<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
</fieldset>
</form>
<!--同时为多个属性赋值-->
<img src="../../images/gtvglogo.png"
th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
userList. js
/**
* Created by Administrator on 2018/8/6 0006.
*/
$(function () {
/**
* 为 删除 用户 按钮绑定事件
* 动态为 from 表单的提交路径赋值,然后进行提交
*/
$(".deleteBtn").bind("click", function () {
let del_uri = $(this).attr("del_uri");
$("#delUserForm").attr("action", del_uri).submit();
});
});
运行测试
$. ajax 执行 delete 请求删除
- 实际开发中会经常使用 ajax 进行异步操作,如编辑、删除等,它的 $.ajax 的 type 支持 "GET(默认方式)"、"POST", 同时还支持 PUT 和 DELETE
- 所以用 ajax 是最合适不过的了
UserController
/**
* 用户删除------form 表单请求
* <p/>
*
* @param user
* @return
*/
//@DeleteMapping(value = "userCRUD/{userId}")
public String deleteUser(@PathVariable("userId") Integer userId) {
System.out.println("_-----:" + userId);
userDao.delUserById(userId);
/** redirect: 表示重定向到一个后台地址 " /" 代表当前项目路径
* forward: 表示转发到一个后台地址
* 两者都是get请求方式
* 修改之后仍然跳转到查询所有用户页面
**/
return "redirect:/user/users";
}
/**
* 用户删除-------ajax 请求
* <p/>
*
* @param user
* @return
*/
@DeleteMapping(value = "userCRUD/{userId}")
public void deleteUser(@PathVariable("userId") Integer userId, HttpServletResponse response) {
try {
PrintWriter pipedWriter = response.getWriter();
userDao.delUserById(userId);
pipedWriter.write("");
pipedWriter.flush();
pipedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
userList. html
......
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<!-- 缓存应用上下文路径,用于js中获取,从而设置路径,效果就是:/tiger/-->
<base th:href="@{/}">
<title>Dashboard Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/asserts/css/dashboard.css}" rel="stylesheet">
<style type="text/css">
........
<td>
<!-- 点击编辑按钮后,进入后台;路径中使用"+"号将两个运算符的结果连接起来-->
<a class="btn btn-sm btn-primary" th:href="@{/user/userCRUD/}+${user.uId}">编辑</a>
<!-- 将用户id 放置在button的 name 属性中,js中可以再获取它-->
<button th:name="${user.uId}"
class="btn btn-sm btn-danger deleteBtn" type="button">删除
</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" th:src="@{/asserts/js/jquery-3.2.1.slim.min.js}"></script>
<script type="text/javascript" th:src="@{/asserts/js/popper.min.js}"></script>
<script type="text/javascript" th:src="@{/asserts/js/bootstrap.min.js}"></script>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" th:src="@{/userList.js}"></script>
......
userList. js
/**
* Created by Administrator on 2018/8/6 0006.
*/
$(function () {
/**
* 为 删除 用户 按钮绑定事件
* 动态为 from 表单的提交路径赋值,然后进行提交
*/
$(".deleteBtn").bind("click", function () {
/**待删除的用户的id值*/
let userId = $(this).attr("name");
/**拼接请求的路径*/
let url = $("base").attr("href") + "user/userCRUD/" + userId;
$(this).fadeOut(600).fadeIn(600);
$.ajax({
url: url,
type: "DELETE",
success: function () {
location.reload();
},
error: function (data) {
console.log("Error:" + data)
}
});
});
});
运行测试