当前位置:网站首页>瑞吉外卖项目(三)员工管理业务开发
瑞吉外卖项目(三)员工管理业务开发
2022-06-11 16:02:00 【缘昔】
瑞吉外卖项目
第五章 员工管理业务开发
新增员工
需求分析
后台系统中可以管理员工信息,通过新增员工来添加后台系统用户,点击【添加员工】进行页面跳转
存在这样一个请求,传递前端新增员工数据
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yYqK2ILS-1654739732497)(C:\Users\12044\Documents\实战项目\瑞吉外卖项目\瑞吉-image-12.png)]](/img/6a/c363161e0117f99cd5609ed6f95819.png)
数据模型
新增员工,其实就是将我们新增页面录入的员工数据插入到employee表。需要注意,employee表中对于username字段加入了唯一约束,因此username不可以重复
employee表中的status字段已经设置了默认值为1,表示状态正常
代码开发
执行过程:
- 页面发送ajax请求,将新增员工页面中输入的数据以json的形式提交到服务端
- 服务端Controller接收页面提交的数据并调用Service进行保存
- Service调用Mapper操作数据库,插入数据
/** * 新增员工 * @param employee * @return */
@PostMapping
public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
log.info("新增员工,员工信息: {}",employee.toString());
//设置初始密码,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属性设置了唯一约束,因此数据库会出现报错问题:
Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry ‘zhangsan’ for key ‘employee.idx_username’
为了知道异常信息,我们需要进行异常捕获处理:
- 在Controller方法中加入try、catch进行异常捕获
- 使用异常处理器进行全局异常捕获
/** * 全局异常处理 */
@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("未知错误");
}
}
员工信息分页查询
需求分析
系统员工很多时候,如果在同一个页面全部展示出来的话,会显得比较乱,不便于查看,所以一般系统中都会以分页的方式来展示列表数据
代码开发
程序执行流程:
- 页面发送Ajax请求,将分页查询参数(page,pageSize,name)提交到服务端
- 服务端Controller接受页面提交的数据,并调用Service层查询数据
- Service调用Mapper操作数据库,查询分页数据
- Controller将查询到的分页数据响应给页面
- 页面接收到分页数据并通过ElementUI的Table组件展示到页面上
配置MybatisPlus分页插件:
/** * 配置MP的分页插件 */
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
在Controller层调用分页插件
/** * 员工信息分页查询 * @param page * @param pageSize * @param name * @return */
@GetMapping("/page")
public R<Page<Employee>> page(int page,int pageSize,String name){
log.info("page={},pageSize={},name={}",page,pageSize,name);
//构造分页构造器
Page<Employee> pageInfo = new Page<>(page, pageSize);
//条件构造器
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
//添加排序条件
queryWrapper.orderByDesc(Employee::getUpdateTime);
//执行查询
employeeService.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
功能测试
分页功能正常运行
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2CZAFrmX-1654739732497)(C:\Users\12044\Documents\实战项目\瑞吉外卖项目\瑞吉-image-13.png)]](/img/97/346e5289204e9f1f9bc8ad20f0ba88.png)
启用/禁用员工账号
需求分析
在员工管理列表页面,可以对某个员工账号进行启用或者禁用操作。账号禁用的员工不能登陆系统,启用后的员工可以正常登录。
需要注意只有管理员(admin)可以对其他普通用户进行启用、禁用操作,所以普通用户登陆系统后启用禁用按钮不显示
代码开发
存在一个/employee的put方式的请求
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M7lRp8q2-1654739732498)(C:\Users\12044\Documents\实战项目\瑞吉外卖项目\瑞吉-image-14.png)]](https://img-blog.csdnimg.cn/77c9e74b334242b082b215c44bfbaf2e.png)
/** * 根据id修改员工信息 * @param employee * @return */
@PutMapping
public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
log.info(employee.toString());
Long emId = (Long) request.getSession().getAttribute("employee");
employee.setUpdateTime(LocalDateTime.now());
employee.setUpdateUser(emId);
employeeService.updateById(employee);
return R.success("员工信息修改成功");
}
功能测试
会发现存在一个问题
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gftSc2ID-1654739732498)(C:\Users\12044\Documents\实战项目\瑞吉外卖项目\瑞吉-image-15.png)]](/img/e6/359735d60c85da72359840cf9cc1dc.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-n0zth7xp-1654739732499)(C:\Users\12044\Documents\实战项目\瑞吉外卖项目\瑞吉-image-16.png)]](/img/c8/f9540f77172c23cf6e1e2df2dfc645.png)
通过观察控制台输出的sql发送的页面传递过来的员工id的值和数据库中张三的id值不一致,是因为分页查询时服务端响应给页面的数据中id的值为19位数字,类型为long
而页面中js处理long型数据只能精确到前16位,所以最终通过Ajax请求提交给服务端的时候id改变了
存在精度问题
代码修复
由于js对于long型数据存在精度丢失,导致提交给后端的id和数据库中的id不一致,
因此我们可以在服务端给页面响应json数据时进行处理,将long型数据统一转换为String字符串
具体实现步骤:
提供对象转换器JacksonObjectMapper,基于Jackson进行Java对象到jsob数据的转换
/** * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象] * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON] */ public class JacksonObjectMapper extends ObjectMapper { public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss"; 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); } }在WebMvcConfig配置类中扩展SpringMvc的消息转换器,在消息转换器中使用使用提供的对象转换器进行Java对象到Json数据的转换
/** * 扩展mvc框架的消息转换器 * @param converters */ @Override protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) { log.info("扩展消息转换器"); //创建消息转换器 MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); //设置对象转换器,底层使用Jackson将java对象转换成json messageConverter.setObjectMapper(new JacksonObjectMapper()); //将上面的消息转换器对象追加到mvc框架的转换器中 converters.add(0,messageConverter); }
编辑员工信息
需求分析
在员工管理列表页面点击编辑按钮,跳转到编辑页面,在编辑页面回显员工信息并进行修改,最后点击保存按钮完成编辑操作
代码开发
执行流程:
- 点击编辑按钮时,页面跳转到add.html,并在url中携带参数【员工id】
- 在add.html页面获取url中的参数
- 发送ajax请求,请求服务端,同时提交员工id参数
- 服务端接受请求,根据员工id查询员工信息,将员工信息以json形式响应给页面
- 页面接收服务端响应的json数据,通过Vue的数据绑定进行员工信息回显
- 点击保存按钮,发送Ajax请求,将页面中的员工信息以Json方式提交给服务端
- 服务端接收员工信息,并进行处理,完成后给页面响应
- 页面接收到服务端相应信息后进行相应处理
/** * 根据id修改员工信息 * @param employee * @return */
@PutMapping
public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
log.info(employee.toString());
Long emId = (Long) request.getSession().getAttribute("employee");
employee.setUpdateTime(LocalDateTime.now());
employee.setUpdateUser(emId);
employeeService.updateById(employee);
return R.success("员工信息修改成功");
}
/** * 根据id查询员工信息 * @param id * @return */
@GetMapping("/{id}")
public R<Employee> getById(@PathVariable Long id){
log.info("根据id查询员工信息");
Employee employee = employeeService.getById(id);
if (employee!=null){
return R.success(employee);
}
return R.error("没有查询到对应员工信息");
}
功能测试
修改成功
边栏推荐
- laravel 8 使用passport 进行Auth验证及颁发token
- Laravel 8 uses passport for auth authentication and token issuance
- After reading the book reading methods
- 3000 words to teach you how to use mot
- postgresql创建数据库
- [Yugong series] June 2022 Net architecture class 077 distributed middleware schedulemaster loading assembly timing task
- Open the door of the hybrid cloud market, Lenovo xcloud's way to break the situation
- How to optimize the performance of compose? Find the answer through "underlying principles" | developers say · dtalk
- Golang map basic operations
- With a lamp inserted in the nostril, the IQ has risen and become popular in Silicon Valley. 30000 yuan is enough
猜你喜欢

