6.springboot实现增删改查

springboot


根据目录点击跳转


前言


一、搭建环境

1.新建一个SpringBoot项目(快速创建)

在这里插入图片描述
在这里插入图片描述选择配件时勾选SpringWeb和Thymeleaf(后面再导入依赖也可)
在这里插入图片描述

2.导入静态资源

在这里插入图片描述

3.模拟数据库(这里使用的时本地的假数据)

1.创建数据库实体类

在这里插入图片描述
1.Department部门实体类

//数据一体化添加get set等
@Data
//有参构造
@AllArgsConstructor
//无参构造
@NoArgsConstructor
public class Department {

    private Integer id;
    private String Department;
    //自己需要修改就不用注解默认的就可以
}

2.Employee员工实体类

//员工表
@Data
@NoArgsConstructor
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;//0女 1男
    private Department department;
    private Date birth;
    //有参构造:最简单直白的话,当你要new一个对象的时候,必须要有构造器才能new出来,类里面默认有无参的构造器,看不到的,当我们要创建一个有参构造的时候,最好也把无参构造写出来
    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() ;
    }
}

导入lombok的依赖

<dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
</dependency>

2.编写dao层(模拟数据)

图片
在这里插入图片描述
1.DepartmentDao部门

package com.web.springbootwebmanage.dao;

import com.web.springbootwebmanage.pojo.Department;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//部门dao
@Repository
public class DepartmentDao {
    //模拟数据库中的数据:使用假数据玩
    private static Map<Integer, Department> departments = null;

    static {
        departments = new HashMap<Integer, Department>();//创建一个部门表

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

}

2.EmployeeDao员工

package com.web.springbootwebmanage.dao;


import com.web.springbootwebmanage.pojo.Department;
import com.web.springbootwebmanage.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;

//格式化代码快捷键:Ctrl+Alt+L

//员工dao
@Repository
public class EmployeeDao {

    //模拟数据库中的数据
    private static Map<Integer, Employee> employees = null;

    //注入依赖员工所属部门:这里用不到,我们这里用了new:这是为自己买坑
    @Autowired
    private DepartmentDao departmentDao;

    static {
        employees = new HashMap<Integer, Employee>();//创建一个部门表

        employees.put(1001, new Employee(1001, "AA", "123456@qq.com", 1, new Department(1001, "教学部")));
        employees.put(1002, new Employee(1002, "BB", "123456@qq.com", 0, new Department(1002, "市场部")));
        employees.put(1003, new Employee(1003, "CC", "123456@qq.com", 1, new Department(1003, "运营部")));
        employees.put(1004, new Employee(1004, "DD", "123456@qq.com", 0, new Department(1004, "教研部")));
        employees.put(1005, new Employee(1005, "EE", "123456@qq.com", 1, new Department(1005, "小卖部")));
    }
    //主键自增
    private static Integer initId =1006;

    //保存一个
    public void save(Employee employee){
        if (employee.getId()==null){
            employee.setId(initId++);
        }
        employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
        //将数据打包添加:获取员工id和员工信息
        employees.put(employee.getId(),employee);
    }
    //查询所有
    public Collection<Employee> getAll(){
        return employees.values();
    }
    //通过id查询员工
    public Employee getEmployeeById(Integer id){
        return employees.get(id);
    }
    //删除员工通过id
    public void delete(Integer id){
        employees.remove(id);
    }

}

二、首页实现

在主程序同级目录下新建config包用来存放自己的配置类
在其中新建一个自己的配置类MyMvcConfig,进行视图跳转

在这里插入图片描述
1.MyMvcConfig配置类

//扩展解析器,需要的功能把自己的功能添加进去即可
@Configuration
public class MyMvcConfig3 implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/main.html").setViewName("dashboard");
    }
  }

2.配置css、js、img资源路径使用Thymeleaf模版引擎来使用
类中
3.每个页面需要添加的命名空间:

xmlns:th="http://www.thymeleaf.org"

4.注意:

第一个/代表项目的classpath,也就是这里的resources目录

类似语法:Thymeleaf模版更多语法去看官网
成功页面
在这里插入图片描述

三、页面国际化

1.统一编码

1.统一编码
在这里插入图片描述

2.编写i18n国际化资源文件

1.在resources目录下新建一个i18n包,其中放置国际化相关的配置
什么是i18n??百度哈!!!

命名方式是下划线的组合:文件名_语言_国家.properties;
以此方式命名,IDEA会帮我们识别这是个国际化配置包,自动绑定在一起转换成如下的模式

进行文件夹的绑定
在这里插入图片描述2.点击可视化界面进行手动输入对应的值
在这里插入图片描述
3.其中新建三个配置文件,用来配置语言
在这里插入图片描述
4.解释

其中新建三个配置文件,用来配置语言: 
login.properties:无语言配置时候生效 
login_en_US.properties:英文生效
login_zh_CN.properties:中文生效

3.配置国际化资源名称

1.login.properties

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

2.login_en_US.properties

login.btn=Sign in
login.password=Password
login.remember=remember me
login.tip=Please login
login.username=Username

3.login_zh_CN.properties

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

原理:

在Spring程序中,国际化主要是通过ResourceBundleMessageSource这个类来实现的

Spring Boot通过MessageSourceAutoConfiguration为我们自动配置好了管理国际化资源文件的组件

1.我们在IDEA中查看以下MessageSourceAutoConfiguration类

@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {

	private static final Resource[] NO_RESOURCES = {};

	@Bean
	@ConfigurationProperties(prefix = "spring.messages")
	public MessageSourceProperties messageSourceProperties() {
		return new MessageSourceProperties();
	}

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

主要了解messageSource()这个方法:

public MessageSource messageSource(MessageSourceProperties properties);

可以看到,它的参数为MessageSourceProperties对象,我们看看这个类

public class MessageSourceProperties {

	/**
	 * Comma-separated list of basenames (essentially a fully-qualified classpath
	 * location), each following the ResourceBundle convention with relaxed support for
	 * slash based locations. If it doesn't contain a package qualifier (such as
	 * "org.mypackage"), it will be resolved from the classpath root.
	 */
	private String basename = "messages";

	/**
	 * Message bundles encoding.
	 */
	private Charset encoding = StandardCharsets.UTF_8;

类中首先声明了一个属性basename,默认值为messages;

/**
	 * Comma-separated list of basenames (essentially a fully-qualified classpath
	 * location), each following the ResourceBundle convention with relaxed support for
	 * slash based locations. If it doesn't contain a package qualifier (such as
	 * "org.mypackage"), it will be resolved from the classpath root.
	 */

- 逗号分隔的基名列表(本质上是完全限定的类路径位置)
- 每个都遵循ResourceBundle约定,并轻松支持于斜杠的位置
- 如果不包含包限定符(例如"org.mypackage"),它将从类路径根目录中解析

意思是:

如果你不在springboot配置文件中指定以.分隔开的国际化资源文件名称的话
它默认会去类路径下找messages.properties作为国际化资源文件
这里我们自定义了国际化资源文件,因此我们需要在SpringBoot配置文件application.properties中加入以下配置指定我们配置文件的名称

那么就从配置文件里面读取

spring.messages.basename=i18n.login
#其中i18n是存放资源的文件夹名,login是资源文件的基本名称。

4.首页获取国际化值

1.利用#{…} 消息表达式,去首页index.html获取国际化的值
在这里插入图片描述

<!--登录面板-->
<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 login</h1>
    <!--name设置传递参数:username-->
    <p class="msgred">[[${msg}]]</p>
    <label class="sr-only" th:text="#{login.username}">Username</label>
    <input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
    <!--name设置传递参数:password-->
    <label class="sr-only" th:text="#{login.password}">Password</label>
    <input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">

    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me">[[#{login.remember}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign login</button>
    <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
	<!--th:href="@{/index.html(l='zh_CN')}"加携带参数:链接用@{} 键值对的参数用(l='zh_CN')而不是index.html?l=zh_CN-->
    <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>

2.重启成功
在这里插入图片描述

5.配置国际化的中英文切换

1.添加切换标签

1.使用模版引擎进行配置在这里插入图片描述2.代码

<!--这里传入参数不需要使用?使用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>

2.自定义地区解析器(重写解析器的方法在springboot用的多)

1.原理:

怎么实现我们自定义的地区解析器呢?我们首先来分析一波源码

在Spring中有关于国际化的两个类:

Locale:代表地区,每一个Locale对象都代表了一个特定的地理、政治和文化地区
LocaleResolver:地区解析器

快捷键搜索WebMvcAutoConfiguration ——>找到localeResolver()

//WebMvcAutoConfiguration,可以在其中找到关于一个方法localeResolver()
@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;
}

该方法就是获取LocaleResolver地区对象解析器:
如果用户配置了则使用用户配置的地区解析器;
如果用户没有配置,则使用默认的地区解析器
我们可以看到默认地区解析器的是AcceptHeaderLocaleResolver对象,我们点入该类查看源码

在这里插入图片描述

可以发现它继承了LocaleResolver接口,实现了地区解析
因此我们想要实现上述自定义的国际化资源生效,只需要编写一个自己的地区解析器,继承LocaleResolver接口,重写其方法即可

我们在config包下新建MyLocaleResolver,作为自己的国际化地区解析器
在这里插入图片描述
我们在index.html中,编写了对应的请求跳转

如果点击中文按钮,则跳转到/index.html(l=‘zh_CN’)页面
如果点击English按钮,则跳转到/index.html(l=‘en_US’)页面
在这里插入图片描述
因此我们自定义的地区解析器MyLocaleResolver中,需要处理这两个带参数的链接请求

package com.web.springbootwebmanage.config;

import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

//重写LocaleResolver的方法
public class MyLocalResolver implements LocaleResolver {
    //解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //从前端页面获取的语言参数
        String language = request.getParameter("l");

        System.out.println("Debug==>"+language);

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

    }
}

