最近开始跟着学SpringBoot,记录一下SpringBoot实现简单网站的CRUD,以便日后回顾。
准备工作
新建spring项目,记得勾选springweb和thymeleaf!
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.fanjh</groupId>
<artifactId>spring-03-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-03-web</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
首先导入现有模板静态资源(可以网上找免费的):
一般静态资源放在根目录下的static文件夹下。
html文件放在template文件夹下,这里包括:登录页面index.html, 首页dashboard.html, 错误页面404.html, 员工管理页面list.html。
项目目录截图
编写java类
(使用lombok插件)
- Empoyee
package com.fanjh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.util.Date;
@Data
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private Department department;
private Date birth;
public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
//日期内部生成
this.birth = new Date();
}
}
- Department
package com.fanjh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
编写dao层(不连接数据库)
伪造数据库
- DepartmentDao
package com.fanjh.dao;
import com.fanjh.pojo.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
//@component的引申注解,实现bean的注入
@Repository
public class DepartmentDao {
//模拟数据库中的数据
private static Map<Integer, Department> departments = null;
static{
departments = new HashMap<>();
departments.put(101, new Department(101, "综合部"));
departments.put(102, new Department(102, "媒体部"));
departments.put(103, new Department(103, "主席团"));
departments.put(104, new Department(104, "留学部"));
departments.put(105, new Department(105, "文体部"));
}
//获取所有部门
public Collection<Department> getDepartments(){
return departments.values();
}
//根据id获取部门
public Department getDepartmentById(Integer id){
return departments.get(id);
}
}
- EmployeeDao
package com.fanjh.dao;
import com.fanjh.pojo.Department;
import com.fanjh.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
//@component的引申注解,实现bean的注入
@Repository
public class EmployeeDao {
//模拟数据库中的数据
private static Map<Integer, Employee> employees = null;
//员工有所属部门
@Autowired
private DepartmentDao departmentDao;
static{
employees = new HashMap<>();
employees.put(1001, new Employee(1001, "AA", "A134324@qq.com", 1, new Department(101, "综合部")));
employees.put(1002, new Employee(1002, "BB", "B134324@qq.com", 0, new Department(102, "媒体部")));
employees.put(1003, new Employee(1003, "CC", "C134324@qq.com", 1, new Department(103, "主席团")));
employees.put(1004, new Employee(1004, "DD", "D134324@qq.com", 0, new Department(104, "留学部")));
employees.put(1005, new Employee(1005, "EE", "E134324@qq.com", 1, new Department(105, "文体部")));
}
//主键自增
private static Integer initid = 1006;
//增加成员
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initid++);
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
//查询全部成员信息
public Collection<Employee> getAll(){
return employees.values();
}
//通过id查询成员
public Employee getEmployeeById(Integer id){
return employees.get(id);
}
//通过id删除成员
public void delete(Integer id){
employees.remove(id);
}
}
首页实现
- index.html
注意引入命名空间;
所有的页面静态资源都要用thymeleaf接管;
<!DOCTYPE html>
<!--所有的页面的静态资源都需要使用thymeleaf接管,所有的本地url格式都是@{}-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<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="">
<title>Signin Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<!--"/"表示在根目录下,即classpath:,static不用写-->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<!-- 点击提交按钮时,走/user/login请求 -->
<form class="form-signin" th:action="@{/user/login}">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<!--msg不为空,即密码错了,才显示提示-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<input type="text" name="username" class="form-control" th:placeholder="#{login.uername}" required="" autofocus="">
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> [[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
</form>
</body>
</html>
效果
国际化
首先确保设置中的File Encodings都是UTF-8,不然会有乱码。
- login.properties
login.btn=登录
login.password=密码
login.remember=记住我
login.tip=请登录
login.uername=用户名
- login_en_US.properties
login.btn=sign in
login.password=Password
login.remember=Remember me
login.tip=please sign in
login.uername=Username
登录页面点击中文/English时,会携带参数’l’传递给后台,此时我们自定义国际化组件解析参数。
配置完后怎么识别到这个国际化?
源码MessageSourceAutoConfiguration
去配置!
#关闭模板引擎缓存
spring.themeleaf.cache=false
#首页地址
#静态资源配置一般转为thymeleaf
server.servlet.context-path=/fanjh
#配置文件的真实位置
spring.messages.basename=i18n.login
#设置日期格式(默认格式)
spring.mvc.format.date=yyyy/MM/dd
自定义国际化组件
- MyLocaleResolver
package com.fanjh.config;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String language = request.getParameter("l");
Locale locale = Locale.getDefault();//如果没有就使用默认的
//如果请求的连接携带了国际化的参数
if(!StringUtils.isEmpty(language)){
//zh_CN
String[] split = language.split("_");
//国家 地区
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
将国际化组件注入到容器中,使之生效。
- MyMvcConfig
如果你想diy一些定制化的功能,只要写这个组件,然后将他交给springboot,springboot就会帮我们自动装配。
如果我们要扩展springmvc,官方建议我们这样做。
package com.fanjh.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//一般在这里配置根目录的东西
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/main.html").setViewName("dashboard");
}
//自定义的国际化组件就生效了
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//对所有的请求的拦截,除了"/index.html", "/", "/user/login",
// "/css/*", "/js/**", "/img/**"
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/index.html", "/", "/user/login",
"/css/*", "/js/**", "/img/**");
}
}
第一部分添加视图,我们可以通过’/’或‘/index.html’访问index页面;
第二部分注入我们自定义的国际化组件;
第三部分添加拦截器,实现对未登录用户的拦截。
登录功能实现
- LoginController
package com.fanjh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
//登录
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model, HttpSession session){
if("abc".equals(username) && "1234".equals(password)){
session.setAttribute("loginUser", username);
return "redirect:/main.html";
}else{
model.addAttribute("msg", "用户名或密码错误");
return "index";
}
}
//注销
@RequestMapping("/user/logout")
public String logout(HttpSession session){
//注销session即可
session.invalidate();
return "redirect:/index/html";
}
}
登录拦截器
- LoginHandlerInterceptor
package com.fanjh.config;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.