本周介绍SpringBoot项目Web开发的项目内容,及常用的CRUD操作,阅读本章前请阅读【SpringBoot】SpringBoot与Thymeleaf模版(六)的相关内容

Web开发

  项目搭建

  1、新建一个SpringBoot的web项目。pom.xml文件如下:

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId>
<artifactId>test-springboot-web2</artifactId>
<version>1.0-SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> <!-- SpringBoot打包插件,可以将代码打包成一个可执行的jar包 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

  2、配置文件application.properties如下:

 # 项目端口
server.port=8081
# 项目访问路径
server.servlet.context-path=/test # 禁用thymeleaf缓存
spring.thymeleaf.cache=false # mvc参数日期格式
spring.mvc.date-format=yyyy-MM-dd

  3、在浏览器中使用地址http://localhost:8081/test/即可访问项目

  4、项目目录结构

    

  登录功能

  1、编写登录LoginController.java;逻辑验证用户名和密码,登录成功后在session中存入熟悉loginUser

 package com.test.springboot.controller;

 import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest;
import java.util.Map; @Controller
public class LoginController { @PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String, Object> map, HttpServletRequest request){
System.out.println("======");
if(!StringUtils.isEmpty(username) && "123456".equals(password)) {
// 登陆成功
// 防止表单重复提交,可以重定向到主页
request.getSession().setAttribute("loginUser", username);
return "redirect:/main.html";
}else {
// 登陆失败
map.put("msg", "用户名或密码错误");
return "login";
} } }

  2、新建拦截器LoginHandlerInterceptor.java;逻辑:在session中判断是否存在属性loginUser,存在即已登录,不存在未登录

 package com.test.springboot.component;

 import org.springframework.web.servlet.HandlerInterceptor;

 import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class LoginHandlerInterceptor implements HandlerInterceptor { @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
Object user = request.getSession().getAttribute("loginUser");
if(user == null) {
// 未登录
request.setAttribute("msg", "没有权限请先登录");
request.getRequestDispatcher("/index.html").forward(request, response);
}else{
// 已登录
return true;
}
return false;
}
}

  3、在SpringMvc中添加拦截器

 package com.test.springboot.config;

 import com.test.springboot.component.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; // @EnableWebMvc // 全面接管SpringMVC,所有的WebMvc自动配置都失效,如静态资源的访问都失效
@Configuration
public class MyMvcConfig implements WebMvcConfigurer { // 添加视图映射
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// // 浏览器访问 "/success2" 重定向到 "/success"
// registry.addRedirectViewController("/success2", "/success");
// // 浏览器访问 "/success2" 转发 "/success"
// registry.addViewController("/success3").setViewName("/success"); // 首页
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("main"); } // 添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) { // springboot静态映射已做好,无需在拦截器中处理静态资源
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/", "/index.html", "/user/login");
}
}

  4、编辑登录界面login.html

 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body style="text-align: center;">
<h3>登录</h3>
<form th:action="@{/user/login}" method="post">
<p>用户名:<input type="text" name="username" /></p>
<p>密 码: <input type="password" name="password" /></p>
<input type="submit" value="提交" />
</form>
提示1:[[${msg}]]
</body>
</html>

  5、编辑主页面main.html

 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>main</title>
</head>
<body style="text-align: center;">
<h3>主页</h3>
<br>
[[${session.loginUser}]]
<h4><a th:href="@{/emps}">员工列表</a></h4>
提示-:[[${msg}]]
</body>
</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

 package com.test.springboot.dao;

 import java.util.Collection;
import java.util.HashMap;
import java.util.Map; import com.test.springboot.entities.Department;
import com.test.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; @Repository
public class EmployeeDao { private static Map<Integer, Employee> employees = null; @Autowired
private DepartmentDao departmentDao; static{
employees = new HashMap<Integer, Employee>(); employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
} private static Integer initId = 1006; public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
} employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
} //查询所有员工
public Collection<Employee> getAll(){
return employees.values();
} public Employee get(Integer id){
return employees.get(id);
} public void delete(Integer id){
employees.remove(id);
}
}

  3、部门DAO

 package com.test.springboot.dao;

 import java.util.Collection;
