本周介绍SpringBoot项目Web开发的项目内容,及常用的CRUD操作,阅读本章前请阅读【SpringBoot】SpringBoot与Thymeleaf模版(六)的相关内容
Web开发
项目搭建
1、新建一个SpringBoot的web项目。pom.xml文件如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.test</groupId> 8 <artifactId>test-springboot-web2</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <parent> 12 <groupId>org.springframework.boot</groupId> 13 <artifactId>spring-boot-starter-parent</artifactId> 14 <version>2.1.8.RELEASE</version> 15 </parent> 16 17 <properties> 18 19 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 20 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 21 <java.version>1.8</java.version> 22 </properties> 23 24 <dependencies> 25 26 <dependency> 27 <groupId>org.springframework.boot</groupId> 28 <artifactId>spring-boot-starter-web</artifactId> 29 </dependency> 30 31 <dependency> 32 <groupId>org.springframework.boot</groupId> 33 <artifactId>spring-boot-starter-thymeleaf</artifactId> 34 </dependency> 35 36 <dependency> 37 <groupId>org.springframework.boot</groupId> 38 <artifactId>spring-boot-starter-test</artifactId> 39 <scope>test</scope> 40 </dependency> 41 42 </dependencies> 43 44 45 <!-- SpringBoot打包插件,可以将代码打包成一个可执行的jar包 --> 46 <build> 47 <plugins> 48 <plugin> 49 <groupId>org.springframework.boot</groupId> 50 <artifactId>spring-boot-maven-plugin</artifactId> 51 </plugin> 52 </plugins> 53 </build> 54 55 </project>
2、配置文件application.properties如下:
1 # 项目端口 2 server.port=8081 3 # 项目访问路径 4 server.servlet.context-path=/test 5 6 # 禁用thymeleaf缓存 7 spring.thymeleaf.cache=false 8 9 # mvc参数日期格式 10 spring.mvc.date-format=yyyy-MM-dd
3、在浏览器中使用地址http://localhost:8081/test/即可访问项目
4、项目目录结构
登录功能
1、编写登录LoginController.java;逻辑验证用户名和密码,登录成功后在session中存入熟悉loginUser
1 package com.test.springboot.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.util.StringUtils; 5 import org.springframework.web.bind.annotation.PostMapping; 6 import org.springframework.web.bind.annotation.RequestParam; 7 8 import javax.servlet.http.HttpServletRequest; 9 import java.util.Map; 10 11 @Controller 12 public class LoginController { 13 14 @PostMapping(value = "/user/login") 15 public String login(@RequestParam("username") String username, 16 @RequestParam("password") String password, 17 Map<String, Object> map, HttpServletRequest request){ 18 System.out.println("======"); 19 if(!StringUtils.isEmpty(username) && "123456".equals(password)) { 20 // 登陆成功 21 // 防止表单重复提交,可以重定向到主页 22 request.getSession().setAttribute("loginUser", username); 23 return "redirect:/main.html"; 24 }else { 25 // 登陆失败 26 map.put("msg", "用户名或密码错误"); 27 return "login"; 28 } 29 30 } 31 32 }
2、新建拦截器LoginHandlerInterceptor.java;逻辑:在session中判断是否存在属性loginUser,存在即已登录,不存在未登录
1 package com.test.springboot.component; 2 3 4 import org.springframework.web.servlet.HandlerInterceptor; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.io.IOException; 10 11 public class LoginHandlerInterceptor implements HandlerInterceptor { 12 13 @Override 14 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException { 15 Object user = request.getSession().getAttribute("loginUser"); 16 if(user == null) { 17 // 未登录 18 request.setAttribute("msg", "没有权限请先登录"); 19 request.getRequestDispatcher("/index.html").forward(request, response); 20 }else{ 21 // 已登录 22 return true; 23 } 24 return false; 25 } 26 }
3、在SpringMvc中添加拦截器
1 package com.test.springboot.config; 2 3 import com.test.springboot.component.LoginHandlerInterceptor; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 6 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 8 9 10 // @EnableWebMvc // 全面接管SpringMVC,所有的WebMvc自动配置都失效,如静态资源的访问都失效 11 @Configuration 12 public class MyMvcConfig implements WebMvcConfigurer { 13 14 // 添加视图映射 15 @Override 16 public void addViewControllers(ViewControllerRegistry registry) { 17 // // 浏览器访问 "/success2" 重定向到 "/success" 18 // registry.addRedirectViewController("/success2", "/success"); 19 // // 浏览器访问 "/success2" 转发 "/success" 20 // registry.addViewController("/success3").setViewName("/success"); 21 22 // 首页 23 registry.addViewController("/").setViewName("login"); 24 registry.addViewController("/index.html").setViewName("login"); 25 26 registry.addViewController("/main.html").setViewName("main"); 27 28 } 29 30 // 添加拦截器 31 @Override 32 public void addInterceptors(InterceptorRegistry registry) { 33 34 // springboot静态映射已做好,无需在拦截器中处理静态资源 35 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**") 36 .excludePathPatterns("/", "/index.html", "/user/login"); 37 } 38 }
4、编辑登录界面login.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>login</title> 6 </head> 7 <body style="text-align: center;"> 8 <h3>登录</h3> 9 <form th:action="@{/user/login}" method="post"> 10 <p>用户名:<input type="text" name="username" /></p> 11 <p>密 码: <input type="password" name="password" /></p> 12 <input type="submit" value="提交" /> 13 </form> 14 提示1:[[${msg}]] 15 </body> 16 </html>
5、编辑主页面main.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>main</title> 6 </head> 7 <body style="text-align: center;"> 8 <h3>主页</h3> 9 <br> 10 [[${session.loginUser}]] 11 <h4><a th:href="@{/emps}">员工列表</a></h4> 12 提示-:[[${msg}]] 13 </body> 14 </html>
6、测试,在浏览器中打开地址:http://localhost:8081/test
CURD功能
1、新建员工Controller,内容如下:
package com.test.springboot.controller; import com.test.springboot.dao.DepartmentDao; import com.test.springboot.dao.EmployeeDao; import com.test.springboot.entities.Department; import com.test.springboot.entities.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Collection; @Controller public class EmployeeController { @Autowired private EmployeeDao employeeDao; @Autowired private DepartmentDao departmentDao; // 查询所有员工列表 @GetMapping("/emps") public String list(Model model){ Collection<Employee> employees = employeeDao.getAll(); // 放在请求域中 model.addAttribute("emps", employees); return "emp/list"; } // 添加员工页面 @GetMapping("/emp") public String toAddPage(Model model){ // 查询所有部门 Collection<Department> departments = departmentDao.getDepartments(); model.addAttribute("depts", departments); return "emp/add"; } @GetMapping("/emp/{id}") public String toEditPage(@PathVariable("id") Integer id , Model model){ Employee employee = employeeDao.get(id); model.addAttribute("emp", employee); Collection<Department> departments = departmentDao.getDepartments(); model.addAttribute("depts", departments); return "emp/add"; } // 员工添加 @PostMapping("/emp") public String addEmp(Employee employee){ System.out.println("员工信息:" + employee); // 返回员工列表界面 // redirect:表示重定向到某个界面 // forward:表示转发到某个界面 employeeDao.save(employee); return "redirect:/emps"; } //员工修改;需要提交员工id; @PutMapping("/emp") public String updateEmployee(Employee employee){ System.out.println("修改的员工数据:"+employee); employeeDao.save(employee); return "redirect:/emps"; } //员工删除 @DeleteMapping("/emp/{id}") public String deleteEmployee(@PathVariable("id") Integer id){ employeeDao.delete(id); return "redirect:/emps"; } }
2、员工DAO
1 package com.test.springboot.dao; 2 3 import java.util.Collection; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import com.test.springboot.entities.Department; 8 import com.test.springboot.entities.Employee; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.stereotype.Repository; 11 12 @Repository 13 public class EmployeeDao { 14 15 private static Map<Integer, Employee> employees = null; 16 17 @Autowired 18 private DepartmentDao departmentDao; 19 20 static{ 21 employees = new HashMap<Integer, Employee>(); 22 23 employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA"))); 24 employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB"))); 25 employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC"))); 26 employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD"))); 27 employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1, new Department(105, "D-EE"))); 28 } 29 30 private static Integer initId = 1006; 31 32 public void save(Employee employee){ 33 if(employee.getId() == null){ 34 employee.setId(initId++); 35 } 36 37 employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId())); 38 employees.put(employee.getId(), employee); 39 } 40 41 //查询所有员工 42 public Collection<Employee> getAll(){ 43 return employees.values(); 44 } 45 46 public Employee get(Integer id){ 47 return employees.get(id); 48 } 49 50 public void delete(Integer id){ 51 employees.remove(id); 52 } 53 }
3、部门DAO
1 package com.test.springboot.dao; 2 3 import java.util.Collection; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import com.test.springboot.entities.Department; 8 import org.springframework.stereotype.Repository; 9 10 11 @Repository 12 public class DepartmentDao { 13 14 private static Map<Integer, Department> departments = null; 15 16 static{ 17 departments = new HashMap<Integer, Department>(); 18 19 departments.put(101, new Department(101, "D-AA")); 20 departments.put(102, new Department(102, "D-BB")); 21 departments.put(103, new Department(103, "D-CC")); 22 departments.put(104, new Department(104, "D-DD")); 23 departments.put(105, new Department(105, "D-EE")); 24 } 25 26 public Collection<Department> getDepartments(){ 27 return departments.values(); 28 } 29 30 public Department getDepartment(Integer id){ 31 return departments.get(id); 32 } 33 34 }
4、员工对象
1 package com.test.springboot.entities; 2 3 import java.util.Date; 4 5 public class Employee { 6 7 private Integer id; 8 private String lastName; 9 10 private String email; 11 //1 male, 0 female 12 private Integer gender; 13 private Department department; 14 private Date birth; 15 16 public Integer getId() { 17 return id; 18 } 19 20 public void setId(Integer id) { 21 this.id = id; 22 } 23 24 public String getLastName() { 25 return lastName; 26 } 27 28 public void setLastName(String lastName) { 29 this.lastName = lastName; 30 } 31 32 public String getEmail() { 33 return email; 34 } 35 36 public void setEmail(String email) { 37 this.email = email; 38 } 39 40 public Integer getGender() { 41 return gender; 42 } 43 44 public void setGender(Integer gender) { 45 this.gender = gender; 46 } 47 48 public Department getDepartment() { 49 return department; 50 } 51 52 public void setDepartment(Department department) { 53 this.department = department; 54 } 55 56 public Date getBirth() { 57 return birth; 58 } 59 60 public void setBirth(Date birth) { 61 this.birth = birth; 62 } 63 public Employee(Integer id, String lastName, String email, Integer gender, 64 Department department) { 65 super(); 66 this.id = id; 67 this.lastName = lastName; 68 this.email = email; 69 this.gender = gender; 70 this.department = department; 71 this.birth = new Date(); 72 } 73 74 public Employee() { 75 } 76 77 @Override 78 public String toString() { 79 return "Employee{" + 80 "id=" + id + 81 ", lastName=‘" + lastName + ‘\‘‘ + 82 ", email=‘" + email + ‘\‘‘ + 83 ", gender=" + gender + 84 ", department=" + department + 85 ", birth=" + birth + 86 ‘}‘; 87 } 88 89 90 }
5、部门对象
1 package com.test.springboot.entities; 2 3 public class Department { 4 5 private Integer id; 6 private String departmentName; 7 8 public Department() { 9 } 10 11 public Department(int i, String string) { 12 this.id = i; 13 this.departmentName = string; 14 } 15 16 public Integer getId() { 17 return id; 18 } 19 20 public void setId(Integer id) { 21 this.id = id; 22 } 23 24 public String getDepartmentName() { 25 return departmentName; 26 } 27 28 public void setDepartmentName(String departmentName) { 29 this.departmentName = departmentName; 30 } 31 32 @Override 33 public String toString() { 34 return "Department [id=" + id + ", departmentName=" + departmentName + "]"; 35 } 36 37 }
6、员工列表界面 list.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>add</title> 6 </head> 7 <body style="text-align: center;"> 8 <h3>员工列表</h3> 9 <a th:href="@{/emp}">添加员工</a> 10 <table> 11 <thead> 12 <tr> 13 <tr> 14 <th>#</th> 15 <th>lastName</th> 16 <th>email</th> 17 <th>gender</th> 18 <th>department</th> 19 <th>birth</th> 20 <th>操作</th> 21 </tr> 22 </tr> 23 </thead> 24 <tbody> 25 <tr th:each="emp:${emps}"> 26 <td th:text="${emp.id}"></td> 27 <td>[[${emp.lastName}]]</td> 28 <td th:text="${emp.email}"></td> 29 <td th:text="${emp.gender} == 0 ? ‘女‘ : ‘男‘"></td> 30 <td th:text="${emp.department.departmentName}"></td> 31 <td th:text="${#dates.format(emp.birth, ‘yyyy-MM-dd HH:mm‘)}"></td> 32 <td> 33 <a th:href="@{/emp/} + ${emp.id}">编辑</a> 34 35 <form id="deleteEmpForm" method="post" th:action="@{/emp/}+${emp.id}"> 36 <input type="hidden" name="_method" value="delete"/> 37 <button th:attr="[email protected]{/emp/}+${emp.id}" type="submit">删除</button> 38 </form> 39 </td> 40 </tr> 41 </tbody> 42 </table> 43 </body> 44 </html>
7、员工新增界面 add.html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>list</title> 6 </head> 7 <body style="text-align: center;"> 8 <h3>添加员工</h3> 9 10 <!-- 发送put请求修改员工数据 --> 11 <!-- 12 1、SpringMVC中配置HiddenHttpMethodFilter(SpringBoot自动配置) 13 2、页面创建一个post表单 14 3、创建一个input项,name="_method"; 值就是我们指定的请求方式 15 --> 16 <form th:action="@{/emp}" method="post"> 17 <input type="hidden" name="_method" value="put" th:if="${emp!=null}"/> 18 <input type="hidden" name="id" th:value="${emp.id}" th:if="${emp!=null}" /> 19 <p>lastName:<input type="text" name="lastName" th:value="${emp != null}?${emp.lastName}"/></p> 20 <p>email: <input type="text" name="email" th:value="${emp != null}?${emp.email}" /></p> 21 <p>gender: 22 <input type="radio" name="gender" value="1" th:checked="${emp != null}?${emp.gender==1}">男 23 <input type="radio" name="gender" value="0" th:checked="${emp != null}?${emp.gender==0 }">女 24 </p> 25 <p>department: 26 <select name="department.id" > 27 <option th:each="dept:${depts}" th:value="${dept.id}" th:selected="${emp != null}?${dept.id == emp.department.id}" th:text="${dept.departmentName}"></option> 28 </select> 29 <p>birth: <input type="text" name="birth" th:value="${emp != null}?${#dates.format(emp.birth, ‘yyyy-MM-dd‘)}"/></p> 30 <input type="submit" th:value="${emp != null? ‘修改‘ : ‘添加‘}" /> 31 </form> 32 </body> 33 </html>
6、测试如下:
原文地址:https://www.cnblogs.com/h--d/p/12375417.html
时间: 2024-11-08 17:31:37