完善登录功能
只有登录才能访问首页,使用过滤器或者拦截器实现
这里使用过滤器实现
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//强转一下,向下转型
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
//获取url
String requestUrl = httpServletRequest.getRequestURI();
//定义可以放行的请求url
String[] urls = {
"/employee/login",
"/employee/login",
"/backend/**",
"/front/**",
"/user/sendMsg",
"/user/login",
"/doc.html",
"/webjars/**",
"/swagger-resources",
"/v2/api-docs"
};
//判断这个路径是否直接放行
Boolean cheakUrl = checkUrl(urls, requestUrl);
//不需要处理直接放行
if (cheakUrl){
log.info("匹配到了{}",requestUrl);
filterChain.doFilter(httpServletRequest, httpServletResponse);
//放行完了直接结束就行
return;
}
//判断用户已经登陆可以放行(PC后台版)
if (redisTemplate.opsForValue().get("employee")!= null){
log.info("后台用户已登录");
filterChain.doFilter(httpServletRequest, httpServletResponse);
//获取当前新增操作人员的id
Long empId= (Long) redisTemplate.opsForValue().get("employee");
//存入LocalThread
BaseContext.setCurrentId(empId);
//放行完了直接结束就行
return;
}//判断用户已经登陆可以放行(移动端前台版)
if (redisTemplate.opsForValue().get("user") != null){
log.info("前台用户已登录");
filterChain.doFilter(httpServletRequest, httpServletResponse);
//获取当前新增操作人员的id
Long userId= (Long) redisTemplate.opsForValue().get("user");
//存入LocalThread
BaseContext.setCurrentId(userId);
//放行完了直接结束就行
return;
}
//没有登陆,跳转到登陆页面
//前端有拦截器完成跳转页面,所以我们用输入流写个json来触发前端的拦截器完成跳转
httpServletResponse.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
log.info("拦截,交由前端跳转");
return;
}
/**
* @param urls 之前定义的可以放行的url地址数组
* @param requestUrl 客户端打来的url地址
* @return 返回值boolean值,true的话就是我们可以放行的目标
*/
public boolean checkUrl(String []urls,String requestUrl){
Boolean matchUrlResult = true;
//遍历的同时调用PATH_MATCHER来对路径进行匹配
for (String currUrl : urls) {
matchUrlResult=PATH_MATCHER.match(currUrl, requestUrl);
if (matchUrlResult){
//匹配到了可以放行的路径,直接放行
return true;
}
}
//否则就是没有匹配到,不予放行
return false;
}
新增员工
if (this.actionType === 'add') {
const params = {
...this.ruleForm,
sex: this.ruleForm.sex === '女' ? '0' : '1'
}
addEmployee(params).then(res => {
if (res.code === 1) {
this.$message.success('员工添加成功!')
if (!st) {
this.goBack()
} else {
this.ruleForm = {
username: '',
'name': '',
'phone': '',
// 'password': '',
// 'rePassword': '',/
'sex': '男',
'idNumber': ''
}
}
} else {
this.$message.error(res.msg || '操作失败')
}
}).catch(err => {
this.$message.error('请求出错了:' + err)
})
@PostMapping("")
public Result addEmployee(HttpServletRequest httpServletRequest,@RequestBody Employee employee) {
//设置默认密码,顺手加密了
employee.setPassword(MD5Util.getMD5("123456"));
//设置修改时间
employee.setCreateTime(LocalDateTime.now());
employee.setUpdateTime(LocalDateTime.now());
//账户默认状态0
employee.setStatus(0);
//获取当前新增操作人员的id
Long empId= (Long) httpServletRequest.getSession().getAttribute("employee");
employee.setCreateUser(empId);
employee.setUpdateUser(empId);
//MP自动CRUD的功能,封装好了save方法
employeeService.save(employee);
return Result.success("插入成功");
}
全局异常处理器
@ExceptionHandler({SQLIntegrityConstraintViolationException.class,NullPointerException.class})
public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
log.error(exception.getMessage());
//这里判断出来是添加员工时出现的异常
if (exception.getMessage().contains("Duplicate entry")){
//exception对象分割,同时存储
String []splitErrorMessage=exception.getMessage().split(" ");
/**
* splitErrorMessage数组内存的信息
* Duplicate entry '新增的账号' for key 'idx_username'
* 下标位2是新增账号,下标位5是关联的字段名
*/
String errorMessage = "这个账号重复了" + splitErrorMessage[2];
return Result.error(errorMessage);
}
return Result.error("失败了");
}
员工信息分页查询
table组件
mybaits plus分页插件,配置类
package com.cc.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MybatisPlus分页插件配置类
*/
@Configuration
@MapperScan("com.cc.mapper")
public class MybatisPlusConfig {
//分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
@GetMapping("/page")
public Result<Page> page(int page, int pageSize,String name){
//分页构造器,Page(第几页, 查几条)
Page pageInfo = new Page(page, pageSize);
//查询构造器
LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
//过滤条件.like(什么条件下启用模糊查询,模糊查询字段,被模糊插叙的名称)
lambdaQueryWrapper.like(!StringUtils.isEmpty(name), Employee::getName, name);
//添加排序
lambdaQueryWrapper.orderByDesc(Employee::getCreateTime);
//查询分页、自动更新
employeeService.page(pageInfo, lambdaQueryWrapper);
//返回查询结果
return Result.success(pageInfo);
}
显示账号正常异常
<el-table-column label="账号状态">
<template slot-scope="scope">
{{ String(scope.row.status) === '0' ? '已禁用' : '正常' }}
</template>
</el-table-column>
启用、禁用员工账号
@PutMapping()
public Result<Employee> update(HttpServletRequest httpServletRequest,@RequestBody Employee employee){
System.out.println("更新"+Thread.currentThread().getName());
//从Request作用域中拿到员工ID
Long empId = (Long) httpServletRequest.getSession().getAttribute("employee");
//拿新的状态值
employee.setStatus(employee.getStatus());
//更新时间
employee.setUpdateTime(LocalDateTime.now());
//更新处理人id
employee.setUpdateUser(empId);
employeeService.updateById(employee);
return Result.success(employee);
}
精度问题出错
使用对象映射器
Java对象和json对象互相转换
public JacksonObjectMapper() {
super();
//收到未知属性时不报异常
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
//反序列化时,属性不存在的兼容处理
this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
SimpleModule simpleModule = new SimpleModule()
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
.addSerializer(BigInteger.class, ToStringSerializer.instance)
.addSerializer(Long.class, ToStringSerializer.instance)
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//注册功能模块 例如,可以添加自定义序列化器和反序列化器
this.registerModule(simpleModule);
}
编辑员工信息
传入要改的ID
//获取url地址上面的参数
function requestUrlParam(argname){
var url = location.href //获取完整的请求url路径
var arrStr = url.substring(url.indexOf("?")+1).split("&")
for(var i =0;i<arrStr.length;i++)
{
var loc = arrStr[i].indexOf(argname+"=")
if(loc!=-1){
return arrStr[i].replace(argname+"=","").replace("?","")
}
}
return ""
}
先查到ID对应的员工
@GetMapping("/{id}")
public Result<Employee> getEmployee(@PathVariable Long id){
Employee employee = employeeService.getById(id);
if (employee!=null){
return Result.success(employee);
}
return Result.error("没有查到员工信息");
}
再修改