当前位置:网站首页>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
边栏推荐
- 植物生长h5动画js特效
- Getting user information for applet learning (getuserprofile and getUserInfo)
- leetCode-面试题 01.05: 一次编辑
- PHP uses recursive and non recursive methods to create multi-level folders
- JS proxy mode
- leetCode-223: 矩形面积
- Queue queue
- Basic operations on binary tree
- Groovy obtains Jenkins credentials through withcredentials
- dedecms模板文件讲解以及首页标签替换
猜你喜欢

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

Producer / consumer model

411-栈和队列(20. 有效的括号、1047. 删除字符串中的所有相邻重复项、150. 逆波兰表达式求值、239. 滑动窗口最大值、347. 前 K 个高频元素)

机器学习——感知机及K近邻

5.菜品管理业务开发

Impdp leading schema message ora-31625 exception handling

1.项目环境搭建

Arbre binaire partie 1

CVPR 2022 Oral | 英伟达提出自适应token的高效视觉Transformer网络A-ViT,不重要的token可以提前停止计算

leetCode-2221: 数组的三角和
随机推荐
415 binary tree (144. preorder traversal of binary tree, 145. postorder traversal of binary tree, 94. inorder traversal of binary tree)
leetCode-498: 對角線遍曆
Jcim | AI based protein structure prediction in drug discovery: impacts and challenges
Programming questions (continuously updated)
植物生长h5动画js特效
MySQL data advanced
PostgreSQL DBA quick start - source compilation and installation
Producer / consumer model
Machine learning perceptron and k-nearest neighbor
Geogebra instance clock
形状变化loader加载jsjs特效代码
Groovy obtains Jenkins credentials through withcredentials
Regular matching mailbox
Array seamless scrolling demo
Machine learning - principal component analysis (PCA)
Internet of things? Come and see Arduino on the cloud
canvas掉落的小球重力js特效动画
Symbol. Iterator iterator
How large and medium-sized enterprises build their own monitoring system
Dragging El table sortablejs