springboot从入门到进阶

1、Hello,SpringBoot
2、SpringBoot原理
3、SpringBoot整合MyBatis
4、SpringBoot集成页面
5、Thymaleaf模板传值
6、Springboot开发Web项目

1、Hello,SpringBoot

spring发展有三个阶段:

  • Servlet + jsp :原生开发,十分的麻烦,web.xml 或者代码中都会存在大量重复内容;
  • Spring 春天:2003 年====> 2020年,里面所有东西都是配置文件。集成很多框架或者做一些大型项目,会导致整个程序和项目十分的臃肿;通篇的配置文件;web.xml,tomcat 都要配置,lib依赖 也需要管理
  • SpringBoot:为了简化配置文件,就好像Spring的升级版,原来很多东西需要手动配置,现在只需要自动配置!
    在SpringBoot中,启动一个服务,就好比启动了一个 hello,wolrd 程序
public class Hello{
	public static void main(String[] args){
		System.out.println("hello,wolrd");
	}
}

我的第一个SpringBoot程序

1、使用IDEA构建一个SpringBoot程序!
在这里插入图片描述
2、填写Maven项目基本信息
在这里插入图片描述
3、勾选启动器(Spring Web) 如果你勾选了这个,相当于帮你自动配置好了Spring和SpringMVC!包括Tomcat
在这里插入图片描述
4、完成之后,等待Maven自动下载所有的依赖即可,第一次有点慢!
在这里插入图片描述5、第一个程序测试

  • 新建controller 包(一定要在 SpringBoot 主启动类的同级或者子级目录下,新建包!否则是识别不了的;)
  • 新建一个HelloController
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "Hello,World!";
    }

}

结果:
在这里插入图片描述
小惊喜:
自定义的启动Logo,默认是SpringBoot
1、我们在 resource 目录下新建一个 banner.txt,在这里面写入自己的banner即可
2、在线网站生成:https://www.bootschool.net/ascii
3、启动测试看效果
在这里插入图片描述


2、SpringBoot原理了解

2.1、如何启动springboot

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

package com.kuang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // 只要标注了他就代表是SpringBoot的应用
public class HelloSpringbootApplication {
	// 你以为启动一个方法,没想到开启了一个服务
    public static void main(String[] args) {
        // Spring的启动类,通过run方法来具体执行
        SpringApplication.run(HelloSpringbootApplication.class, args);
    }

}

一个注解:@SpringBootApplication
一个类:SpringApplication

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

  • 在类上面增加一个注解@SpringBootApplication
  • 使用SpringBootApplication 的run方法启动

2.2、依赖如何配置

SpringBoot默认有一个 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>
<!-- 点进源码后发现 -->
<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、插件和资源过滤的自动管理;
-->

启动器:

<!--依赖-->
<!--在这里写的依赖都不需要版本号,只要在父依赖中有!-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<!-- spring-boot-starter-xx 场景启动器;导入对应场景所需要的类
     会自动帮你导入封装了这个场景所需要需要的依赖
-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

官网有所有的启动器:https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/html/using-spring-boot.html#using-boot

2.3、SpringBoot的配置

所有的配置都可以在配置文件中配置:

application*.yml
application*.yaml
application*.properties

properties 是我们传统的配置文件 key = value

yaml SpringBoot 推荐的配置文件,功能更加强大

yaml所有语法:(空格严格要求,缩进严格要求)

# 普通键值对
key: value
name: yang

# map/对象
key:
  k1: v1
  k2: v3

person:
  name: yang
  age: 3

# 行内写法 {}
person: {name: yang,age: 3}
  
# list/数组
key:
  - v1
  - v2
  
pets:
  - dog
  - pig
  - cat

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

3、SpringBoot整合MyBatis

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

1、导入驱动 和 依赖

<!-- 这是自定义的包 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
<!-- mysql 驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--在这里写的依赖都不需要版本号,只要在父依赖中有!-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2、编写配置文件(两种配置方式)
application.properties

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

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

application.yaml

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

3、测试一下数据源有没有在测试了中测试即可

@SpringBootTest
class HelloSpringbootApplicationTests {

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

    // SpringBoot 2.X 默认集成的是 Hikari
    @Test
    void contextLoads() throws SQLException {
        // 查看默认数据源 class com.zaxxer.hikari.HikariDataSource
        System.out.println(dataSource.getClass());
        // 获得connection连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        // 关闭连接,连接用完一定要关闭
       
        connection.close();
    }


SpringBoot 目前默认的是 数据源 class com.zaxxer.hikari.HikariDataSource

4、编写实体类

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}

5、编写Mapper接口(使用注解和 XML 都可以,二选一即可)
注解:

@Mapper // @Mapper 标注这是一个Mapper接口
@Repository // 代表持久层
public interface UserMapper {

    // @Select("select * from user")
    List<User> getUserLists();

}

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.yang.mapper.UserMapper">
   <select id="getUserLists" resultType="User">
       select * from user;
   </select>
</mapper>

6、编写Controller 调用测试 自动注入即可

@RestController
public class MyBatisController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/list")
    public List<User> getUserList(){
        List<User> userLists = userMapper.getUserLists();
        return userLists;
    }

}

补充:如果发现配置文件没有导出,只需要配置资源过滤即可

 <!-- 如果发现配置文件没有导出,只需要配置资源过滤即可 -->
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

结果:
在这里插入图片描述
我们未来在使用SpringBoot 或者 SPring Cloud 的任何东西的时候,都只需要编写对应的配置文件,导入对应的依赖就可以用了!


4、SpringBoot集成页面

1、资源存放目录说明

static 今天资源

templates 页面,templates只能通过 controller来访问

resources 也可以存放资源文件

