自定义配置以及Thymeleaf模板实现员工管理系统

我们这里就不在设计数据库,在类中设计模拟数据库即可。

首页配置:

1.注意点,在这里所有页面的静态资源都需要使用thymeleaf接管;
2.url:@{}

国际化

首先分析源码
源码分析
在这里插入图片描述
在这里插入图片描述

  • 1.我们需要配置i18n文件
  • 2.我们如果需要在项目中进行按钮自动切换,我们需要自定义一个组件LocaleResolver
  • 3.记得将自己写的组件配置到spring容器@Bean
  • 4.#{ }

先创建文件,文件内的properties文件创建了上层文件会自动生成,
在这里插入图片描述
国际化的源码可以看出可以设置的参数属性
在这里插入图片描述
在Bundle中可以进行可视化的编辑
在这里插入图片描述

index.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>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" th:text="#{login.tip}">Please sign in</h1>
			<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
			<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
			<div class="checkbox mb-3">
				<label>
          <input type="checkbox" value="remember-me"> [[#{login.remember}]]
        </label>
			</div>
			<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>
			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
			<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
			<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
		</form>
	</body>

</html>

自定义国际化解析器(LocaleResolver 的方法名必须为localeResolver,否则会报错)

public class MyLocalResolver implements LocaleResolver {
    
    

    //解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
    
    
        //获取请求中的语言参数:请求里面带了l的都会走这个请求
        String language = httpServletRequest.getParameter("l");//解析参数这个l来自th:href="@{/index.html(l='zh_CN')}"从而实现解析
        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) {
    
    

    }
}

在MyMvcConfig中注册

    //自定义的国际化组件就生效了
    @Bean //将组件注册在容器
    public LocaleResolver localeResolver(){
    
    
        return new MyLocalResolver();
    }

实现效果
在这里插入图片描述

登录功能的实现

对首页的改动比如用户名或密码错误的提示等等

<!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" th:action="@{/user/login}">
			<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
			<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
			<!--如果msg 为空,则不显示消息-->
			<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
			<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
			<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">[[#{login.btn}]]</button>
			<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
			<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
			<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
		</form>
	</body>
</html>

登录功能

@Controller
public class LoginController {
    
    

    @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.setAttribute("loginUser",username);
            System.out.println("-----------");
            return "redirect:/main.html";

        }else{
    
    
            //告诉用户,你登录失败了
            model.addAttribute("msg","用户名或者密码错误!");
            return "index";
        }
    }
}

在MyMvcConfig定制页面的跳转

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        //浏览器发送 /main.html 请求来到dashboard.html页面
        registry.addViewController("/main.html").setViewName("dashboard");
    }

实现效果

故意输入错误密码
在这里插入图片描述
登录成功后的页面
在这里插入图片描述

登录拦截器

实现拦截器

/**
 * @author acoffee
 * @create 2021-08-05 12:53
 */
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;
        }
    }
}