为了让我们的区域化信息能够生效,我们需要再配置一下这个组件!在自己的MvcConofig配置类下添加bean, 让spring容器来管理该组件。

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

四、登陆功能的实现

我们重启项目,来访问一下,发现点击按钮可以实现成功切换!
点击中文按钮,跳转到http://localhost:8080/index.html?l=zh_CN,显示为中文
中文
在这里插入图片描述
英文
在这里插入图片描述

五、登陆(并且配置拦截器)

登录,也就是当我们点击登录按钮的时候,会进入一个页面,这里进入dashboard页面。
因此我们首先在index.html中的表单编写一个提交地址/user/login,并给名称和密码输入框添加name属性为了后面的传参
在这里插入图片描述

<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 login</h1>
    <!--name设置传递参数:username-->
    <p class="msgred">[[${msg}]]</p>
    <label class="sr-only" th:text="#{login.username}">Username</label>
    <input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
    <!--name设置传递参数:password-->
    <label class="sr-only" th:text="#{login.password}">Password</label>
    <input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="">

    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me">[[#{login.remember}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign login</button>
    <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
	<!--th:href="@{/index.html(l='zh_CN')}"加携带参数:链接用@{} 键值对的参数用(l='zh_CN')而不是index.html?l=zh_CN-->
    <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>

2.编写对应的controller: LoginController2
在主程序同级目录下新建controller包,在其中新建类loginController,处理登录请求

package com.web.springbootwebmanage.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController2 {
   /* 测试环境是否成立
   @RequestMapping("/user/login")
    @ResponseBody
    public String Login(){
        return "yes";
    }*/
   @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)){
           //创建session中有loginUser,在
           session.setAttribute("loginUser",username);
           return "redirect:/main.html";
       }else{
           //model时一个交互的视图
           model.addAttribute("msg","用户名或者输入的密码错误!");
           return "index";
       }
   }
}

