Day43——SpringBoot学习笔记part1

SpringBoot入门1

认识SpringBoot

SpringBoot第一个程序

Spring Boot的诞生和Spring是息息相关的,Spring Boot是Spring发展到一定程度的一个升级版。

Servlet + jsp 原生开发,十分的麻烦,web.xml 或者代码中都会存在大量重复内容;

Spring,Spring的前身是interface21, Spring是一个从实际开发中抽取出来的框架,因此它完成了大量开发中的通用步骤,留给开发者的仅仅是与特定应用相关的部分,从而大大提高了企业应用的开发效率。

经过十几年的发展,spring中集成很多框架或者做一些大型项目,会导致整个程序和项目十分的臃肿以及通篇的配置文件;

Springboot的诞生,就简化了配置文件,以前很多需要手动配置的,现在自动就配置好

SpringBoot第一个程序

  • 新建一个project,选择Spring Initializr,如图所示,点击next

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s8fxE9Ay-1583485630626)(SpringBoot.assets/1583209643849.png)]

  • 项目名的填写,next下一步

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XI8if1VM-1583485630628)(SpringBoot.assets/1583209771704.png)]

  • 进行启动器的勾选!web项目,选择Springweb,next下一步

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lEESKC5o-1583485630628)(SpringBoot.assets/1583209827959.png)]

  • 选择项目路径后,Finish

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fEHv1FFr-1583485630628)(SpringBoot.assets/1583209888517.png)]

现在,在Springbootdemo文件夹下中SpringbootdemoApplication类所在的同级目录或子级目录下建立Controller层,开始建立第一个hello程序

  • 在Controller目录下建立HelloController类
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public  String hello(){
        return  "Hello,world";
    }
}
  • 点击SpringbootdemoApplication类中的运行

控制台输出:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8qqrG3j3-1583485630629)(SpringBoot.assets/1583210115446.png)]

在浏览器中打开,输入http://localhost:8080/hello,会在页面输出Hello,world字样,即成功。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fBnjbZKa-1583485630630)(SpringBoot.assets/1583209156608.png)]
banner.txt文件存放启动logo样式


浅显理解SpringBoot原理

  • 如何启动?

新建的一个SpringBoot项目中,都有一个主启动类

@SpringBootApplication
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }
}

注解:@SpringBootApplication就代表时SpringBoot的应用

:SpringbootdemoApplication,Spring的启动类

调用run方法

如何把自己的类变成SpringBoot的主启动类?

1、在类上面增加一个注解@SpringBootApplication

2、使用SpringBootApplication 的run方法启动

  • 依赖如何配置?

pom.xml

<!--父依赖-->
<!--spring-boot-starter-xx 启动类-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<!--点进spring-boot-starter-parent的源码查看-->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.2.5.RELEASE</version>
    <relativePath>../../spring-boot-dependencies</relativePath>
  </parent>

父依赖作用分析:

1、自动帮你管理依赖,里面包含了几乎常用的所有依赖

2、插件和资源过滤的管理

启动器:spring-boot-starter-xx,

在官网学习:https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/html/using-spring-boot.html#using-boot


学习SpringBoot的配置

所有的配置都可在配置文件中配置,如

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rtCn5XtS-1583485630631)(SpringBoot.assets/1583235404831.png)]

application*.yml
application*.yaml
application*.properties
  • properties 是我们传统的配置文件 ,里面存放 key = value

application.properties文件,在这里也可以编写一些SpringBoot的配置

# 更改tomcat端口号
server.port=9090
  • yaml SpringBoot 推荐的配置文件,功能更加强大
# 普通键值对
key: value
name: xiaoxiao

# map/对象,冒号后带一个空格,还要注意缩进
key:
  k1: v1
  k2: v2
  
person:
  name: Tom
  age: 22

# 行内写法 {}
person: {name: Tom,age: 22}
  
# list/数组
key:
  - v1
  - v2
  
pets:
  - dog
  - fish
  - cat

# 行内写法
pets: [dog,fish,cat]

SpringBoot集成Mybatis

数据访问层:mybatis中的所有包都是自己的,所以要导入自己的依赖

自定义的包
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

还有一个连接数据库的驱动

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

配置一(可以在properties文件中配置):

# server.port=8080
#spring.datasource.username=root
#spring.datasource.password=123456
#spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
#spring.datasource.driver=com.mysql.cj.jdbc.Driver

# mysql 5 com.mysql.jdbc.Driver
# mysql 8 com.mysql.cj.jdbc.Driver 必须要在url中编写时区