import java.util.HashMap;
import java.util.Map; import com.test.springboot.entities.Department;
import org.springframework.stereotype.Repository; @Repository
public class DepartmentDao { private static Map<Integer, Department> departments = null; static{
departments = new HashMap<Integer, Department>(); departments.put(101, new Department(101, "D-AA"));
departments.put(102, new Department(102, "D-BB"));
departments.put(103, new Department(103, "D-CC"));
departments.put(104, new Department(104, "D-DD"));
departments.put(105, new Department(105, "D-EE"));
} public Collection<Department> getDepartments(){
return departments.values();
} public Department getDepartment(Integer id){
return departments.get(id);
} }

  4、员工对象

 package com.test.springboot.entities;

 import java.util.Date;

 public class Employee {

     private Integer id;
private String lastName; private String email;
//1 male, 0 female
private Integer gender;
private Department department;
private Date birth; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Integer getGender() {
return gender;
} public void setGender(Integer gender) {
this.gender = gender;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} public Date getBirth() {
return birth;
} public void setBirth(Date birth) {
this.birth = birth;
}
public Employee(Integer id, String lastName, String email, Integer gender,
Department department) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
this.birth = new Date();
} public Employee() {
} @Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
", department=" + department +
", birth=" + birth +
'}';
} }

  5、部门对象

 package com.test.springboot.entities;

 public class Department {

     private Integer id;
private String departmentName; public Department() {
} public Department(int i, String string) {
this.id = i;
this.departmentName = string;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getDepartmentName() {
return departmentName;
} public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
} @Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
} }

  6、员工列表界面 list.html

 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>add</title>
</head>
<body style="text-align: center;">
<h3>员工列表</h3>
<a th:href="@{/emp}">添加员工</a>
<table>
<thead>
<tr>
<tr>
<th>#</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>department</th>
<th>birth</th>
<th>操作</th>
</tr>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td>[[${emp.lastName}]]</td>
<td th:text="${emp.email}"></td>
<td th:text="${emp.gender} == 0 ? '女' : '男'"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td>
<td>
<a th:href="@{/emp/} + ${emp.id}">编辑</a> <form id="deleteEmpForm" method="post" th:action="@{/emp/}+${emp.id}">
<input type="hidden" name="_method" value="delete"/>
<button th:attr="del_uri=@{/emp/}+${emp.id}" type="submit">删除</button>
</form>
</td>
</tr>
</tbody>
</table>
</body>
</html>

  7、员工新增界面 add.html

 <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>list</title>
</head>
<body style="text-align: center;">
<h3>添加员工</h3> <!-- 发送put请求修改员工数据 -->
<!--
1、SpringMVC中配置HiddenHttpMethodFilter(SpringBoot自动配置)
2、页面创建一个post表单
3、创建一个input项,name="_method"; 值就是我们指定的请求方式
-->
<form th:action="@{/emp}" method="post">
<input type="hidden" name="_method" value="put" th:if="${emp!=null}"/>
<input type="hidden" name="id" th:value="${emp.id}" th:if="${emp!=null}" />
<p>lastName:<input type="text" name="lastName" th:value="${emp != null}?${emp.lastName}"/></p>
<p>email: <input type="text" name="email" th:value="${emp != null}?${emp.email}" /></p>
<p>gender:
<input type="radio" name="gender" value="1" th:checked="${emp != null}?${emp.gender==1}">男
<input type="radio" name="gender" value="0" th:checked="${emp != null}?${emp.gender==0 }">女
</p>
<p>department:
<select name="department.id" >
<option th:each="dept:${depts}" th:value="${dept.id}" th:selected="${emp != null}?${dept.id == emp.department.id}" th:text="${dept.departmentName}"></option>
</select>
<p>birth: <input type="text" name="birth" th:value="${emp != null}?${#dates.format(emp.birth, 'yyyy-MM-dd')}"/></p>
<input type="submit" th:value="${emp != null? '修改' : '添加'}" />
</form>
</body>
</html>

  6、测试如下:

    