public SpringBoot 源码中找到的,静态资源公共的可以放在这里

2、Thymeleaf 使用,导入静态资源模板 使用html 编写页面

  • 导入对应maven依赖

    <!-- thymeleaf依赖,如果要编写页面一定需要这个依赖  -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  • 编写 html 页面放到 templates 目录下

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

  • 使用controller 进行跳转

    @Controller // 可以被视图解析器解析
    public class IndexController {
    
        // 只要访问了 / 就会跳转到 templates目录下的 index 页面
        // SpringBoot 要使用默认的模板引擎 thymeleaf 一定需要导入其对应的依赖!
        @RequestMapping("/")
        public String index(){
            System.out.println("1111");
            return "index";
        }
            @RequestMapping("/user/index")
      public String userIndex(){
          return "user/index";
      }
      @RequestMapping("/user/list")
      public String userList(){
          return "user/list";
      }
    }
    
  • 启动项目请求测试,看是否可以跳转 html 页面!


5、Thymaleaf页面传值

1、在后端方法中使用 Model 传递值

    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("msg","HelloSpringBoot!");
        return "index";
    }

2、在index.html前端使用 th:xxx 去接收后端传递值,注意:一定要导入头文件约束

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>首页</h1>

<!-- 普通取值 -->
<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>

</body>
</html>

6、Springboot开发Web项目

1、首页配置

1、新建一个SPringboot项目,构建web模块

2、导入pojo 和 dao 的类
pojo:

@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;
}

mapper:

/ 模拟数据库
@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")));
        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;

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

3、导入静态资源(页面放在 Templeate,资源 放在 static目录下)
在这里插入图片描述
这时的界面没有样式,因为没有加载css内些文件,解决方法是4.5
4、所有页面增加头文件 xmlns:th="http://www.thymeleaf.org">

5、所有的资源链接修改格式为thymeleaf 语法 th:xxx='@'

6、可以增加一个配置类,配置我们的SpringMVC(了解即可)

@Configuration // 代表这是一个配置类
public class MyMvcConfig implements WebMvcConfigurer {

    // 通过配置类来设置视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }
}

在这里插入图片描述

2、页面国际化

1、保证全局都是utf-8
在这里插入图片描述2、在资源下新建一个文件夹i18n,建立新的配置文件,login.properties;建立login_zh_CN.properties,再添加英文配置
在这里插入图片描述3、可视化配置中设置中英文配置,
在这里插入图片描述
登录的中英文配置:
在这里插入图片描述同理配置剩余的几个:
在这里插入图片描述
4、在application.properties中配置绑定i18n

spring.messages.basename=i18n.login

5、在首页更改刚才的配置

<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>

在这里插入图片描述
6、实现英文登录界面
前端参数:

<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类:

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;
 class MyLocaleResolver implements LocaleResolver {

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

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

注入bean:

//自定义的国家化组件
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

结果:
在这里插入图片描述

3、登录功能

1、前端修改表单提交

<form class="form-signin" th:action="@{/user/login}" method="post">

2、新建一个usercontroller

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 UserController {

    // 登录实现
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model, HttpSession session){

        if (!StringUtils.isEmpty(username) && "123456".equals(password)){
           return "dashboard";
        }else {
            model.addAttribute("msg","用户名或者密码错误");
            return "index";
        }
    }
}

3、如果用户名和密码错误,我们想要前端给出提示,在前端增加一个p标签

<p th:if="${not #strings.isEmpty(msg)}" th:text="#{login.msg}" style="color: red"></p>

4、启动测试后,登录访问dashboard页面,路径显示 http://localhost:8080/user/login ,现在通过访问/main.html也能访问到dashboard,于是就可在配置里面添加映射

 // 通过配置类来设置视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }

5、在usercontroller登陆后重定向到main

 if (!StringUtils.isEmpty(username) && "123456".equals(password)){
            // 登录成功, 利用重定向可以防止表单重复提交
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        }else {
            model.addAttribute("msg","用户名或者密码错误");
            return "index";
        }

在这里插入图片描述

4、拦截器

在config目录下,新建LoginHandlerInterceptor类

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","没有权限,请先登录");
            System.out.println("LoginHandlerInterceptor");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else {
            return true;
        }

    }
}

注册bean:

// 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 选择要过滤和排除的请求
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/index.html","/","/user/login")
                .excludePathPatterns("/asserts/**");
    }

这样访问main的话,会跳转到登录页面
在这里插入图片描述

5、展示员工列表

修改dashboard.html中customs部分:

<li class="nav-item">
		<a class="nav-link" th:href="@{/emps}">
	员工管理
		</a>
</li>

控制类:

@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放入,抽取出来顶部导航栏和侧边栏:在这里插入图片描述将公共的部分抽取出,在templates下建立common文件夹,建立commons.html页面
在这里插入图片描述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

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

表的遍历:

<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()==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>
</table>

6、增

在页面上首先要有一个添加按钮,点击跳转到添加页面,添加员工后,返回到首页
控制类:

@GetMapping("/emp")
public String toAddpage(Model model){
    //查出所有部门的信息
    Collection<Department> departments = departmentDao.getDepartments();
    model.addAttribute("departments",departments);
    return "emp/add";
}
@PostMapping("/emp")
public String addEmp(Employee employee){
    //添加的操作
    System.out.println("save=>"+employee);
    employeeDao.save(employee);
    return "redirect:/emps";
}

添加页面:

<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>

补充:在配置中将默认时间格式yyyy/MM/dd修改为xxxx-xx-xx
spring.mvc.date-format=yyyy-MM-dd

7、改

在list.html中编辑按钮,复制add.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 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>

8、删

页面:

<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";
}

9、注销

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";
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值