注册拦截器(MyMvcConfig类中)

    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        //将静态资源排除在拦截之外 ("/index.html","/","/user/login","/css/*","/js/**","/img/**")
        //"/**":意思是所有请求都拦截,excludePathPatterns:除了那些文件不拦截
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/*","/js/**","/img/**");
    }

员工列表展示

1.提取公共页面

1.th:fragment="sidebar"
2. th:replace="~{commons /commons : :topbar}"
3.如果要传递参数,可以直接使用()传参,接收判断即可!│

2.列表循环展示

<div class="container-fluid">
    <div class="row">
        <div th:insert="~{/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>Section title</h2>
            <div class="table-responsive">
                <table class="table table-striped table-sm">
                    <thead>
                    <tr>
                        <th>id</th>
                        <th>lastName</th>
                        <th>email</th>
                        <th>gender</th>
                        <th>department</th>
                        <th>birth</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr th:each="emp:${emps}">
                        <td th:text="${emp.getId()}"></td>
                        <td th:text="${emp.getLastName()}"></td>
                        <td th:text="${emp.getEmail()}"></td>
                        <td th:text="${emp.getGender()==0?'':''}"></td>
                        <td th:text="${emp.department.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>
            </div>
        </main>
    </div>
</div>

在EmployeeController中加入添加员工的方法

    @PostMapping("/emp")
    public String addEmp(Employee employee){
    
    
        System.out.println("save→"+employee);
        employeeDao.save(employee);//调用底层业务方法保存员工信息
        //添加的组件 forward
        return "redirect:/emps";
    }

实现效果
在这里插入图片描述

添加员工

添加页面我们直接用list.html改一下就可以了因为侧边栏和顶部栏是一样的


<div class="container-fluid">
    <div class="row">
        <div th:insert="~{/commons/common::sidebar(active='list.html')}"></div>
        <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="acoffee">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" placeholder="[email protected]">
                </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-labe1"></label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="gender" value="e">
                        <label class="form-check-labe1"></label>
                    </div>
                </div>
                <div class="form-group">
                    <label>department</label>
                    <!--我们在controller接收的是一个Employee,所以我们需要提交的是其中的一个属性-->
                    <select class="form-control" name="department.id">
                        <option th:each="dept:${departments}" th:text="${dept.getDepartmentName()}"
                                th:value="${dept.getId()}">
                        </option>
                    </select>
                </div>
                <div elass="form-group">
                    <label>Birth</label>
                    <input type="text" name="birth" class="form-control" placeholder="acoffee"></div>
                <button type="submit" class="btn btn-primary">添加</button>
            </form>
        </main>
    </div>
</div>

时间格式的问题

在这里插入图片描述
当我们不去配置配置文件直接去添加2012-1-1这种时间格式,是会报以下错误的,因为当我们不去配置时间格式的时候它会默认2012/1/1这种斜杠的格式才是正确的,所以要么我们去配置文件中配置,要么我们就是用这种默认的时间格式
在这里插入图片描述
从源码中我们也可以看出
在这里插入图片描述

修改功能

update.html表单

<div class="container-fluid">
    <div class="row">
        <div th:insert="~{/commons/common::sidebar(active='list.html')}"></div>
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">

            <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="acoffee">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input th:value="${emp.getEmail()}" type="email" name="email" class="form-control" placeholder="[email protected]">

                </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-labe1"></label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input th:checked="${emp.getGender()==0}" class="form-check-input" type="radio" name="gender" value="e">
                        <label class="form-check-labe1"></label>
                    </div>
                </div>
                <div class="form-group">
                    <label>department</label>
                    <!--我们在controller接收的是一个Employee,所以我们需要提交的是其中的一个属性-->
                    <select class="form-control" name="department.id">
                        <option th:selected="${dept.getId()==emp.getDepartment().getId()}" th:each="dept:${departments}" th:text="${dept.getDepartmentName()}"
                                th:value="${dept.getId()}">
                        </option>
                    </select>
                </div>
                <div elass="form-group">
                    <label>Birth</label>
                    <input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm')}" type="text" name="birth" class="form-control" placeholder="acoffee">
                </div>
                <button type="submit" class="btn btn-primary">修改</button>
            </form>


        </main>
    </div>
</div>

添加功能

    //去员工的修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
    
    
        //查出原来的数据
        Employee employee = employeeDao.getEmployeeById(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";
    }

实现效果
在这里插入图片描述

删除功能

在list.html表单中添加删除跳转

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

删除功能

    //删除员工
    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id")int id){
    
    
        employeeDao.delete(id);
        return "redirect:/emps";
    }

功能实现
在这里插入图片描述

404处理

直接在templates中创建一个error文件夹将404的页面放入其中即可,springBoot会自动帮我们去找,其他异常同理,如500等
在这里插入图片描述
实现效果
在这里插入图片描述

注销功能

每个页面都有注销功能,所以在这个功能我们加载commons.html表单中

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

注销功能在loginController中

    //注销功能
    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
    
    
        session.invalidate();
        return "redirect:index.html";
    }

猜你喜欢

转载自blog.csdn.net/weixin_44742328/article/details/119411950