1.pox.xml文件加入依赖+导入静态资源
kaungshenSpringboot静态资源
链接:https://pan.baidu.com/s/18ORYE0SzHmwKL4QsM2kcfw?pwd=f5ii
提取码:f5ii静态资源包存放。
<dependencies>
<!-- 导入thymeleaf依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.15.RELEASE</version>
</dependency>
<!-- @validation配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- 导入配置文件处理器,配置文件进行绑定就会有提示,需要重启 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.application.properties配置
server.port=8081
#关闭模板引擎缓存
spring.thymeleaf.cache=false
#项目的虚拟目录
server.servlet.context-path=/lyj
#我们的配置文件的真实位置
spring.messages.basename=i18n.login
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy/MM/dd HH:mm:ss
3.配置实体类pojo Employee+Department
package com.lyj.springboot02.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
//@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
import java.util.Date;
@Data
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;//0:女 ,1:男
private Department department;
//重点 new Date()底层是yyyy/MM/dd
@DateTimeFormat(pattern = "yyyy-MM-dd")
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();
}
}
package com.lyj.springboot02.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private int id;
private String Name;
}
4.自定义表数据
EmployeeDao+ DepartmentDao
package com.lyj.springboot02.dao;
import com.lyj.springboot02.pojo.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@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);
}
}
----------------------------------------------------------------------
package com.lyj.springboot02.dao;
import com.lyj.springboot02.pojo.Department;
import com.lyj.springboot02.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;
@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","26321312@qq.com",0,new Department(101,"教学部")) );
employees.put(1002,new Employee(1002,"BB","36321312@qq.com",1,new Department(102,"开发部")) );
employees.put(1003,new Employee(1003,"CC","46321312@qq.com",0,new Department(103,"生产部")) );
employees.put(1004,new Employee(1004,"DD","56321312@qq.com",1,new Department(104,"研发部")) );
employees.put(1005,new Employee(1005,"EE","66321312@qq.com",0,new Department(105,"运营部")) );
}
//主键自增
public static Integer initId=1006;
//添加一个员工
public void save(Employee employee){
System.out.println(employee);
if (employee.getId()==null && employee.getId()<0){
employee.setId(initId++);
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
//查询全部员工信息;
public Collection<Employee> getEmployees(){
return employees.values();
}
//通过id查询员工
public Employee getEmployeeById(int id){
return employees.get(id);
}
//通过id删除员工
public void delete(Integer id){
employees.remove(id);
}
}
5.首页配置 index.html
注意点,所有的静态页面资源都需要使用thymeleaf接管;
url:@{}
<!--在i每个html头部引入thymeleaf-->
<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 -->
<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">
<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的值为null就不显示消息-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input name="username" type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input name="password" type="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">[[#{login.btn}]]</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>
6.页面国际化:
我们需要配置i18n文件, internationalization : i18n 国际化简称
我们如果需要在项目中进行按钮自动切换,我们需要自定义一个组件LocaleReslover
记得将自己写的组件配置到spring容器@Bean
#{}
<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>
在resources下创建一个Resouce Bundle 'login' 分别包含:
login.properties,login_en_US.propertiesz 英文美国,login_zh_CN.properties 中文中国
设置对应的 login.properties,login_zh_CN.properties
login.btn=登录 login.password=密码 login.remember=记住我 login.tip=请登录 login.username=用户名
login.btn=Sign in login.password=Password login.remember=Remember me login.tip=Please Sign in login.username=Username
7:登录+拦截器
1.controller包下创建LoginController
LoginHandleInterceptor 自定义登录处理拦截
package com.lyj.springboot02.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username")String username,
@RequestParam("password")String pwd,
Model model,
HttpSession session){
//具体的业务
if(!StringUtils.isEmpty(username)&&"123456".equals(pwd)){
session.setAttribute("loginUser", username);
return "redirect:main.html";
}else {
model.addAttribute("msg", "用户名或着密码错误");
return "index";
}
}
@RequestMapping("/user/logout")
public String logout(HttpSession session){
session.invalidate();//session销毁
return "redirect:index.html";
}
}
2.在config包下配置自定义 WebMvcConfigurer
MyLocaleResolver自定义局部求解器
package com.lyj.springboot02.config;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
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");
//System.out.println("MyLocaleResolver->"+language);
Locale locale = Locale.getDefault();
//如果请求的链接携带了参数
if(!StringUtils.isEmpty(language)){
//zn-CH 中文 中国
String[]split=language.split("_");
//国家 地区
locale=new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
//Locale.getDefault() 的底层代码
public static Locale getDefault() {
// do not synchronize this method - see 4071298
return defaultLocale;
}
private volatile static Locale defaultLocale = initDefault();
private static Locale initDefault() {
String language, region, script, country, variant;
language = AccessController.doPrivileged(
new GetPropertyAction("user.language", "en"));
// for compatibility, check for old user.region property
region = AccessController.doPrivileged(
new GetPropertyAction("user.region"));
if (region != null) {
// region can be of form country, country_variant, or _variant
int i = region.indexOf('_');
if (i >= 0) {
country = region.substring(0, i);
variant = region.substring(i + 1);
} else {
country = region;
variant = "";
}
script = "";
} else {
script = AccessController.doPrivileged(
new GetPropertyAction("user.script", ""));
country = AccessController.doPrivileged(
new GetPropertyAction("user.country", ""));
variant = AccessController.doPrivileged(
new GetPropertyAction("user.variant", ""));
}
return getInstance(language, script, country, variant, null);
}
3.MyMvcConfig,自定义总配置,并将MyLocaleResolver ,LoginHandleInterceptor 加入到总配置。
package com.lyj.springboot02.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;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//所有走/,/index.html,返回index.html页面,/*/main.html返回dashboard.html页面
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/*/main.html").setViewName("dashboard");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor
(new LoginHandleInterceptor())
.addPathPatterns("/**")//全部的路径都拦截
.excludePathPatterns("/index.html","/",//首页不拦截
"/user/login", //用户登录不拦截
"/css/*","/js/**","/img/**");//静态资源不拦截
}
//自定义的国际化文件就生效了
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
8.员工列表展示
-
提取公共页面,像vue一样,把公共的代码提取出来复用,实现代码的复用性。
-
th:fragment="sidebar" th:fragment="topbar"
-
th:replace="~{commons/commons::topbar}" commons包/commons.html ::topbar
-
如果要传递参数,可以直接使用()传参,接受判断即可
-
列表循环展示
-
templates下建一个commons包commons.html中放一些公共的代码,像头部栏,侧边栏等。
9.添加员工
-
按钮提交
-
跳转到添加页面
-
添加员工成功
-
返回首页
-
.CRUD
-
404页面
-
-
controller包下新建LoginController,EmployeeController。
注意:一定要使用@Autowired 否则会出现 NullPointerException异常
@Autowired
private EmployeeDao employees;
package com.lyj.springboot02.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username")String username,
@RequestParam("password")String pwd,
Model model,
HttpSession session){
//具体的业务
if(!StringUtils.isEmpty(username)&&"123456".equals(pwd)){
session.setAttribute("loginUser", username);
return "redirect:main.html";
}else {
model.addAttribute("msg", "用户名或着密码错误");
return "index";
}
}
@RequestMapping("/user/logout")
public String logout(HttpSession session){
session.invalidate();//session销毁
return "redirect:index.html";
}
}
-----------------------------------------------------
package com.lyj.springboot02.controller;
import com.lyj.springboot02.dao.DepartmentDao;
import com.lyj.springboot02.dao.EmployeeDao;
import com.lyj.springboot02.pojo.Department;
import com.lyj.springboot02.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
@Controller
public class EmployeeController {
@Autowired
private EmployeeDao employees;
@Autowired
private DepartmentDao department;
@RequestMapping("/empList")
public String list(Model model){
Collection<Employee> employeeList = employees.getEmployees();
model.addAttribute("emps", employeeList);
return "emp/list";
}
@GetMapping("/emp")
public String toAddPage(Model model){
//查出所有部门的信息
Collection<Department> departments = department.getDepartments();
model.addAttribute("departments", departments);
return "emp/add";
}
@PostMapping("/emp")
public String addEmp(Employee employee){
System.out.println("save->"+employee);
employees.save(employee);//调用底层的方法保存员工信息
return "redirect:/empList";
}
@GetMapping("/emp{id}")
public String toUpdatePage(@PathVariable("id") Integer id, Model model){
//查出所有部门的信息
Employee employee = employees.getEmployeeById(id);
Collection<Department> departments = department.getDepartments();
model.addAttribute("departments", departments);
model.addAttribute("emp", employee);
return "emp/update";
}
@PostMapping("/emp/update")
public String UpdateEmp(Employee employee){
System.out.println("save->"+employee.getId());
employees.save(employee);//调用底层的方法保存员工信息
return "redirect:/empList";
}
@GetMapping("/delEmp{id}")
public String deleteEmp(@PathVariable("id") Integer id){
employees.delete(id);
return "redirect:/empList";
}
}
10.最后这个项目资源路径
链接:https://pan.baidu.com/s/1ze5WuzyjEU5GffaZYhEuAg?pwd=jrgk
提取码:jrgk