Table of contents
2. Project public field filling
1. Edit employee information
1.1 Demand Analysis
Click the edit button in the employee management list, jump to the edit page, and echo the employee data for modification.
Request URL:
http://localhost:8080/backend/page/member/add.hml?id=1519713809428660226
The edit page uses the add page. The difference is that the edit page needs to carry the passed parameter ID to modify the employee object.
1.2 Code writing
Implementation process
Before developing the code, you need to sort out the operation process and the execution process of the corresponding program:
- When the edit button is clicked, the page jumps to add.html and carries the parameter employee ID in the url
- Obtain the parameter employee ID in the url on the add.html page
- Send an ajax request, request the server, and submit the employee id parameter at the same time
- The server receives the request, queries the employee information according to the employee ID, and responds to the page with the employee information in the form of ison
- The page receives the ison data responded by the server, and echoes the employee information through VUE data binding
- Click the save button, send aiax request, and submit the employee information on the page to the server in the form of ison
- The server receives employee information, processes it, and responds to the page after completion
- After receiving the response information from the server, the page performs corresponding processing
backend code
EmployeeController
/**
* 根据ID查询员工信息
* @param id
* @return
*/
@GetMapping("/{id}")
public R<Employee> getById(@PathVariable Long id){
log.info("根据ID查询员工信息");
Employee employee = employeeService.getById(id);
return R.success(employee);
}
2. Project public field filling
2.1 Problem Analysis
When adding new employees, you need to set the fields such as time, creator, modification time, and modification person. These fields should also be set when editing employees. These public fields can use the public field filling function provided by MybatisPlus to avoid code duplication :
2.2 Code implementation
Implementation steps:
- Add the @TableField annotation to the attribute of the entity class to specify the automatic filling strategy
- Write a metadata object handler according to the framework, assign values to the same field, and implement the MetaObjectHandler interface
MyMetaObjecthandler.java
package com.itheima.reggie.common;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 自定义元数据对象处理器
*/
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {
/**
* 插入操作,自动填充
* @param metaObject
*/
@Override
public void insertFill(MetaObject metaObject) {
log.info("公共字段自动填充[insert]...");
log.info(metaObject.toString());
metaObject.setValue("createTime", LocalDateTime.now());
metaObject.setValue("updateTime",LocalDateTime.now());
metaObject.setValue("createUser", BaseContext.getCurrentId());
metaObject.setValue("updateUser", BaseContext.getCurrentId());
}
/**
* 更新操作,自动填充
* @param metaObject
*/
@Override
public void updateFill(MetaObject metaObject) {
log.info("公共字段自动填充[update]...");
log.info(metaObject.toString());
long id = Thread.currentThread().getId();
log.info("线程id为:{}",id);
metaObject.setValue("updateTime",LocalDateTime.now());
metaObject.setValue("updateUser",BaseContext.getCurrentId());
}
}
2.3 Perfect functions
The above code is still lacking. The inability to obtain the created and updated users causes the program to report an error. Using ThreadLocal can solve the problem of not being able to obtain the employee ID in the session.
When each Http request sent by the client, the corresponding server will allocate a new thread to process it. During the process, the methods of the following classes belong to one thread:
- LoginCheckFilter's doFilter method
- The update method of EmployeeController
- The updateFill method of MyMetaObjectHandler
The following code can be added to the above three methods respectively (to get the current thread ID):
long id = Thread.currentThread().getId();
log.info("线程id为:{}",id);
What is ThreadLocal?
ThreadLocal is not a Thread, but a local variable of Thread. When using ThreadLocal to maintain variables, ThreadLocal provides an independent copy of the variable for each thread that uses the variable, so each thread can change its own copy independently without affecting the corresponding copies of other threads. ThreadLocal provides a separate storage space for each thread, which has the effect of thread isolation. The corresponding value can only be obtained within the thread, and cannot be accessed outside the thread.
ThreadLocal common methods
public void set(Tvalue) : Set the value of the thread local variable of the current thread
public T get(): Return the value of the thread local variable corresponding to the current thread
We can obtain the current login user id in the doFilter method of LoainCheckFilter, and call the set method of ThreadLocal to set the value user ID of the thread local variable of the current thread, and then use the updateFill method of MyMetaObjectHandler to obtain the user ID
Specific implementation steps:
- Write the BaseContext tool class, based on the tool class encapsulated by ThreadLocal
- Call BaseContext in the doFilter method of LoginCheckFilter to set the id of the currently logged in user
- Call BaseContext in the method of MyMetaObjectHandler to get the id of the logged-in user
BaseContext.java
package com.itheima.reggie.common;
/**
* 基于ThreadLocal封装工具类,用户保存和获取当前登录用户id
*/
public class BaseContext {
private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
/**
* 设置值
* @param id
*/
public static void setCurrentId(Long id){
threadLocal.set(id);
}
/**
* 获取值
* @return
*/
public static Long getCurrentId(){
return threadLocal.get();
}
}
Add to the doFilter method of LoginCheckFilter.java :
Long empId = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
After the modification, the function after the test is the same as before, indicating that there is no problem.