当前位置:网站首页>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 :

image-20220617150553491

image-20220617150609264

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 :

  1. When you click the Edit button , The page jumps to add.html, And in url Carry parameters in [ staff id]
  2. stay add.html Page to obtain url Parameters in
  3. send out ajax request , Request server , At the same time, submit the employee id Parameters
  4. Server receives request , According to the staff id Query employee information , Send employee information to JSON Form response to the page
  5. The page receives the response from the server JSON data , adopt vue Data binding for employee information echo
  6. 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
  7. The server receives employee information , And process it , Respond to the page after completion
  8. 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

原网站

版权声明
本文为[xjhqre]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240916021290.html