【SpringBoot】SpringBoot Web开发(八)
本周介绍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开发(八)的更多相关文章
- SpringBoot学习(七)-->SpringBoot在web开发中的配置
SpringBoot在web开发中的配置 Web开发的自动配置类:在Maven Dependencies-->spring-boot-1.5.2.RELEASE.jar-->org.spr ...
- SpringBoot:Web开发
西部开源-秦疆老师:基于SpringBoot 2.1.6 的博客教程 , 基于atguigu 1.5.x 视频优化 秦老师交流Q群号: 664386224 未授权禁止转载!编辑不易 , 转发请注明出处 ...
- SpringBoot之WEB开发-专题二
SpringBoot之WEB开发-专题二 三.Web开发 3.1.静态资源访问 在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资 ...
- springboot java web开发工程师效率
基础好工具 idea iterm2 和 oh-my-zsh git 热加载 java web项目每次重启时间成本太大. 编程有一个过程很重要, 就是试验, 在一次次试验中探索, 积累素材优化调整程序模 ...
- SpringBoot与Web开发
web开发1).创建SpringBoot应用,选中我们需要的模块:2).SpringBoot已经默认将这些场景已经配置好了,只需要在配置文件中指定少量配置就可以运行起来3).自己编写业务代码: 自动配 ...
- SpringBoot日记——Web开发篇
准备开始实战啦!~~~~ 我们先来看,SpringBoot的web是如何做web开发的呢?通常的步骤如下: 1.创建springboot应用,指定模块: 2.配置部分参数配置: 3.编写业务代码: 为 ...
- 十二、springboot之web开发之静态资源处理
springboot静态资源处理 Spring Boot 默认为我们提供了静态资源处理,使用 WebMvcAutoConfiguration 中的配置各种属性. 建议大家使用Spring Boot的默 ...
- SpringBoot(四) Web开发 --- Thymeleaf、JSP
Spring Boot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依 ...
- 【SpringBoot】Web开发
一.简介 1.1 引入SpringBoot模块 1.2 SpringBoot对静态资源的映射规则 二.模版引擎 2.1 简介 2.2 引入thymeleaf 2.3 Thymeleaf使用 一.简介 ...
- SpringBoot的Web开发
一.创建Web项目 创建的时候勾选对应web选项即可,会自动引入相应的starter,pom如下: <dependency> <groupId>org.springframew ...
随机推荐
- windows驱动不要签名
BCDEDIT -SET LOADOPTIONS DISABLE_INTEGRITY_CHECKSBCDEDIT -SET TESTSIGNING ON
- 【学CG系列】web之审查元素
一.审查元素的作用 审查元素(你的F12)可以做到定位网页元素.实时监控网页元素属性变化的功能,可以及时调试.修改.定位.追踪检查.查看嵌套 ,修改样式和查看js动态输出信息,是开发人员得心应手的好工 ...
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 字体图标(Glyphicons):glyphicon glyphicon-play-circle
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- G - Traffic
vin is observing the cars at a crossroads. He finds that there are n cars running in the east-west d ...
- 数据结构——KMP(串)
KMP一个非常经典的字符串模式匹配算法,虽然网上有很多kmp算法的博客,但是为了更好的理解kmp我还是自己写了一遍(这个kmp的字符串存储是基于堆的(heap),和老师说的定长存储略有不同,字符串索引 ...
- l5213. 玩筹码
这道题本应该很简单的但是我把他复杂化了,所以没有在第一时间里A出来.我们来看看题目 看上去是不是很复杂,思路是有,但是,很难实现.我最开始的时候是认为有三种情况,左边筹码最多,右边筹码最多,中间筹码最 ...
- tornado+peewee-async+peewee+mysql(一)
前言: 需要异步操作MySQL,又要用orm,使用sqlalchemy需要加celery,觉得比较麻烦,选择了peewee-async 开发环境 python3.6.8+peewee-async0.5 ...
- 054-for循环
<?php for($i=1;$i<=5;$i++){ echo "$i<br />"; //循环体 } ?>
- 第二阶段scrum-7
1.整个团队的任务量: 2.任务看板: 会议照片: 产品状态: 部署云服务器完成,链接数据库完成,消息收发正在制作.
- 经验分享:如何搞定Personal Statement?
最近又到申请季啦,如何自己DIY申请,如何准备文书成为众多留学生关心的问题.不管是你申请本科,硕士,还是博士,相信这篇文章都能帮助到你.下面来说一下文书中一个很重要的组成,就是个人陈述Personal ...