页面提示错误信息

<p style="color: red" th:text="${msg}"></p>

位置:
在这里插入图片描述
我们再测试一下,启动主程序,访问localhost:8080
如果我们输入正确的用户名和密码
在这里插入图片描述成功
错误中示范
在这里插入图片描述
问题:
1.到此我们的登录功能实现完毕,但是有一个很大的问题,浏览器的url暴露了用户的用户名和密码,这在实际开发中可是重大的漏洞,泄露了用户信息,因此我们需要编写一个映射
我们在自定义的配置类MyMvcConfig中加一句代码

registry.addViewController("/main.html").setViewName("dashboard");

2.也就是访问/main.html页面就跳转到dashboard页面
然后我们稍稍修改一下LoginController,当登录成功时重定向到main.html页面,也就跳转到了dashboard页面

return "redirect:/main.html";

3.我们再次重启测试,输入正确的用户名和密码登陆成功后,浏览器不再携带泄露信息
4.问题:但是这又出现了新的问题,无论登不登陆,我们访问localhost/main.html都会跳转到dashboard的页面,这就引入了接下来的拦截器
5.配置拦截器:为了解决上述4的问题,我们需要自定义一个拦截器;
在config目录下,新建一个登录拦截器类LoginHandlerInterceptor
理解:

用户登录成功后,后台会得到用户信息;如果没有登录,则不会有任何的用户信息;

我们就可以利用这一点通过拦截器进行拦截:

当用户登录时将用户信息存入session中,访问页面时首先判断session中有没有用户的信息
如果没有,拦截器进行拦截;
如果有,拦截器放行
因此我们首先在LoginController中当用户登录成功后,存入用户信息到session中``
package com.web.springbootwebmanage.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController2 {
   @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)){
           //创建session中有loginUser,在
           session.setAttribute("loginUser",username);
           return "redirect:/main.html";
       }else{
           //model时一个交互的视图
           model.addAttribute("msg","用户名或者输入的密码错误!");
           return "index";
       }
   }
}
然后再在实现自定义的登录拦截器,继承HandlerInterceptor接口

其中获取存入的session进行判断,如果不为空,则放行;

如果为空,则返回错误消息,并且返回到首页,不放行。
package com.web.springbootwebmanage.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//继承一个拦截器的接口
public class LoginHandIerInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        //创建一个session,如果登录成功之后就可以跳转到后台并且生成一个对应的session:是否存在
        //loginUser取出用getAttribute
        Object loginUser = request.getSession().getAttribute("loginUser");
        //判断session会话中是否存在这个loginUser,如果为提示
        if (loginUser == null) {
            request.setAttribute("msg","没有权限请先登录");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }
        //放行
        return true;
    }
}

注册使用:然后配置到bean中注册,在MyMvcConfig配置类中,重写关于拦截器的方法,添加我们自定义的拦截器,注意屏蔽静态资源及主页以及相关请求的拦截

    //将拦截器添加到spring容器中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandIerInterceptor1()).
                addPathPatterns("/**").
                excludePathPatterns("/index.html","/","/user/login","/js/**","/img/**","/css/**");
    }

然后重启主程序进行测试,直接访问http://localhost:8080/main.html
在这里插入图片描述

进入到dashboard页面
如果我们再直接重新访问http://localhost:8080/main.html,也可以直接直接进入到dashboard页面,这是因为session里面存入了用户的信息,拦截器放行通过

在这里插入图片描述

六、展示员工信息——查询所有

1.实现视图跳转

1.目标:点击dashboard.html页面中的Customers展示跳转到list.html页面显示所有员工信息
在这里插入图片描述
2.list页面

