首页 > 其他分享 >新增员工

新增员工

时间:2023-02-24 16:01:58浏览次数:33  
标签:新增 springframework 员工 org employee import 异常

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

将录入的员工数据插入到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("未知错误");
    }

}

 

标签:新增,springframework,员工,org,employee,import,异常
From: https://www.cnblogs.com/fxzm/p/17145729.html

相关文章