新增员工

后台系统中可以管理员工信息,通过新增员工来添加后台系统用户,点击【添加员工】按钮跳转到新增页面。

将录入的员工数据插入到employee表,需注意,employee表中的username字段加入了唯一约束,因为username是员工的登录账号,必须唯一。

(1)页面发送ajax请求,将新增员工页面中输入的数据以JSON的形式提交到服务端

(2)服务端Controller接收页面提交的数据并调用Service将数据进行保存

(3)Service调用Mapper操作数据库,保存数据

复制代码
    @PostMapping()
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee){
            log.info("新增员工, 员工信息:{}", employee.toString());
            //设置初始密码123456,需要进行md5加密处理
            employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            employee.setCreateTime(LocalDateTime.now());
            employee.setUpdateTime(LocalDateTime.now());
            //获得当前你登录用户的id
            Long empId = (Long) request.getSession().getAttribute("employee");
            employee.setCreateUser(empId);
            employee.setUpdateUser(empId);
            employeeService.save(employee);

            return R.success("新增员工成功");
    }
复制代码

测试后程序存在的问题:由于employee表中对username字段进行了唯一性约束。因此当username重复提交到数据库时,程序会报异常。

 

需要进行异常捕获,两种方法

1、在controller中加入try、catch进行异常捕获

2、使用异常处理器进行全局异常捕获。

使用第二种方法:

复制代码
package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */

//拦截类上加了注解@RestController的Controller、拦截一般controller
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //输出异常信息
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

}
复制代码

 

posted @   佛系粥米  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示