Home > Java > javaTutorial > body text

How to use Java to implement employee information management system functions?

王林
Release: 2023-04-26 13:52:07
forward
2291 people have browsed it

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:

How to use Java to implement employee information management system functions?

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

How to use Java to implement employee information management system functions?

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;
    }
}
Copy after login

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);
    }
Copy after login

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(&#39;userInfo&#39;)).username
        },
Copy after login

The column that displays the account status:

<el-table-column label="账号状态">
    <template slot-scope="scope">
        {{ String(scope.row.status) === &#39;0&#39; ? &#39;已禁用&#39; : &#39;正常&#39; }}
    </template>
</el-table-column>
Copy after login

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(&#39;确认调整该账号的状态?&#39;, &#39;提示&#39;, {
		&#39;confirmButtonText&#39;: &#39;确定&#39;,
		&#39;cancelButtonText&#39;: &#39;取消&#39;,
		&#39;type&#39;: &#39;warning&#39;
	}).then(() => {
		enableOrDisableEmployee({ &#39;id&#39;: this.id, &#39;status&#39;: !this.status ? 1 : 0 }).then(res => {
			console.log(&#39;enableOrDisableEmployee&#39;,res)
			if (String(res.code) === &#39;1&#39;) {
				this.$message.success(&#39;账号状态更改成功!&#39;)
				this.handleQuery()
			}
		}).catch(err => {
			this.$message.error(&#39;请求出错了:&#39; + err)
		})
	})
},
Copy after login
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("员工信息修改成功");
}
Copy after login

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);
    }
}
Copy after login

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);
    }
Copy after login

After the repair, the employee status can be modified normally, and the ID has also been changed to string format. :

How to use Java to implement employee information management system functions?##

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template