书籍《阅读的方法》读后感

Dapr mind map

Nat Commun|語言模型可以學習複雜的分子分布

Code farming essential SQL tuning (Part 2)

Laravel 2020-01-01t00:00:00.000000z date conversion

Kill the swagger UI. This artifact is better and more efficient!

Nat Commun|语言模型可以学习复杂的分子分布

What happened to the frequent disconnection of the computer at home

Toolbar details of user interface - autorunner automated test tool

基于FPGA的VGA协议实现
随机推荐
laravel 8 使用passport 进行Auth验证及颁发token
What happened to the frequent disconnection of the computer at home
leetcode684. 冗余连接(中等)
Nielseniq announces appointment of Tracey Massey as chief operating officer
完整的测试流程【杭州多测师】【杭州多测师_王sir】
Production problem troubleshooting reference
Factory calibrated gravity: working principle and installation position of carbon monoxide sensor, calibration standard description
Go language - array
Nat Commun|語言模型可以學習複雜的分子分布
How to optimize the performance of compose? Find the answer through "underlying principles" | developers say · dtalk
整了20张高清数据分析全知识地图,强烈建议收藏!
再聊数据中心网络
Nat Common | le Modèle linguistique peut apprendre des distributions moléculaires complexes
Transfer learning
DHCP protocol instantiation analysis
Heartless sword English Chinese bilingual poem 001 Spring outing
Laravel 2020-01-01t00:00:00.000000z date conversion
Aaai2022 latest "time series data processing" report, 127 pages of PPT describing time series data processing and medical application progress
电脑下面的任务栏怎么显示打开的程序
[Yugong series] June 2022 Net architecture class 077 distributed middleware schedulemaster loading assembly timing task