


How to use Java to implement employee information management system functions?
1. Paging query of employee information
1. Requirements analysis
When more and more users in the system display incomplete pages, we need to display employees’ information through paging. Information:
2. Code development
Before developing the code, you need to clarify the execution process and business logic of the program:
The page sends an Ajax request and submits the paging query parameters (page, pagesize, name) to the server. The server
Controller receives the data submitted by the page and calls the query data
Service calls Mapper to operate the database and query paging data
Controller responds to the page with the queried paging data
The page receives the paging data and displays it on the page through the Table component of ElementUI
In fact, the paging parameters of the page are through JSON The format of the value is passed to the backend, but why is it spliced in this way of question marks in the picture? The reason is that the front end intercepts the request and then resplices the result (the front-end code will not be described again).
Configure paging plug-in
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; /** * 配置Mybatis-plus分页插件 * @author jektong * @date 2022年05月01日 0:08 */ @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); return mybatisPlusInterceptor; } }
Controller layer
/** * 员工信息分页查询 * * @param page 当前页 * @param pageSize 页码 * @param name 关键字查询 * @return */ @GetMapping("/page") public R<Page> page(int page, int pageSize, String name) { log.info("page={},pageSize={},name={}", page, pageSize, name); // 构造分页构造器 Page pageInfo = new Page(page, pageSize); // 构造条件 LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper(); queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name).or() .like(StringUtils.isNotEmpty(name),Employee::getUsername,name); // 添加排序 queryWrapper.orderByDesc(Employee::getUpdateTime); // 执行查询 employeeService.page(pageInfo, queryWrapper); return R.success(pageInfo); }
2. Enable or disable employee status
1 Requirements analysis
Employee management list page, you can enable or disable an employee's status. Employees with disabled accounts cannot log in to the system. Once enabled, they can log in normally. This operation is only allowed for administrators.
2 Code development
Front-end core code
How to ensure that only the administrator admin can see the disabled button on the page. In fact, only the login information is required on the front-end account, and then make a user name judgment:
Get the login account when the page is initialized:
created() { this.init() this.user = JSON.parse(localStorage.getItem('userInfo')).username },
The column that displays the account status:
<el-table-column label="账号状态"> <template slot-scope="scope"> {{ String(scope.row.status) === '0' ? '已禁用' : '正常' }} </template> </el-table-column>
Backend To pass the JSON data, you need to disable the employee's account ID and status to pass the value to the backend. The main front-end code:
//状态修改 statusHandle (row) { this.id = row.id this.status = row.status this.$confirm('确认调整该账号的状态?', '提示', { 'confirmButtonText': '确定', 'cancelButtonText': '取消', 'type': 'warning' }).then(() => { enableOrDisableEmployee({ 'id': this.id, 'status': !this.status ? 1 : 0 }).then(res => { console.log('enableOrDisableEmployee',res) if (String(res.code) === '1') { this.$message.success('账号状态更改成功!') this.handleQuery() } }).catch(err => { this.$message.error('请求出错了:' + err) }) }) },
Backend core code
/** * 根据用户ID去修改用户状态 * @param request * @param employee * @return */ @PostMapping public R<String> update(HttpServletRequest request, @RequestBody Employee employee){ // 获取员工ID Long empId = (Long) request.getSession().getAttribute("employee"); employee.setUpdateTime(LocalDateTime.now()); employee.setUpdateUser(empId); employeeService.updateById(employee); return R.success("员工信息修改成功"); }
In fact, the test found that this code is not It will be modified successfully because it involves a JS precision issue. JS can only identify the Long type accurately to 16 digits, while the ID generated by the snowflake algorithm has 19 digits, causing the ID accuracy to be lost.
Code Repair
How to solve the above problem and convert the Long type of the page to a string. Specific steps:
Use JacksonObjectMapper to convert JSON data
Extend the SringMVC message converter in the WebConfig configuration class and mirror the Java object to Conversion of JSON data
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 org.springframework.stereotype.Component; 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; /** * 对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象 * 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象] * 从Java对象生成JSON的过程称为 [序列化Java对象到JSON] */ @Component 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:
/** * 扩展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); }
After the repair, the employee status can be modified normally, and the ID has also been changed to string format. :
##
The above is the detailed content of How to use Java to implement employee information management system functions?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
