当前位置:网站首页>3. addition, deletion, modification and query of employees
3. addition, deletion, modification and query of employees
2022-06-24 10:15:00 【xjhqre】
Addition, deletion, modification and query of employees
1、 New employees
1.1、 Save employee method
establish save Method , route :com/itheima/reggie/controller/EmployeeController.java
@PostMapping
public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
log.info(" New employees , Employee information :{}", employee.toString());
// Set the initial password 123456, Need to carry out md5 Encryption processing
employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
employee.setCreateTime(LocalDateTime.now());
employee.setUpdateTime(LocalDateTime.now());
// Get the current login user's id
Long empId = (Long) request.getSession().getAttribute("employee");
// Set the name of the person who added the employee information id
employee.setCreateUser(empId);
employee.setUpdateUser(empId);
// Store employee information in the database
employeeService.save(employee);
return R.success(" New employees ");
}
1.2、 Global exception
Create a global exception capture class GlobalExceptionHandler, Catch the exception of the class annotated with the specified annotation
package com.itheima.reggie.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.SQLIntegrityConstraintViolationException;
/** * @Author: xjhqre * @DateTime: 2022/6/17 14:17 */
// It's marked RestController and Controller Annotated classes to intercept
@Slf4j
@RestControllerAdvice(annotations = {
RestController.class, Controller.class})
public class GlobalExceptionHandler {
@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] + " Already exists ";
return R.error(msg);
}
return R.error(" Unknown error ");
}
}
2、 Paging query of employee list
2.1、 To configure mybatis-plus Pagination plug-in for
stay config Create under directory MybatisPlusConfig
package com.itheima.reggie.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** * @Author: xjhqre * @DateTime: 2022/6/17 14:45 */
@Configuration
public class MybatisPlusConfig {
/** * Configure paging plug-ins */
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
2.2 Query method writing
establish page Method , route :com/itheima/reggie/controller/EmployeeController.java
// Query employee information by page
@GetMapping("/page")
public R<Page<Employee>> page(int page, int pageSize, String name) {
log.info("page = {}, pageSize = {}, name = {}", page, pageSize, name);
// Construct a paging constructor
Page<Employee> pageInfo = new Page<>(page, pageSize);
// Construct condition constructors
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
// Add filter conditions
queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
// Add sorting criteria
queryWrapper.orderByDesc(Employee::getUpdateTime);
// Execute the query
employeeService.page(pageInfo, queryWrapper);
return R.success(pageInfo);
}
2.3 Test paging
If you want to test the paging button function , You can add multiple pieces of data or modify the display quantity of each page
To modify the display quantity per page, you can modify the front end list.html file , route :backend/page/member/list.html
Modify the following two values :


3、 Enable / Disable employee account
When querying the employee list , The back end will send the information to each employee in the front end , However, due to the id The attribute is Long Type and length exceeds js The maximum length that can be handled , Results in a loss of accuracy .
resolvent :
The custom message converter replaces the default message converter , In the custom Converter Long Type into String Type is sent to the front end .
3.1 To write JacksonObjectMapper class
stay common Create under directory JacksonObjectMapper.
package com.itheima.reggie.common;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
/** * Object mapper : be based on jackson take Java Object to json, Or will json To Java object * take JSON It can be interpreted as Java The process of an object is called [ from JSON Deserialization Java object ] * from Java Object to generate JSON The process is called [ serialize Java Object to 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();
// No exception is reported when an unknown attribute is received
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
// When deserializing , Property does not exist
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)));
// Registration function module for example , You can add custom serializers and deserializers
this.registerModule(simpleModule);
}
}
3.2、 Expand Spring MVC Message converter for
stay WebMvcConfig Rewriting in extendMessageConverters Method
/** * Expand mvc Message converter of framework * @param converters */
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info(" Extended message converter ...");
// Create a message repeater object
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
// Set the object circulator , Bottom use Jackson take java Object to json
messageConverter.setObjectMapper(new JacksonObjectMapper());
// Append the above message converter object to mvc In the converter collection of the framework
converters.add(0, messageConverter);
}
3.3 Write update methods
stay EmployeeController Created in update Method
No changes are seen in the code status, Because the value is passed in from the front end , It has been encapsulated in the formal parameter employee in
/** * Update employee information * @param request * @param employee * @return */
@PutMapping
public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
Long empId = (Long) request.getSession().getAttribute("employee");
employee.setUpdateUser(empId);
employee.setUpdateTime(LocalDateTime.now());
employeeService.updateById(employee);
return R.success(" Employee information modified successfully ");
}
4、 Edit employee information
Process description :
- When you click the Edit button , The page jumps to add.html, And in url Carry parameters in [ staff id]
- stay add.html Page to obtain url Parameters in
- send out ajax request , Request server , At the same time, submit the employee id Parameters
- Server receives request , According to the staff id Query employee information , Send employee information to JSON Form response to the page
- The page receives the response from the server JSON data , adopt vue Data binding for employee information echo
- Click the save button , send out ajax request , Change the employee information in the page to JSON Submit to the server , It's called update Method
- The server receives employee information , And process it , Respond to the page after completion
- The page will respond after receiving the server response information
add.html The page is a public page , Adding and editing employees are operated on this page
4.1 How to create echo data
stay EmployeeController Class getById Method
/** * according to id Query employee information * @param id * @return */
@GetMapping("/{id}")
public R<Employee> getById(@PathVariable(value = "id") Long id) {
log.info(" according to id Query employee information ...");
Employee employee = employeeService.getById(id);
if (employee != null) {
return R.success(employee);
}
return R.error(" No corresponding employee information is found ");
}
4.2 Test and modify employee information
边栏推荐
- 消息队列的作用
- 时尚的弹出模态登录注册窗口
- 大中型企业如何构建自己的监控体系
- SQL Sever关于like操作符(包括字段数据自动填充空格问题)
- Development of anti fleeing marketing software for health products
- 411 stack and queue (20. valid parentheses, 1047. delete all adjacent duplicates in the string, 150. inverse Polish expression evaluation, 239. sliding window maximum, 347. the first k high-frequency
- 分布式 | 如何与 DBLE 进行“秘密通话”
- Network of test and development - Common Service Protocols
- PHP encapsulates a file upload class (supports single file and multiple file uploads)
- 上升的气泡canvas破碎动画js特效
猜你喜欢

二叉树第一部分

leetCode-498: 對角線遍曆

Wechat applet learning to achieve list rendering and conditional rendering

TP5 using post to receive array data times variable type error: solution to array error

canvas管道动画js特效

p5.js实现的炫酷交互式动画js特效

利用pandas读取SQL Sever数据表

How to improve the efficiency of network infrastructure troubleshooting and bid farewell to data blackouts?

整理接口性能优化技巧,干掉慢代码

SSH Remote Password free login
随机推荐
美国电子烟巨头 Juul 遭遇灭顶之灾,所有产品强制下架
tf.contrib.layers.batch_norm
MYSQL数据高级
MySQL data advanced
Producer / consumer model
Open Oracle server under Linux to allow remote connection
物联网?快来看 Arduino 上云啦
Observer mode
2022-06-23:给定一个非负数组,任意选择数字,使累加和最大且为7的倍数,返回最大累加和。 n比较大,10的5次方。 来自美团。3.26笔试。
Record the range of data that MySQL update will lock
tf.errors
微信小程序rich-text图片宽高自适应的方法介绍(rich-text富文本)
dedecms模板文件讲解以及首页标签替换
Operator details
Cicflowmeter source code analysis and modification to meet requirements
学习使用phpstripslashe函数去除反斜杠
El table Click to add row style
np.float32()
Jcim | AI based protein structure prediction in drug discovery: impacts and challenges
Which of the top ten securities companies has the lowest Commission and is the safest and most reliable? Do you know anything