🌻🌻目录
- 一、项目搭建
- 1.1 根据上节删掉不需要的
- 1.2 导入静态资源
- 1.3 创建实体
- 1.4 创建dao
- 二、首页实现
- 三、国际化
- 3.1 首页修改为中文显示
- 3.2 中英文切换显示
- 四、登录功能实现
- 4.1 登录功能实现
- 4.2 登录拦截器
一、项目搭建
准备阶段最终结构:
1.1 根据上节删掉不需要的
首先,我们搭建一个普通的SpringBoot项目,回顾一下HelloWorld程序!
导入依赖: pom.xml
<!--thymeleaf 我们都是基于 3.x 开发-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
根据上节,现在只留下面这些,是一个干净的空项目:
1.2 导入静态资源
1.3 创建实体
- 创建包
com.zql.pojo
,并分别创建实体Department.java
,Employee.java
Department.java
package com.zql.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author:Daniel
* @Version 1.0
* 部门表
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
Employee.java
package com.zql.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @Author:Daniel
* @Version 1.0
* 员工表
*/
@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;
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();
}
}
1.4 创建dao
- (因没有数据库表,所以直接这里写了,建议直接copy代码到你工程中)
- 创建包
com.zql.dao
,并分别创建DepartmentDao.java
,EmployeeDao.java
DepartmentDao.java
package com.zql.dao;
import com.zql.pojo.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.Map;
/**
* @Author:Daniel
* @Version 1.0
* 部门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);
}
}
EmployeeDao.java
package com.zql.dao;
import com.zql.pojo.Department;
import com.zql.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;
/**
* @Author:Daniel
* @Version 1.0
* 员工Dao
*/
@Repository
public class EmployeeDao {
//模拟数据库中的数据
private static Map<Integer, Employee> employees = null;
//员工所属的部门
@Autowired
private DepartmentDao departmentDao;
static {
employees = new HashMap<Integer,Employee>();//创建一个部门表
employees.put(101,new Employee(1001,"AA","A198247@qq.com",0,new Department(101,"教学部")));
employees.put(102,new Employee(1002,"AB","B198247@qq.com",1,new Department(102,"市场部")));
employees.put(103,new Employee(1003,"AC","C198247@qq.com",0,new Department(103,"教研部")));
employees.put(104,new Employee(1004,"AD","D198247@qq.com",1,new Department(104,"运营部")));
employees.put(105,new Employee(1005,"AE","E198247@qq.com",0,new Department(105,"后勤部")));
}
//主键自增
private static Integer initId = 1006;
//增加一个员工
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
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);
}
}
二、首页实现
首页配置:注意点,所有页面的静态资源都需要使用thymeleaf接管;@{ }
- 视图层
MyMvcConfig.java
package com.zql.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Author:Daniel
* @Version 1.0
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
- 修改页面
(2)
清除缓存,配置项目路径
#清除模板引擎缓存
spring.thymeleaf.cache=false
#修改配置项目路径,是url的一部分
server.servlet.context-path=/daniel
启动主启动类测试:http://localhost:8080/daniel/
三、国际化
3.1 首页修改为中文显示
前提:修改 IDEA 编码规则
- 在resources下面创建一个文件夹 i18n(国际化缩写,首尾字母,中间18个字母,类似得还有K8S)
- 创建 login.properties,login_zh_CN.properties,则自动生成如下所示,
(1)
(2)
(3)
(4)
结果自动生成:
全局搜索
MessageSourceProperties
类可以查看源码,而后在application.properties 中做如下配置
#我们配置文件得真实位置
spring.messages.basename=i18n.login
修改 index.html 页面
启动程序运行查看:
3.2 中英文切换显示
- 首页 index.html 添加链接
<a class="btn btn-sm" th:href="@{/index.html(1='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(1='en_US')}">English</a>
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>
<label class="sr-only">Username</label>
<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only">Password</label>
<input type="password" class="form-control" placeholder="Password" 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:value="#{login.btn}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index.html(1='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(1='en_US')}">English</a>
</form>
</body>
</html>
- 在包com.zql.config下面创建类
MyLocaleResolver.java
package com.zql.config;
import org.springframework.cglib.core.Local;
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;
/**
* @Author:Daniel
* @Version 1.0
*/
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("1");
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) {
}
}
- 添加到类 MyMvcConfig.java
//自定义得国家化组件就生效了!
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
重启测试:http://localhost:8080/daniel/
点击中文显示得:
点击 English 显示得:
(注:如果直接跳转其它页面一般是包导错了)
四、登录功能实现
4.1 登录功能实现
- 修改index.html 前端页面:
- 后端实现(在com.zql.controller下面创建
LoginController.java
)
package com.zql.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.jws.WebParam;
/**
* @Author:Daniel
* @Version 1.0
*/
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(
@RequestParam("username") String username,
@RequestParam("password") String password,
Model model){
if(!StringUtils.isEmpty(username) && "123".equals(password)){
return "redirect:/main.html";
}else{
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}
}
- 修改 MyMvcConfig.java 登录映射
4.前端 index.html 修改
测试:用户名随意输入,密码:123,登录不成功显示
登录成功显示(直接跳到 dashboard.html 页面)
4.2 登录拦截器
- 在 LoginController.java中修改
- 在 com.zql.config报下创建
LoginHandlerInterceptor.java
package com.zql.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Author:Daniel
* @Version 1.0
*/
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.java
//自定义得国家化组件就生效了!
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/css/*","/img/**","/js/**");
}
启动测试,被拦截
- 显示登录名
- 最终测试(登录成功显示):