<body>
	<!--导航栏-->
		<div th:replace="~{commons/common::sidenav}"></div>
		<div class="container-fluid">
			<div class="row">
				<!--侧边栏-->
				<!--插入组件:dashboard::sidebar       页面::位置-->
				<div th:replace="~{commons/common::sidebar(active='list.html')}"></div>
				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<h2>员工信息栏</h2>
					<a th:href="@{/emp}" class="btn btn-sm btn-success">添加员工</a>

					<div class="table-responsive">
						<table class="table table-striped table-sm">
							<thead>
								<tr>
									<th>序号</th>
									<th>姓名</th>
									<th>电子邮件</th>
									<th>性别</th>
									<th>部门</th>
									<th>生日</th>
									<th>操作</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() == 1 ?'':''}"></td>
									<!--一对多这里-->
									<td th:text="${emp.department.getDepartment()}"></td>
									<td th:text="${#dates.format(emp.getBirth(), 'yyyy-MM-dd HH:mm:ss')}"></td>
									<th>

										<!--路径出错-->
										<!--<a class="btn btn-sm btn-primary" th:href="@{/emp}+${emp.getId()}">编辑</a>-->
										<!--对的-->
										<!--<a class="btn btn-sm btn-primary" th:href="@{/emp}">编辑</a>-->
										<!--百度-->
										<a class="btn btn-sm btn-primary" th:href="@{/emp/{id}(id=${emp.getId()})}">编辑</a>
										<a class="btn btn-sm btn-danger" th:href="@{/delete/{id}(id=${emp.getId()})}">删除</a>
									</th>
								</tr>
							</tbody>
						</table>
					</div>
				</main>
			</div>
		</div>

3.执行查询所有:EmployeeController

package com.web.springbootwebmanage.controller;

import com.web.springbootwebmanage.dao.DepartmentDao;
import com.web.springbootwebmanage.dao.EmployeeDao;
import com.web.springbootwebmanage.pojo.Department;
import com.web.springbootwebmanage.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 {
    //调用dao层的代码;但是一般先走service再走dao,这里直调用
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
    //1.查询所有的员工,返回列表页面
    //@GetMapping("/emps")
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        //放在model请求域中
        model.addAttribute("emps",employees);
        //路径错误/emp/list 前端报错
        return "emp/list";
    }

    //添加页面
    @GetMapping("/emp")
    public String addList(Model model){
        //显示部门数据
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/addlist";
    }

    //添加成功跳回员工页面
    //@RequestMapping("/emp")
    @PostMapping("/emp")
    public String addSuccess(Employee employee){
        //添加的操作
        System.out.println("测试数据-->"+employee);
        //调用底层业务逻辑保存员工信息
        employeeDao.save(employee);
        //c到员工页
        return "redirect:/emps";
    }

}

2.提取功能部分

1.原来

<a class="nav-link active" th:href="@{/main.html}">

2.高亮

 <!--三目运算符:是否激活:对应index页面-->
<a th:class="${active=='main.html'? 'nav-link active' : 'nav-link'}" th:href="@{/main.html}">

1.组件化的开发

在这里插入图片描述
1.抽取共同的部分

<!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="sidenav">
    <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" th:href="@{/user/loginout}">退出注销</a>
        </li>
    </ul>
</nav>

<!--侧边栏-->
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">
    <div class="sidebar-sticky">
        <ul class="nav flex-column">
            <li class="nav-item">
                <!--三目运算符:是否激活:对应index页面-->
                <a th:class="${active=='main.html'? 'nav-link active' : 'nav-link'}" th:href="@{/main.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>
                    订单管理
                </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>
                    产品管理
                </a>
            </li>
            <li class="nav-item">
                <!--三目运算符:是否激活:对应list页面-->
                <a th:class="${active=='list.html'? '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>

2.组件化

<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">

使用

注释:好多可以使用:insert、replace
<div th:replace="~{commons/common::sidenav}"></div>

这里使用:侧边栏和导航栏实现复用

3.高亮部分的实现