【SpringBoot】SpringBoot Web开发(八)的更多相关文章

  1. SpringBoot学习(七)-->SpringBoot在web开发中的配置

    SpringBoot在web开发中的配置 Web开发的自动配置类:在Maven Dependencies-->spring-boot-1.5.2.RELEASE.jar-->org.spr ...

  2. SpringBoot:Web开发

    西部开源-秦疆老师:基于SpringBoot 2.1.6 的博客教程 , 基于atguigu 1.5.x 视频优化 秦老师交流Q群号: 664386224 未授权禁止转载!编辑不易 , 转发请注明出处 ...

  3. SpringBoot之WEB开发-专题二

    SpringBoot之WEB开发-专题二 三.Web开发 3.1.静态资源访问 在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资 ...

  4. springboot java web开发工程师效率

    基础好工具 idea iterm2 和 oh-my-zsh git 热加载 java web项目每次重启时间成本太大. 编程有一个过程很重要, 就是试验, 在一次次试验中探索, 积累素材优化调整程序模 ...

  5. SpringBoot与Web开发

    web开发1).创建SpringBoot应用,选中我们需要的模块:2).SpringBoot已经默认将这些场景已经配置好了,只需要在配置文件中指定少量配置就可以运行起来3).自己编写业务代码: 自动配 ...

  6. SpringBoot日记——Web开发篇

    准备开始实战啦!~~~~ 我们先来看,SpringBoot的web是如何做web开发的呢?通常的步骤如下: 1.创建springboot应用,指定模块: 2.配置部分参数配置: 3.编写业务代码: 为 ...

  7. 十二、springboot之web开发之静态资源处理

    springboot静态资源处理 Spring Boot 默认为我们提供了静态资源处理,使用 WebMvcAutoConfiguration 中的配置各种属性. 建议大家使用Spring Boot的默 ...

  8. SpringBoot(四) Web开发 --- Thymeleaf、JSP

    Spring Boot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依 ...

  9. 【SpringBoot】Web开发

    一.简介 1.1 引入SpringBoot模块 1.2 SpringBoot对静态资源的映射规则 二.模版引擎 2.1 简介 2.2 引入thymeleaf 2.3 Thymeleaf使用 一.简介 ...

  10. SpringBoot的Web开发

    一.创建Web项目 创建的时候勾选对应web选项即可,会自动引入相应的starter,pom如下: <dependency> <groupId>org.springframew ...

随机推荐

  1. 深入了解memcached

    一.memcached如何支持高并发 Memcached使用多路复用 I/O模型(如epoll.select等).传统阻塞 I/O中,系统可能会因为某个用户连接还没做好 I/O准备而一直等待,直到这个 ...

  2. 051、Java中使用while循环实现1~100的累加

    01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...

  3. docker centos 镜像中安装python36详解!生成centos+python36的基础镜像

    获取centos镜像docker pull centos:7.4.1708 启动并进入centos的容器docker run -i –t centos /bin/bash下载安装python编译环境依 ...

  4. SpringBoot-属性配置yaml自定义属性和值

    SpringBoot-属性配置yaml自定义属性和值 SpringBoot-属性配置yaml自定义属性和值 在SpringBoot中yml/yaml文件可以自定义一些属性,以供注入给自定义bean对象 ...

  5. 吴裕雄 Bootstrap 前端框架开发——Bootstrap 字体图标(Glyphicons):glyphicon glyphicon-repeat

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...

  6. Window Server 2019 配置篇(5)- 在域中建立WSUS以实现自动更新

    上次讲到我们的服务器群中增加了一台用于自动部署的服务器,这次我们要添加一台搭载WSUS服务的服务器,以实现对window更新的管理 那么WSUS是什么服务呢? WSUS是window server u ...

  7. java集合简单特性

  8. golang开启随机端口并获取端口

    listener, err := net.Listen("tcp", ":0") if err != nil { panic(err) } fmt.Printl ...

  9. layui-注册界面

    注册页面register.html源代码: <!DOCTYPE html> <html lang="en"> <head> <meta c ...

  10. Java8集合框架——HashSet源码分析

    本文的目录结构: 一.HashSet 的 Javadoc 文档注释和简要说明 二.HashSet 的内部实现:内部属性和构造函数 三.HashSet 的 add 操作和扩容 四.HashSet 的 r ...