SpringBoot学习笔记——简单实例-员工管理系统
前置知识:
- SpringBoot学习笔记——SpringBoot简介与HelloWord
- SpringBoot学习笔记——源码初步解析
- SpringBoot学习笔记——配置文件yaml学习
- SpringBoot学习笔记——JSR303数据校验与多环境切换
- SpringBoot学习笔记——自动配置原理
- SpringBoot学习笔记——Web开发探究
- SpringBoot学习笔记——Thymeleaf
spring-boot实例-员工管理系统
-
首先新建一个spring-boot项目。
可以将启动代码移动到如下!
整合MyBatis
官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
Maven仓库地址:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter/2.1.1
代码结构
-
新建立spring-boot项目
-
导入依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
-
maven配置资源过滤问题
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources>
-
application.yaml配置mybatis
spring: datasource: username: root password: 123456 #?serverTimezone=UTC解决时区的报错 url: jdbc:mysql://localhost:3307/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver mybatis: type-aliases-package: com.sdz.pojo mapper-locations: classpath:mybatis/mapper/*.xml configuration: map-underscore-to-camel-case: true
-
编写实体类
package com.sdz.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Department { private Integer id; private String departmentName; }
package com.sdz.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class Employee { private Integer id; private String lastName; private String email; private Integer gender; private Integer department; private Date birth; private Department eDepartment; // 冗余设计 }
-
编写mapper
DepartmentMapper.java
package com.sdz.mapper; import com.sdz.pojo.Department; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; //这个注解表示这是一个 mybatis 的 mapper 类 @Mapper // dao层 @Repository public interface DepartmentMapper { // 获取所有部门信息 List<Department> getDepartments(); // 通过id获得部门 Department getDepartment(Integer id); // 添加部门 void addDepartment(Department department); // 更新部门 void updateDepartment(Department department); // 删除部门 void deleteDepartment(int id); }
DepartmentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.sdz.mapper.DepartmentMapper"> <select id="getDepartments" resultType="Department"> select * from department; </select> <select id="getDepartment" resultType="Department" parameterType="int"> select * from department where id = #{id} </select> <insert id="addDepartment" parameterType="Department"> insert into department values (#{id}, #{departmentName}) </insert> <update id="updateDepartment" parameterType="Department"> update department set departmentName=#{departmentName} where id = #{id} </update> <delete id="deleteDepartment" parameterType="int"> delete from department where id = #{id} </delete> </mapper>
EmployeeMapper.java
package com.sdz.mapper; import com.sdz.pojo.Employee; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface EmployeeMapper { // 获取所有员工的信息 List<Employee> getEmployees(); // 新增一个员工 int addEmployee(Employee employee); // 通过id获取员工信息 Employee getEmployee(Integer id); // 通过id删除员工 int deleteEmployee(Integer id); }
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.sdz.mapper.EmployeeMapper"> <resultMap id="EmployeeMap" type="Employee"> <id property="id" column="eid"/> <result property="lastName" column="last_name"/> <result property="email" column="email"/> <result property="gender" column="gender"/> <result property="birth" column="birth"/> <association property="eDepartment" javaType="Department"> <id property="id" column="did"/> <result property="departmentName" column="dname"/> </association> </resultMap> <select id="getEmployees" resultMap="EmployeeMap"> select e.id as eid,last_name,email,gender,birth,d.id as did,d.department_name as dname from department d,employee e where d.id = e.department </select> <insert id="addEmployee" parameterType="Employee"> insert into employee (last_name,email,gender,department,birth) values (#{lastName},#{email},#{gender},#{department},#{birth}); </insert> <select id="getEmployee" resultType="Employee"> select * from employee where id = #{id} </select> <delete id="deleteEmployee" parameterType="int"> delete from employee where id = #{id} </delete> </mapper>
-
TestController.java
package com.sdz.controller; import com.sdz.mapper.DepartmentMapper; import com.sdz.mapper.EmployeeMapper; import com.sdz.pojo.Department; import com.sdz.pojo.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.sql.DataSource; import java.util.Date; import java.util.List; @RestController public class TestController { @RequestMapping("/test") public String test(){ return "test"; } @Autowired DepartmentMapper departmentMapper; // 查询全部部门 @GetMapping("/getDepartments") public List<Department> getDepartments(){ return departmentMapper.getDepartments(); } // 增加部门 @GetMapping("/addDepartment/{id}/{departmentName}") public String addDepartment(@PathVariable("id") Integer id, @PathVariable("departmentName") String departmentName){ departmentMapper.addDepartment(new Department(id, departmentName)); return "add ok"; } // 按照id查询部门 @GetMapping("/getDepartment/{id}") public Department getDepartment(@PathVariable("id") Integer id){ return departmentMapper.getDepartment(id); } // 更新部门 @GetMapping("/updateDepartment") public String updateDepartment(){ departmentMapper.updateDepartment(new Department(3,"财务")); return "update ok!"; } // 删除部门 @GetMapping("/deleteDepartment/{id}") public String deleteDepartment(@PathVariable("id") Integer id){ departmentMapper.deleteDepartment(id); return "delete ok"; } @Autowired EmployeeMapper employeeMapper; // 获取所有员工信息 @GetMapping("/getEmployees") public List<Employee> getEmployees(){ return employeeMapper.getEmployees(); } @GetMapping("/addEmployee") public int addEmployee(){ Employee employee = new Employee(); employee.setLastName("sdz"); employee.setEmail("sdz@qq.com"); employee.setGender(1); employee.setDepartment(1); employee.setBirth(new Date()); return employeeMapper.addEmployee(employee); } // 通过id获得员工信息 @GetMapping("/getEmployee/{id}") public Employee getEmployee(@PathVariable("id") Integer id){ return employeeMapper.getEmployee(id); } // 通过id删除员工 @GetMapping("/deleteEmployee/{id}") public int deleteEmployee(@PathVariable("id") Integer id){ return employeeMapper.deleteEmployee(id); } }
整合springMVC
静态资源
SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置里面,我们可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法;
比如:addResourceHandlers
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
private Integer getSeconds(Duration cachePeriod) {
return (cachePeriod != null) ? (int) cachePeriod.getSeconds() : null;
}
private void customizeResourceHandlerRegistration(ResourceHandlerRegistration registration) {
if (this.resourceHandlerRegistrationCustomizer != null) {
this.resourceHandlerRegistrationCustomizer.customize(registration);
}
}
总结:
-
在springboot,我们可以通过以下方式处理静态资源
- webjars localhost:8080/webjars
- public,static,/**,resources localhost:8080/
-
优先级: resources>static>public 我们一般将静态资源放在static中
-
将网页与静态资源导入
导入完毕这些之后,我们还需要导入我们的前端页面,及静态资源文件!
- css,js等放在static文件夹下
- html放在templates文件夹下
-
首页配置
package com.sdz.config; import org.springframework.context.annotation.Configuration; 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) { registry.addViewController("/").setViewName("index"); registry.addViewController(("/index.html")).setViewName("index"); } }
-
thymeleaf
注意点,所有页面的静态资源都需要使用thymeleaf接管; @{}引入
<html lang="en" xmlns:th="http://www.thymeleaf.org">
资源链接修改
index.html
<!-- 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"> <img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
其它页面一样
(不显示的话)关闭缓存
spring: thymeleaf: cache: false
-
配置http://localhost:8080/sdz/
server: servlet: context-path: /sdz
代码里面自动配置/sdz
页面国际化
准备工作
先在IDEA中统一设置properties的编码问题!
编写国际化配置文件,抽取页面需要显示的国际化页面消息。我们可以去登录页面查看一下,哪些内容我们需要编写国际化的配置!
配置文件编写
1、我们在resources资源文件下新建一个i18n目录,存放国际化配置文件
2、建立一个login.properties文件,还有一个login_zh_CN.properties;发现IDEA自动识别了我们要做国际化操作;文件夹变了!
3、我们可以在这上面去新建一个文件;
弹出如下页面:我们再添加一个英文的;
这样就快捷多了!
4、接下来,我们就来编写配置,我们可以看到idea下面有另外一个视图;
这个视图我们点击 + 号就可以直接添加属性了;我们新建一个login.tip,可以看到边上有三个文件框可以输入。
然后依次添加其他页面内容即可!
但IDEA看你保存不了,手写配置文件即可。
login.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
中文:
login.btn=登录
login.password=密码
login.remember=记住我
login.tip=请登录
login.username=用户名
配置文件步骤搞定!
配置文件生效探究
我们去看一下SpringBoot对国际化的自动配置!这里又涉及到一个类:MessageSourceAutoConfiguration
里面有一个方法,这里发现SpringBoot已经自动配置好了管理我们国际化资源文件的组件 ResourceBundleMessageSource;
// 获取 properties 传递过来的值进行判断
@Bean
public MessageSource messageSource(MessageSourceProperties properties) {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(properties.getBasename())) {
// 设置国际化文件的基础名(去掉语言国家代码的)
messageSource.setBasenames(
StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(properties.getBasename())));
}
if (properties.getEncoding() != null) {
messageSource.setDefaultEncoding(properties.getEncoding().name());
}
messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
Duration cacheDuration = properties.getCacheDuration();
if (cacheDuration != null) {
messageSource.setCacheMillis(cacheDuration.toMillis());
}
messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
return messageSource;
}
我们真实 的情况是放在了i18n目录下,所以我们要去配置这个messages的路径;
spring:
messages:
basename:
i18n.login
配置页面国际化值
去页面获取国际化的值,查看Thymeleaf的文档,找到message取值操作为:#{...}。我们去页面测试下:
IDEA还有提示,非常智能的!
我们可以去启动项目,访问一下,发现已经自动识别为中文的了!
但是我们想要更好!可以根据按钮自动切换中文英文!
配置国际化解析
在Spring中有一个国际化的Locale (区域信息对象);里面有一个叫做LocaleResolver (获取区域信息对象)的解析器!
我们去我们webmvc自动配置文件,寻找一下!看到SpringBoot默认配置:
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
// 容器中没有就自己配,有的话就用用户配置的
if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
// 接收头国际化分解
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
AcceptHeaderLocaleResolver 这个类中有一个方法
public Locale resolveLocale(HttpServletRequest request) {
Locale defaultLocale = this.getDefaultLocale();
// 默认的就是根据请求头带来的区域信息获取Locale进行国际化
if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
return defaultLocale;
} else {
Locale requestLocale = request.getLocale();
List<Locale> supportedLocales = this.getSupportedLocales();
if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
if (supportedLocale != null) {
return supportedLocale;
} else {
return defaultLocale != null ? defaultLocale : requestLocale;
}
} else {
return requestLocale;
}
}
}
那假如我们现在想点击链接让我们的国际化资源生效,就需要让我们自己的Locale生效!
我们去自己写一个自己的LocaleResolver,可以在链接上携带区域信息!
修改一下前端页面的跳转连接:
<!-- 这里传入参数不需要使用 ?使用 (key=value)-->
<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>
我们去写一个处理的组件类!
package com.sdz.component;
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");
Locale locale = Locale.getDefault(); // 如果没有获取到就使用系统默认的
//如果请求链接不为空
if (!StringUtils.isEmpty(language)){
//分割请求参数
String[] split = language.split("_");
//国家,地区
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
为了让我们的区域化信息能够生效,我们需要再配置一下这个组件!在我们自己的MvcConofig下添加bean;
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
我们重启项目,来访问一下,发现点击按钮可以实现成功切换!搞定收工!
页面国际化: .
我们需要配置i18n文件
我们如果需要在项目中进行按钮自动切换,我们需要自定义一个组件LocaleResolver
记得将自己写的组件配置到spring容器
@Bean
{}
登录功能实现
修改action
<form class="form-signin" th:action="@{/user/login}">
新建LoginController.java
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model, HttpSession httpSession) {
// 具体业务
if(!StringUtils.isEmpty(username) && "123456".equals(password)) {
httpSession.setAttribute("loginUser", username);
return "redirect:/main.html";
}
else{
model.addAttribute("msg","登录失败!");
return "index";
}
}
}
登录失败
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
页面修改
MyMvcConfig.java
registry.addViewController("/main.html").setViewName("dashboard");
登录拦截器
编写拦截器 LoginHandlerInterceptor.java
package com.sdz.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 登录成功之后,有用户的session;
Object loginUser = request.getSession().getAttribute("loginUser");
if(loginUser == null){
request.setAttribute("msg", "请先登录");
request.getRequestDispatcher("/index.html").forward(request, response);
return false;
}
return true;
}
}
LoginController里面配置
package com.sdz.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 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 httpSession) {
// 具体业务
if(!StringUtils.isEmpty(username) && "123456".equals(password)) {
httpSession.setAttribute("loginUser", username);
return "redirect:/main.html";
}
else{
model.addAttribute("msg","登录失败!");
return "index";
}
}
}
MyMvcConfig配置,配置需要过滤和不需要过滤得页面
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/login","/","/index.html",
"/css/**","/js/**","/img/**");
}
dashborad.html显示登录用户名
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
展示员工列表
- Thymeleaf 公共页面元素抽取
th: fragment="sidebar"
th:replace="~{commons/ commons:: sidebar}"
- 如果要传递参数,可以直接使用(active='main.html')传参,接收判断即可,实现选择高亮功能。
- 列表循环展示
Customers->员工管理
前端代码复用(提取公共页面)及选择高亮
commons/commons.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!--头部导航栏-->
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">注销</a>
</li>
</ul>
</nav>
<!--侧边栏-->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="siedbar">
<div class="sidebar-sticky">
<ul class="nav flex-column">
<li class="nav-item">
<a th:class="${active=='main.html' ? 'nav-link active' : 'nav-link'}" th:href="@{/index.html}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path>
<polyline points="9 22 9 12 15 12 15 22"></polyline>
</svg>
首页 <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
<polyline points="13 2 13 9 20 9"></polyline>
</svg>
Orders
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-shopping-cart">
<circle cx="9" cy="21" r="1"></circle>
<circle cx="20" cy="21" r="1"></circle>
<path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
</svg>
Products
</a>
</li>
<li class="nav-item">
<a th:class="${active=='emps' ? 'nav-link active' : 'nav-link'}" th:href="@{/emps}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工管理
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bar-chart-2">
<line x1="18" y1="20" x2="18" y2="10"></line>
<line x1="12" y1="20" x2="12" y2="4"></line>
<line x1="6" y1="20" x2="6" y2="14"></line>
</svg>
Reports
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-layers">
<polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
<polyline points="2 17 12 22 22 17"></polyline>
<polyline points="2 12 12 17 22 12"></polyline>
</svg>
Integrations
</a>
</li>
</ul>
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Saved reports</span>
<a class="d-flex align-items-center text-muted" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
</a>
</h6>
<ul class="nav flex-column mb-2">
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Current month
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Last quarter
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Social engagement
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-file-text">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
Year-end sale
</a>
</li>
</ul>
</div>
</nav>
</html>
dashbord.html 引用
<!--顶部导航栏-->
<div th:replace="~{commons/commons::topbar}"></div>
<!--侧边栏-->
<div th:replace="~{commons/commons::siedbar(active='main.html')}"></div>
emp/list.html 引用
<!--顶部导航栏-->
<div th:replace="~{commons/commons::topbar}"></div>
<!--侧边栏-->
<div th:replace="~{commons/commons::siedbar(active='emps')}"></div>
展示页面
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2><a class="btn btn-sm btn-success" th:href="@{/emp}">添加员工</a></h2>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>department</th>
<th>birth</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.getId()}"></td>
<td>[[${emp.getLastName()}]]</td>
<td th:text="${emp.getEmail()}"></td>
<td th:text="${emp.getGender()==0 ? '女' : '男'}"></td>
<td th:text="${emp.getEDepartment().getDepartmentName()}"></td>
<td th:text="${#dates.format(emp.getBirth(), 'yyyy-MM-dd HH:mm:ss')}"></td>
<td>
<a class="btn btn-sm btn-primary">编辑</a>
<a class="btn btn-sm btn-danger">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
</main>
增加员工
将添加员工信息改为超链接
<!--添加员工按钮-->
<h2> <a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}">添加员工</a></h2>
编写对应的controller
//to员工添加页面
@GetMapping("/emp")
public String toAddPage(){
return "emp/add";
}
添加前端页面;复制list页面,修改即可
bootstrap官网文档 : https://v4.bootcss.com/docs/4.0/components/forms/ , 我们去可以里面找自己喜欢的样式!
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<form th:action="@{/emp}" method="post">
<div class="form-group">
<label>LastName</label>
<input type="text" name="lastName" class="form-control" placeholder="宋端正">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" placeholder="sdz@qq.com">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department">
<option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}">
</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" name="birth", class="form-control" placeholder="1998/12/8 00:00:00">
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
</main>
部门信息下拉框应该选择的是我们提供的数据,所以我们要修改一下前端和后端controller
@Autowired
DepartmentMapper departmentMapper;
@GetMapping("/emp")
public String toAddPage(Model model){
// 查询部门信息,用于下拉框
List<Department> departments = departmentMapper.getDepartments();
model.addAttribute("departments", departments);
return "emp/add";
}
<div class="form-group">
<label>department</label>
<!--提交的是部门的ID-->
<select class="form-control">
<option th:each="dept:${departments}" th:text="${dept.departmentName}" th:value="${dept.id}">1</option>
</select>
</div>
OK,修改了controller,重启项目测试!
我们来具体实现添加功能;
修改add页面form表单提交地址和方式
RestFul风格
<form th:action="@{/emp}" method="post">
编写controller;
//员工添加功能,使用post接收
@PostMapping("/emp")
public String AddEmp(Employee employee){
// 添加员工
employeeMapper.addEmployee(employee);
return "redirect:/emps";
}
回忆:重定向和转发 以及 /的问题?
原理探究 : ThymeleafViewResolver
public static final String REDIRECT_URL_PREFIX = "redirect:";
public static final String FORWARD_URL_PREFIX = "forward:";
protected View createView(String viewName, Locale locale) throws Exception {
if (!this.alwaysProcessRedirectAndForward && !this.canHandle(viewName, locale)) {
vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
return null;
} else {
String forwardUrl;
if (viewName.startsWith("redirect:")) {
vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName);
forwardUrl = viewName.substring("redirect:".length(), viewName.length());
RedirectView view = new RedirectView(forwardUrl, this.isRedirectContextRelative(), this.isRedirectHttp10Compatible());
return (View)this.getApplicationContext().getAutowireCapableBeanFactory().initializeBean(view, viewName);
} else if (viewName.startsWith("forward:")) {
vrlogger.trace("[THYMELEAF] View \"{}\" is a forward, and will not be handled directly by ThymeleafViewResolver.", viewName);
forwardUrl = viewName.substring("forward:".length(), viewName.length());
return new InternalResourceView(forwardUrl);
} else if (this.alwaysProcessRedirectAndForward && !this.canHandle(viewName, locale)) {
vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName);
return null;
} else {
vrlogger.trace("[THYMELEAF] View {} will be handled by ThymeleafViewResolver and a {} instance will be created for it", viewName, this.getViewClass().getSimpleName());
return this.loadView(viewName, locale);
}
}
}
OK,看完源码,我们继续编写代码!
我们要接收前端传过来的属性,将它封装成为对象!首先需要将前端页面空间的name属性编写完毕!【操作】
编写controller接收调试打印【操作】
@PostMapping("/emp")
public String AddEmp(Employee employee){
System.out.println(employee);
// 添加员工
employeeMapper.addEmployee(employee);
return "redirect:/emps";
}
前端填写数据,注意时间问题
点击提交,后台输出正常!页面跳转及数据显示正常!OK!
那我们将时间换一个格式提交
提交发现页面出现了400错误!
生日我们提交的是一个日期 , 我们第一次使用的 / 正常提交成功了,后面使用 - 就错误了,所以这里面应该存在一个日期格式化的问题;
SpringMVC会将页面提交的值转换为指定的类型,默认日期是按照 / 的方式提交 ; 比如将2019/01/01 转换为一个date对象。
那思考一个问题?我们能不能修改这个默认的格式呢?
我们去看webmvc的自动配置文件;找到一个日期格式化的方法,我们可以看一下
@Bean
public FormattingConversionService mvcConversionService() {
WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat());
this.addFormatters(conversionService);
return conversionService;
}
调用了 getDateFormat 方法;
public String getDateFormat() {
return this.dateFormat;
}
这个在配置类中,所以我们可以自定义的去修改这个时间格式化问题,我们在我们的配置文件中修改一下;
spring:
mvc:
format:
date: yyyy-MM-dd
这样的话,我们现在就支持 - 的格式了,但是又不支持 / 了 , 2333吧
测试OK!
员工修改功能
我们要实现员工修改功能,需要实现两步;
-
点击修改按钮,去到编辑页面,我们可以直接使用添加员工的页面实现
-
显示原数据,修改完毕后跳回列表页面!
我们去实现一下:首先修改跳转链接的位置;
<a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a>
编写对应的controller
//to员工修改页面
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id") Integer id, Model model){
// 查出原来数据
Employee employee = employeeMapper.getEmployee(id);
model.addAttribute("emp", employee);
// 查询部门信息,用于下拉框
List<Department> departments = departmentMapper.getDepartments();
model.addAttribute("departments", departments);
return "emp/update";
}
我们需要在这里将add页面复制一份,改为update页面;需要修改页面,将我们后台查询数据回显
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<form th:action="@{/emp}" method="post">
<div class="form-group">
<label>LastName</label>
<input th:value="${emp.getLastName()}" type="text" name="lastName" class="form-control" placeholder="宋端正">
</div>
<div class="form-group">
<label>Email</label>
<input th:value="${emp.getEmail()}" type="email" name="email" class="form-control" placeholder="sdz@qq.com">
</div>
<div class="form-group">
<label>Gender</label><br/>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender() == 1}" class="form-check-input" type="radio" name="gender" value="1">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender() == 0}" class="form-check-input" type="radio" name="gender" value="0">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department">
<option th:selected="${dept.getId() == emp.getDepartment}"
th:each="dept:${departments}"
th:text="${dept.getDepartmentName()}"
th:value="${dept.getId()}">
</option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input name="birth" type="text" class="form-control" th:value="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}">
<!-- <input th:value="${emp.getBirth()}" type="text" name="birth", class="form-control" placeholder="1998/12/8 00:00:00">-->
</div>
<button type="submit" class="btn btn-primary">修改</button>
</form>
</main>
测试OK!
发现我们的日期显示不完美,可以使用日期工具,进行日期的格式化!
<input name="birth" type="text" class="form-control" th:value="${#dates.format(emp.birth,'yyyy-MM-dd HH:mm')}">
数据回显OK,我们继续完成数据修改问题!
修改表单提交的地址:
<form th:action="@{/updateEmp}" method="post">
编写对应的controller
@PostMapping("/updateEmp")
public String updateEmp(Employee employee){
employeeMapper.updateEmployee(employee);
//回到员工列表页面
return "redirect:/emps";
}
发现页面提交的没有id;我们在前端加一个隐藏域,提交id;
<input name="id" type="hidden" class="form-control" th:value="${emp.id}">
重启,修改信息测试OK!
注意日期少一天的问题:
时间设置时区。
spring:
datasource:
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3307/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring:
jackson:
time-zone: GMT+8
删除员工
list页面,编写提交地址
<a class="btn btn-sm btn-danger" th:href="@{/delEmp/}+${emp.id}">删除</a>
编写Controller
@GetMapping("/delEmp/{id}")
public String delEmp(@PathVariable("id") Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}
测试OK!
定制错误页面
我们只需要在模板目录下添加一个error文件夹,文件夹中存放我们相应的错误页面,比如404.html 或者 4xx.html 等等,SpringBoot就会帮我们自动使用了!
注销功能
<a class="nav-link" href="#" th:href="@{/user/loginOut}">注销</a>
对应的controller
@GetMapping("/user/loginOut")
public String loginOut(HttpSession session){
session.invalidate();
return "redirect:/index.html";
}
学到这里,SpringBoot的基本开发就以及没有问题了;
前端
前端: .
- 模板:别人写好的,我们拿来改成自己需要的
- 框架:组件:自己手动组合拼接! Bootstrap, Layui, semantic-ui
- 栅格系统
- 导航栏
- 侧边栏
- 表单
总结
- 前端搞定:页面长什么样子:数据
- 设计数据库(数据库设计难点)
- 前端让它能够独立运行,独立化工程
- 数据接口如何对接:json, 对象all in one!
- 前后端联调测试!
有一套自己熟悉的后台模板:工作必要 (X-admin)
前端界面:至少自己能够通过前端框架,组合出来一个网站页面。