1.我们可以传递参数判断点击了哪个标签实现相应的高亮

首先在dashboard.html的侧边栏标签传递参数active为dashboard.html

<!--插入组件:dashboard::sidebar       页面::位置-->
<div th:replace="~{commons/common::sidebar(active='list.html')}"></div

使用:

<!--三目运算符:是否激活:对应index页面-->
<a th:class="${active=='main.html'? 'nav-link active' : 'nav-link'}" th:href="@{/main.html}">

4.显示所有员工

1.修改list.html页面,显示我们自己的数据值
在这里插入图片描述
对应
在这里插入图片描述
添加删除额编辑按钮

<a class="btn btn-sm btn-primary" th:href="@{/emp/{id}(id=${emp.getId()})}">编辑</a>
<a class="btn btn-sm btn-danger" th:href="@{/delete/{id}(id=${emp.getId()})}">删除</a>

运行
在这里插入图片描述

七、增加员工信息——增加一个

1.创建添加员工按钮

lits.html

<h2>员工信息栏</h2>
<a th:href="@{/emp}" class="btn btn-sm btn-success">添加员工</a>

2.创建add页面

addlist.html

<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<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>Dashboard 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/dashboard.css}" rel="stylesheet">
    <style type="text/css">
        /* Chart.js */

        @-webkit-keyframes chartjs-render-animation {
            from {
                opacity: 0.99
            }
            to {
                opacity: 1
            }
        }

        @keyframes chartjs-render-animation {
            from {
                opacity: 0.99
            }
            to {
                opacity: 1
            }
        }

        .chartjs-render-monitor {
            -webkit-animation: chartjs-render-animation 0.001s;
            animation: chartjs-render-animation 0.001s;
        }
    </style>
</head>

<body>
<!--导航栏-->
<div th:replace="~{commons/common::sidenav}"></div>
<div class="container-fluid">
    <div class="row">
        <!--侧边栏-->
        <!--插入组件:dashboard::sidebar       页面::位置-->
        <div th:replace="~{commons/common::sidebar(active='list.html')}"></div>

        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">


            <h2>添加页面</h2>
            <form th:action="@{/emp}" method="post"><!--忘记路径加@{{}}-->
                <div class="form-group">
                    <label>姓名</label>
                    <input type="text" name="lastName" class="form-control" placeholder="lastname:zsr">
                </div>
                <div class="form-group">
                    <label>邮件</label>
                    <input type="email" name="email" class="form-control" placeholder="email:xxxxx@qq.com">
                </div>
                <div class="form-group">
                    <label>性别</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>部门</label>
                    <!--注意这里的name是department.id,因为传入的参数为id-->
                    <select class="form-control" name="department.id">
                        <!--将遍历的department放入dept中-->
                        <option th:each="dept:${departments}" th:text="${dept.getDepartment()}" th:value="${dept.getId()}"></option>
                    </select>
                </div>
                <div class="form-group">
                    <label>生日</label>
                    <!--springboot默认的日期格式为yy/MM/dd-->
                    <input type="text" name="birth" class="form-control" placeholder="birth:yyyy/MM/dd">
                </div>
                <button type="submit" class="btn btn-primary">添加</button>
            </form>
        </main>
    </div>
</div>

<!-- Bootstrap core JavaScript================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" th:src="@{/static/js/jquery-3.2.1.slim.min.js}"></script>
<script type="text/javascript" th:src="@{/static/js/popper.min.js}"></script>
<script type="text/javascript" th:src="@{/static/js/bootstrap.min.js}"></script>

<!-- Icons -->
<script type="text/javascript" th:src="@{/static/js/feather.min.js}"></script>
<script>
    feather.replace()
</script>

<!-- Graphs -->
<script type="text/javascript" th:src="@{/static/js/Chart.min.js}"></script>
<script>
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            datasets: [{
                data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
                lineTension: 0,
                backgroundColor: 'transparent',
                borderColor: '#007bff',
                borderWidth: 4,
                pointBackgroundColor: '#007bff'
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: false
                    }
                }]
            },
            legend: {
                display: false,
            }
        }
    });