配置二(使用application.yaml):

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.feng.springbootdemo.pojo
  mapper-locations: classpath:com/feng/springbootdemo/mapper/*.xml

测试一下 数据源的存在,在test文件中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zcW0fsA8-1583485630633)(SpringBoot.assets/1583236373026.png)]

SpringbootdemoApplicationTest测试类中进行测试

@SpringBootTest
class SpringbootdemoApplicationTests {

    //自动导入数据源
    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        //查看默认数据源
        System.out.println(dataSource.getClass());
        //connection
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        //关闭
        connection.close();
    }
}

结果:class com.zaxxer.hikari.HikariDataSource

SpringBoot 2.X ,目前默认集成的是 Hikari数据源

tips:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4R9CpuOY-1583485630633)(SpringBoot.assets/1583214486788.png)]


SpringBoot开发Web应用

可使用的存放资源的文件夹:

  • static 静态资源
  • templates 页面
  • resources 资源文件
  • public 在SpringBoot源码中存在,公共的静态资源可存放

首页定制:

在静态资源目录下,建立一个index.html

tips:其它目录下存放的index.html都可访问;templates放页面,只通过Controller来访问

测试存在一级或多级目录,如何访问?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a6mz9N0f-1583485630634)(SpringBoot.assets/1583218064754.png)]

@Controller
public class IndexController {
    
    //在SpringBoot中,要使用默认的模板引擎,要导入thymeleaf依赖
    @RequestMapping("/")
    public  String index(){
        return  "index";
    }
}

@Controller
public class IndexController {
    //在SpringBoot中,要使用默认的模板引擎,要导入thymeleaf依赖
    @RequestMapping("/")
    public  String index(){
        return  "index";
    }

    //测试在templates目录下建立文件与文件夹时,返回的路径写法
    @RequestMapping("/user")
    public String user(){
        return "/user/user.html";
    }
    @RequestMapping("/UserList")
    public String list1(){
        return "/user/list/UserList.html";
    }

}

页面传值:

在controller层中

@RequestMapping("/UserList")
public String list1(Model model){
    ArrayList<User> users = new ArrayList<>();
    users.add(new User(1,"小白","123"));
    users.add(new User(2,"小黑","456"));
    model.addAttribute("users",users);

    return "/user/list/UserList.html";
}

在前端页面Userlist.html中取值方法

<!--普通取值-->
<p th:text="${msg}"></p>

<!--循环遍历,接收后端传递的users,遍历每个结果就是user,可以在这个标签内使用:th:each="item:items"-->
<h2 th:each="user:${users}" th:text="${user}"></h2>
<!--行内写法-->
<h2 th:each="user:${users}">[[${user}]]</h2>

<div th:each="user:${users}">
    <p th:text="${user}"></p>
</div>

Userlist.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用户名单</h1>
<h2 th:each="user:${users}" th:text="${user}"></h2>
<hr>
<h2 th:each="user:${users}">[[${user}]]</h2>
<hr>
<div th:each="user:${users}">
    <p th:text="${user}"></p>
</div>
</body>
</html>

启动后,在浏览器地址栏中输入 http://localhost:8080/UserList 查看

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fQYJ1acp-1583485630635)(SpringBoot.assets/1583377459320.png)]


实践:SpringBoot开发web项目

一个员工管理系统的建立

1.建立SpringBoot项目
2.导入素材

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j1yGkn4y-1583485630636)(SpringBoot.assets/1583377684008.png)]

3.模拟数据库
  • 建立pojo、dao、controller、config目录结构
  • 建立所需数据对应的类
    • Deapartment部门类
    • Employee员工类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    private Integer id;
    private String departmentName;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
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;
}
  • 建立对应dao层的操作
// 模拟数据库
@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();
    }
    // 通过id获取部门信息
    public Department getDepartment(Integer id){
        return departments.get(id);
    }

}
// 模拟数据库
@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"),new Date()));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB"),new Date()));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC"),new Date()));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD"),new Date()));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE"),new Date()));
    }

    private static Integer initId = 1006;

    // 新增员工实时 id 自增
    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();
    }

    // 通过id获取员工
    public Employee get(Integer id){
        return employees.get(id);
    }

    // 通过id删除员工
    public void delete(Integer id){
        employees.remove(id);
    }

}
4.首页实现
  • 方法一:可以在Controller层写,用@RequsetMapping实现,return回index页面

  • 方法二:在config目录下配置

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

启动后,就可访问localhost:8080进行查看,但是会发现没有样式,因为静态资源没有加载,这里使用thymeleaf来接管所有静态资源。

解决

  • index.html中,在< html >标签中加上xmlns:th="http://www.thymeleaf.org"命名空间,这是使用thymeleaf,但是一些路径,资源要配置成thymeleaf所支持的格式
  • 在比如超链接herf,src…前面加上th:,所有的Link URL:使用@{},其中@{/}这里面的第一个斜杠,表示根目录,static是静态目录不用写
<!DOCTYPE html>
<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" action="dashboard.html">
			<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
			<h1 class="h3 mb-3 font-weight-normal">Please Sign in</h1>
            
			<label class="sr-only">Username</label>
			<input type="text" class="form-control" name="username" placeholder="Username" required="" autofocus="">
			<label class="sr-only">Password</label>
			<input type="password" class="form-control" name="password" placeholder="Password" required="">
			<div class="checkbox mb-3">
				<label>
					<input type="checkbox" value="remember-me">Remember me
				</label>
			</div>
			<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
			<a class="btn btn-sm">中文</a>
			<a class="btn btn-sm">English</a>
		</form>
	</body>
</html>

此时再运行后,样式就出现了,后面将其他html文件也这样更改

5.页面国际
  • 先保证IDEA中的全局编码为UTF-8

  • 在resources目录下建立个i18n文件夹(internationalization国际化)
  • 在i18n下建立新的配置文件,login.properties;再建立login_zh_CN.properties,发现自动创建一文件夹将其管理;再在系统刚创建的文件夹鼠标右键,Add …Login,选择,如下图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nGfUkwqt-1583485630637)(SpringBoot.assets/1583380050638.png)]

  • 创建完后,点击Resource Bundle

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-shSvdoC4-1583485630638)(SpringBoot.assets/1583380309949.png)]

  • 进行编写

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kerCEAJ7-1583485630638)(SpringBoot.assets/1583380268245.png)]

在login.properties文件中存放:

login.btn=登录
login.password=密码
login.remember=记住我
login.tip=请登录
login.username=用户名

接着在application.properties中配置刚写的

# 绑定i18n
spring.messages.basename=i18n.login

在index.html中,更改一处进行测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FnzSBQul-1583485630639)(SpringBoot.assets/1583380958882.png)]

测试结果,没有问题,进行全部的更改

注意:使用的是#{}来取值

<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please Sign in</h1>

<input type="text" class="form-control" name="username" th:placeholder="#{login.username}" required="" autofocus="">

<input type="password" class="form-control" name="password" th:placeholder="#{login.password}" required="">

<input type="checkbox" value="remember-me"> [[#{login.remember}]]

<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>

目前显示为:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pmu2LkWY-1583485630640)(SpringBoot.assets/1583382042820.png)]

现在,需要将页面下方的中英文切换按钮的功能实现!

在config中编写MyLocaleResolver这个类

前端传个参数

<a class="btn btn-sm" th:href="@{/index.html(lan='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(lan='en_US')}">English</a>

MyLocaleResolver类:

public class MyLocaleResolver implements LocaleResolver {

    //解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        //获取请求中的语言参数
        String language= httpServletRequest.getParameter("lan");

        //如果没有参数就为默认的
        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) {
    }
}

往容器中注入组件,在MyMvcConfig中配置

@Bean
public LocaleResolver localeResolver(){
    return new MyLocaleResolver();
}

运行测试,此时就可通过下方链接切换中英文

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NzS7OpsC-1583485630641)(SpringBoot.assets/1583393488285.png)]

6.登录功能的实现
  • index.html中表单的提交动作更改
<form class="form-signin" th:action="@{/user/login}" method="post">
  • 在controller中创建LoginController,先写一步,测试,成功后再写
@Controller
public class LoginController {

    @RequestMapping("/user/login")
    @ResponseBody
    public String login(){
        return "OK";
    }
}
//测试成功
  • 利用index.html中Username与Password中的name属性,在controller中接收,进行操作
@RequestMapping("/user/login")
public String login(@RequestParam("username") String username,
                    @RequestParam("password") String password,
                    Model model){

    //具体业务
    if (!StringUtils.isEmpty(username) && "123456".equals(password)){
        return "dashboard";
    }else {
        //告诉用户登陆失败,model传值
        model.addAttribute("msg","用户名或密码错误");
        return "index";
    }
}
  • 若用户名与密码错误,页面应该给予提示
<!--判断是否有错误信息${msg}-->
<p th:if="${not #strings.isEmpty(msg)}" th:text="#{login.msg}" style="color: red"></p>

启动测试后,任意用户名和123456密码,访问dashboard页面,路径显示 http://localhost:8080/user/login ,我们想通过访问/main.html也能访问到dashboard,于是就可在配置里面添加映射

@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");
    }
...}

然后在login controller中登录之后重定向到main.html

//具体业务
if (!StringUtils.isEmpty(username) && "123456".equals(password)){
    return "redirect:/main.html";
}else {...}

不过现在就有问题,在没有登录的情况下,也可以访问main.html页面,不符合情理,所以增加拦截器

7.拦截器

在config目录下,新建LoginHandlerInterceptor类,实现HandlerInterceptor接口,重写其中方法

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;//不放行
        }else{
            return true;
        }
    }
}

写完,在配置中注册

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
    }

测试一下

直接访问main.html会跳转至登录页面

8.展示员工列表
  • 首先在dashboard.html文件中找到customs,使其在页面中点击后能够展示员工信息
<li class="nav-item">
	<a class="nav-link" href="这里应该跳到写的Controller">
		......							
        (原来是Customs)员工管理
	</a>
</li>
  • Controller的编写
@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }
}
  • 功能页面分类

templates目录下建立emp文件夹,将list.html放入

  • dashboard页面与list页面中的员工管理保持一致
  • 抽取页面中相同的部分(侧边栏与导航栏),thymeleaf的fragment知识
<!--dashboard.html中侧边栏抽取出,相当于个组件-->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar"...>
<!--抽取导航栏-->
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar"...>
<!--list.html-->
<body>
	<!--dashboard.html导航栏抽取,list页面的导航栏位置也插入-->
	<div th:insert="~{dashboard::topbar}"></div>

		<div class="container-fluid">
			<div class="row">
				<!--dashboard那边侧边栏提取出,这边插入-->
				<div th:insert="~{dashboard::sidebar}"></div>
                ....
  • 将公共的部分抽取出,在templates下建立common文件夹,建立commons.html页面
    • 提取:th:fragment=""
<!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"...>
<!--侧边栏的抽取-->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar"...>
  • 在dashboard与list页面中进行replace,实行代码的复用!
	<!--顶部导航栏,,从common中拿过来-->
	<div th:replace="~{common/commons::topbar}"></div>
    <!--2.侧边栏,,从common中拿过来-->
    <div th:replace="~{common/commons::sidebar}"></div>
  • 现在的问题是鼠标放在员工管理处,没有高亮,解决
    • 在调用模板引擎的时候传递参数
<!--list.html中-->
<div th:replace="~{common/commons::sidebar(active='list.html')}"></div>

在common.html中,对应的员工管理标签处进行判断激活

此处使用thymeleaf三元判断符,解释:当active为list.html时,点亮激活(active),否则不点亮激活

<li class="nav-item">
    <a th:class="${active=='list.html'?'nav-link active':'nav-link'}" th:href="@{/emps}">
                    ...
                    员工管理
    </a>
</li>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u3M9bDsy-1583485630642)(SpringBoot.assets/1583411687944.png)]

  • 现在在list页面中进行表格的编写,表头与Employee中的属性一一对应
<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>
        </tr>
    </thead>
  • 表的身体,遍历出
<tbody>
    <tr th:each="emp:${emps}">
        <td th:text="${emp.getId()}"></td>
        <td th:text="${emp.getLastName()}"></td>
        <td th:text="${emp.getEmail()}"></td>
        <td th:text="${emp.getGender()}"></td>
        <td th:text="${emp.getDepartment().getDepartmentName()}"></td>
        <td th:text="${emp.getBirth()}"></td>
    </tr>
</tbody>
  • 对显示出的列表加以优化,如,男女的显示,日期的显示,添加编辑,删除按钮
<tr>
    ....
	<th>操作</th>       
</tr>
<tbody>
    <tr th:each="emp:${emps}">
        <td th:text="${emp.getId()}"></td>
        <td th:text="${emp.getLastName()}"></td>
        <td th:text="${emp.getEmail()}"></td>
        <td th:text="${emp.getGender()==0?'':''}"></td>
        <td th:text="${emp.getDepartment().getDepartmentName()}"></td>
        <td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td>
        <td>
            <button class="btn btn-sm btn-primary">编辑</button>
            <button class="btn btn-sm btn-danger">删除</button>
        </td>
    </tr>
</tbody>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sTbaiNkj-1583485630643)(SpringBoot.assets/1583413126500.png)]

9.增加员工
  • 在页面上首先要有一个添加按钮
  • 跳转到添加页面
  • 添加员工之后
  • 返回首页

写Controller,使用@GetMapping注解

@GetMapping("/emp")
public String toAddpage(Model model){
    //查出所有部门的信息
    Collection<Department> departments = departmentDao.getDepartments();
    model.addAttribute("departments",departments);
    return "emp/add";
}

少员工添加页面,复制list.html进行更改;将增加页面与列表页面都放在emp文件夹下

<!--add,html中将list页面其他位置不变,
更改<main>下内容(可以从bootstrap网站上增加其他样式的表单自己用)-->

<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="XX@163.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.id">
                <!--遍历取出department,给option一个value值,提交的时候提交value的值-->
                <!--在controller接收的是一个employee对象,这里我们需要提交的是其中的一个属性-->
                <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="2020-02-02">
        </div>
        <button type="submit" class="btn btn-primary">添加</button>
    </form>
</main>

controller中增加表单的提交动作,(restful风格)

@PostMapping("/emp")
public String addEmp(Employee employee){
    //添加的操作
    System.out.println("save=>"+employee);
    employeeDao.save(employee);
    return "redirect:/emps";
}

这里在页面输入日期格式时,可在application.properties中设置

# 处理增加用户信息时,时间日期输入格式(默认时yyyy/MM/dd)
spring.mvc.date-format=yyyy-MM-dd
10.修改员工信息

修改员工对应的在list.html中编辑按钮的操作

编写一个修改页面,复制add.html,在此上进行更改

  • 先到员工的修改页面
//到员工的修改页面
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
    //查出原来的数据
    Employee employee = employeeDao.get(id);
    model.addAttribute("emp",employee);

    //查出来部门信息
    Collection<Department> departments = departmentDao.getDepartments();
    model.addAttribute("departments",departments);
    return "emp/update";
}

//表单中更新操作完成后,返回人员清单
@PostMapping("/updateEmp")
public String UpdateEmp(Employee employee){

    employeeDao.save(employee);
    return "redirect:/emps";
}
  • 在修改页面中,form表单中每个属性上添加value的值,这样修改后,后端拿到
  • 添加一个隐藏域标签放置要修改人员的id,后台拿到,在点击修改后,被修改人的id不会出现变化
  • 在日期显示中,要使用规定的格式(yyyy-MM-dd)
<form th:action="@{/updateEmp}" method="post">
    <!--添加一个隐藏域标签-->
    <input type="hidden" name="id" th:value="${emp.getId()}">
    <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="XX@163.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.id">
            <!--遍历取出department,给option一个value值,提交的时候提交value的值-->
            <!--在controller接收的是一个employee对象,这里我们需要提交的是其中的一个属性-->
            <option th:selected="${dept.getId()==emp.getDepartment().getId()}"
                    th:each="dept:${departments}" th:text="${dept.getDepartmentName()}" th:value="${dept.getId()}"></option>

        </select>
    </div>
    <div class="form-group">
        <label>Birth</label>
        <input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:dd')}" type="text" name="birth" class="form-control" placeholder="2020-02-02">
    </div>
    <button type="submit" class="btn btn-primary">修改</button>
</form>

测试,成功修改用户信息

11.删除与404处理
  • 通过拿到要删除人的id,进行删除操作
  • 删除完,转至员工清单
<a class="btn btn-sm btn-danger" th:href="@{/delemp/{empid}(empid=${emp.id})}">删除</a>
//删除信息
@GetMapping("/delemp/{id}")
public String delete(@PathVariable("id") Integer id){
    employeeDao.delete(id);
    return "redirect:/emps";
}
  • 注销用户的处理
    • 在导航栏中的Sign out ,所以在common中
<a class="nav-link" th:href="@{/user/loginout}">注销</a>
//在logincontroller中
@RequestMapping("/user/loginout")
public String loginOut(HttpSession session){
    session.invalidate();
    return "redirect:/index.html";
}
  • 404的处理
    • 在templates文件夹下建立error文件夹
    • 将404.html放入error文件夹里,这样在报错时,会自动转至404
    • 还可以添加500.html,当报500错误时,也会自动跳转

像是在路径后加上未知的一些,就会报404

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oxMaF8nw-1583485630644)(SpringBoot.assets/1583483919133.png)]


SpringBoot补充
SpringBoot原理分析
下一节学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值