</script>

</body>

</html>

3.add页面添加员工请求

控制层写入添加的方法EmployeeController

package com.web.springbootwebmanage.controller;

import com.web.springbootwebmanage.dao.DepartmentDao;
import com.web.springbootwebmanage.dao.EmployeeDao;
import com.web.springbootwebmanage.pojo.Department;
import com.web.springbootwebmanage.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 {
    //调用dao层的代码;但是一般先走service再走dao,这里直调用
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
    //1.查询所有的员工,返回列表页面
    //@GetMapping("/emps")
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        //放在model请求域中
        model.addAttribute("emps",employees);
        //路径错误/emp/list 前端报错
        return "emp/list";
    }

    //添加页面
    @GetMapping("/emp")
    public String addList(Model model){
        //显示部门数据
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/addlist";
    }

    //添加成功跳回员工页面
    //@RequestMapping("/emp")
    @PostMapping("/emp")
    public String addSuccess(Employee employee){
        //添加的操作
        System.out.println("测试数据-->"+employee);
        //调用底层业务逻辑保存员工信息
        employeeDao.save(employee);
        //c到员工页
        return "redirect:/emps";
    }
}

八、修改员工信息——修改一个

1.创建修改的页面

1.updatelist.html

<!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>Dashboard 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/dashboard.css}" rel="stylesheet">
    <style type="text/css">
        /* Chart.js */
        @-webkit-keyframes chartjs-render-animation {
            from {
                opacity: 0.99
            }
            to {
                opacity: 1
            }
        }
        @keyframes chartjs-render-animation {
            from {
                opacity: 0.99
            }
            to {
                opacity: 1
            }
        }
        .chartjs-render-monitor {
            -webkit-animation: chartjs-render-animation 0.001s;
            animation: chartjs-render-animation 0.001s;
        }
    </style>
</head>

<body>
<!--导航栏-->
<div th:replace="~{commons/common::sidenav}"></div>
<div class="container-fluid">
    <div class="row">
        <!--侧边栏-->
        <!--插入组件:dashboard::sidebar       页面::位置-->
        <div th:replace="~{commons/common::sidebar(active='list.html')}"></div>

        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">

            <h2>修改页面</h2>
            <form th:action="@{/updateEmp}" method="post"><!--忘记路径加@{{}}-->
                <!--携带隐藏的id过来-->
               <input type="hidden" name="id" th:value="${emp.getId()}">
                <div class="form-group">
                    <label>姓名</label>
                    <input th:value="${emp.getLastName()}" type="text" name="lastName" class="form-control" placeholder="lastname:zsr">
                </div>
                <div class="form-group">
                    <label>邮件</label>
                    <input th:value="${emp.getEmail()}" type="email" name="email" class="form-control" placeholder="email:xxxxx@qq.com">
                </div>
                <div class="form-group">
                    <label>性别</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>部门</label>
                    <!--注意这里的name是department.id,因为传入的参数为id-->
                    <select class="form-control" name="department.id">
                        <!--将遍历的department放入dept中-->
                        <option th:each="dept:${departments}" th:text="${dept.getDepartment()}" th:value="${dept.getId()}"></option>
                    </select>
                </div>
                <div class="form-group">
                    <label>生日</label>
                    <!--springboot默认的日期格式为yy/MM/dd-->
                    <input th:value="${#dates.format(emp.getBirth(),'yy/mm/dd HH:mm')}" type="text" name="birth" class="form-control" placeholder="birth:yyyy/MM/dd">
                </div>
                <button type="submit" class="btn btn-primary">点击修改</button>
            </form>
        </main>
    </div>
</div>

<!-- Bootstrap core JavaScript================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" th:src="@{/static/js/jquery-3.2.1.slim.min.js}"></script>
<script type="text/javascript" th:src="@{/static/js/popper.min.js}"></script>
<script type="text/javascript" th:src="@{/static/js/bootstrap.min.js}"></script>

<!-- Icons -->
<script type="text/javascript" th:src="@{/static/js/feather.min.js}"></script>
<script>
    feather.replace()
</script>

<!-- Graphs -->
<script type="text/javascript" th:src="@{/static/js/Chart.min.js}"></script>
<script>
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
            datasets: [{
                data: [15339, 21345, 18483, 24003, 23489, 24092, 12034],
                lineTension: 0,
                backgroundColor: 'transparent',
                borderColor: '#007bff',
                borderWidth: 4,
                pointBackgroundColor: '#007bff'
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: false
                    }
                }]
            },
            legend: {
                display: false,
            }
        }
    });
</script>

</body>

</html>

2.页面编辑完成并提交请求

控制层写入添加的方法EmployeeController

package com.web.springbootwebmanage.controller;

import com.web.springbootwebmanage.dao.DepartmentDao;
import com.web.springbootwebmanage.dao.EmployeeDao;
import com.web.springbootwebmanage.pojo.Department;
import com.web.springbootwebmanage.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 {
    //调用dao层的代码;但是一般先走service再走dao,这里直调用
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
    //1.查询所有的员工,返回列表页面
    //@GetMapping("/emps")
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        //放在model请求域中
        model.addAttribute("emps",employees);
        //路径错误/emp/list 前端报错
        return "emp/list";
    }

    //restful风格接收参数
    //修改页面
    @GetMapping("/emp/{id}")
    public String updateList(@PathVariable("id")Integer id,Model model){
        //查出数据
        Employee employee = employeeDao.getEmployeeById(id);
        //将员工信息返回到页面
        model.addAttribute("emp",employee);
        //显示部门数据传到修改的页面
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        /*System.out.println("修改---》");*/
        //显示修改页面
        return "emp/updatelist";
    }
    //提交修改数据到页面
    @PostMapping("/updateEmp")
    public String update(Employee employee){
        //提交的再保存一遍
        employeeDao.save(employee);
        //重定向到员工页
        return "redirect:/emps";
    }
    //删除
    //@GetMapping("/delete/{id}")
    //public String delete(@PathVariable("id") Integer id) {
     // employeeDao.delete(id);
     //return "redirect:/emps";
    //}

}

九、删除一个员工信息

package com.web.springbootwebmanage.controller;

import com.web.springbootwebmanage.dao.DepartmentDao;
import com.web.springbootwebmanage.dao.EmployeeDao;
import com.web.springbootwebmanage.pojo.Department;
import com.web.springbootwebmanage.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 {
    //调用dao层的代码;但是一般先走service再走dao,这里直调用
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;
    //1.查询所有的员工,返回列表页面
    //@GetMapping("/emps")
    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();
        //放在model请求域中
        model.addAttribute("emps",employees);
        //路径错误/emp/list 前端报错
        return "emp/list";
    }
    //删除
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
      employeeDao.delete(id);
     return "redirect:/emps";
    }
}

十、404页面

在这里插入图片描述

<body>
<div th:replace="~{commons/common::sidenav}"></div>
<div class="container-fluid">
	<div class="row">
		<!--侧边栏-->
		<!--插入组件:dashboard::sidebar       页面::位置-->
		<!--传递参数-->
		<div th:replace="~{commons/common::sidebar(active='main.html')}"></div>

		<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
			<h1>404页面没准备好,程序员太累啦!!!</h1>
		</main>
	</div>
</div>
</div>
</div>

十一、注销操作

common.html

<li class="nav-item text-nowrap">
   <a class="nav-link" th:href="@{/user/loginout}">退出注销</a>
</li>

LoginController2.java

 //注销
    @RequestMapping("/user/loginout")
    public String loginout(HttpSession session){
       //删除session
       session.invalidate();
       return "redirect:/index.html";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值