BeanUtils StringUtils Validation

本文详细介绍了如何使用Apache Commons BeanUtils库进行JavaBean的属性复制、设置及克隆,包括从Map集合填充JavaBean、对象属性的深拷贝、指定属性的设置与复制,以及类型转换和自定义转换器的实现。
package com.example.demo.BeanUtils;


import com.example.demo.dao.Animals;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shuyue.guo
 * @date 2019/12/16
 */

public class test {

    public void test1() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "tuantuan");
        map.put("age", 3);
        map.put("color", "black");
        map.put("sex", "female");

        // 将map数据拷贝到javabean中
        Animals a1 = new Animals();
        BeanUtils.populate(a1,map);
        System.out.println(a1);

        // 对象的拷贝
        Animals a2 = new Animals();
        org.springframework.beans.BeanUtils.copyProperties(a1,a2);

        System.out.println(a2);

        Animals a3 = new Animals();

        // 设置指定的属性
        BeanUtils.setProperty(a3, "sex", "male");
        System.out.println("set"+a3);

        // 拷贝指定的属性
        Animals a4 = new Animals();

        BeanUtils.copyProperty(a4, "sex", "22");
        System.out.println("copy" + a4);
        System.out.println("copy"+a3);


        // 克隆对象
        Object object = BeanUtils.cloneBean(a3);
        System.out.println(object);

        // 将整型转换成字符串
        Object objectConvert = ConvertUtils.convert(123,String.class);
        String typeName = object.getClass().getTypeName();
        System.out.println(typeName);

        // 将日期转换成字符串
        Object object2 = ConvertUtils.convert(new Date(), String.class);
        String typeName2 = object2.getClass().getTypeName();
        System.out.println(typeName2);

        // 将字符串转换成Double
        Object object3 = ConvertUtils.convert("123", Double.class);
        String typeName3 = object3.getClass().getTypeName();
        System.out.println(typeName3);

        // 自定义convert使用
        MyConverter myConverter = new MyConverter("yyy-MM-dd HH:mm:ss");
        //注册该转换器
        ConvertUtils.register(myConverter,Date.class);
        Animals a5 = new Animals();
        Object object4 = ConvertUtils.convert("2019-03-13 14:04:00",Date.class);
        System.out.println(object4.getClass().getTypeName());
        System.out.println("date:"+object4);

        Animals a6 = new Animals();
        BeanUtils.copyProperty(a6,"birth","2019-03-13 14:04:00");
        System.out.println(a6);

    }

}

状态转换器

package com.example.demo.BeanUtils;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @author shuyue.guo
 * @date 2019/12/17
 */
public class MyConverter implements Converter {
    private static SimpleDateFormat format;

    MyConverter(String pattern){
        format = new SimpleDateFormat(pattern);
    }
    @Override
    public Object convert(Class type,Object value) {
        if(value == null){
            return null;
        }else {
            if(value instanceof String){
                String temp = (String)value;
                if(temp.trim().length() == 0){
                    return null;
                }else {
                    try {
                        return format.parse(temp);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }else {
                throw new ConversionException("not string");
            }
        }
        return value;
    }

}

ApiBenaUtils API

StringUtils API

Validation API

获取validation message 并且放在返回api中

package com.example.demo.util;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;

/**
 * @author shuyue.guo
 * @date 2019/12/11
 */
public class ValidateUtil {
    public static Object validateError(BindingResult result) {
        HashMap<String,Object> msg = new HashMap<>();
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                return msg.put("warn", ValidateUtil.validateError(result));
            }
        }
        return null;
    }
}

/* * Copyright (c) 2018-2028, Chill Zhuang All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the dreamlu.net developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: Chill 庄骞 (smallchill@163.com) */ package com.foonsu.efenxiao.user.controller; import com.alibaba.cloud.commons.lang.StringUtils; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.foonsu.efenxiao.common.cache.CacheNames; import com.foonsu.efenxiao.common.constant.CommonConstant; import com.foonsu.efenxiao.common.enums.UserDetailType; import com.foonsu.efenxiao.common.exception.CommonErrorCode; import com.foonsu.efenxiao.common.exception.ServiceException; import com.foonsu.efenxiao.common.oss.OSSApiService; import com.foonsu.efenxiao.common.utils.ValidateUtils; import com.foonsu.efenxiao.system.entity.Tenant; import com.foonsu.efenxiao.system.service.ITenantService; import com.foonsu.efenxiao.system.vo.TenantVO; import com.foonsu.efenxiao.user.dto.req.ModifyPasswordReq; import com.foonsu.efenxiao.user.dto.MergeAccountsReq; import com.foonsu.efenxiao.user.entity.User; import com.foonsu.efenxiao.user.entity.ValidateAddress; import com.foonsu.efenxiao.user.handler.UploadHandler; import com.foonsu.efenxiao.user.service.IUserService; import com.foonsu.efenxiao.user.vo.SubUserResp; import com.foonsu.efenxiao.user.vo.SubUserSaveVO; import com.foonsu.efenxiao.user.vo.UserDetailVO; import com.foonsu.efenxiao.user.vo.UserSaveVO; import com.foonsu.framework.boot.common.utils.ConvertDomainUtils; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.google.common.collect.Sets; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import lombok.AllArgsConstructor; import org.springblade.core.mp.support.Condition; import org.springblade.core.mp.support.Query; import org.springblade.core.redis.cache.BladeRedis; import org.springblade.core.secure.BladeUser; import org.springblade.core.secure.utils.AuthUtil; import org.springblade.core.tenant.annotation.NonDS; import org.springblade.core.tool.api.R; import org.springblade.core.tool.utils.Func; import org.springframework.beans.BeanUtils; import org.springframework.util.ObjectUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List; /** * 控制器 * * @author Chill */ @NonDS @RestController @RequestMapping @AllArgsConstructor @Validated @Api(value = "", tags = "用户接口") public class UserController { private final IUserService userService; private final ITenantService tenantService; private final BladeRedis bladeRedis; private final UploadHandler uploadHandler; /** * 修改密码 */ @PostMapping("/update-password") @ApiOperationSupport(order = 9) @ApiOperation(value = "修改密码", notes = "传入密码") public R updatePassword(@Valid ModifyPasswordReq modifyPasswordReq) { BladeUser user = AuthUtil.getUser(); boolean temp = userService.updatePassword(user.getUserId(), modifyPasswordReq); return R.status(temp); } /** * 用户解锁 */ @PostMapping("/unlock") @ApiOperationSupport(order = 19) @ApiOperation(value = "账号解锁", notes = "传入id") public R unlock(String userIds) { List<User> userList = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, Func.toLongList(userIds))); userList.forEach(user -> bladeRedis.del(CacheNames.tenantKey(user.getTenantId(), CacheNames.USER_FAIL_KEY, user.getAccount()))); return R.success("操作成功"); } /** * 个人信息设置 */ @PostMapping("/selfSetting") @ApiOperationSupport(order = 20) @ApiOperation(value = "个人信息设置", notes = "传入用户信息") public R selfSetting(@Valid @RequestBody TenantVO tenantVO) { BladeUser user = AuthUtil.getUser(); //参数校验 ValidateAddress validateAddress = new ValidateAddress(); BeanUtils.copyProperties(tenantVO,validateAddress); validateAddress.setMobile(tenantVO.getDfMobile()); R validResult = validateAddress.validateParam(validateAddress); if (!R.isSuccess(validResult)){ return R.fail(validResult.getMsg()); } if (StringUtils.isBlank(tenantVO.getName())) { return R.fail("昵称不能为空"); } if (StringUtils.isBlank(tenantVO.getDfMobile()) && StringUtils.isBlank(tenantVO.getPhone())){ return R.fail("手机号或电话至少填一项"); } if (StringUtils.isNotBlank(tenantVO.getDfMobile())){ if (!ValidateUtils.isValidMobile(tenantVO.getDfMobile())) { return R.fail("手机号格式不正确"); } } if (StringUtils.isNotBlank(tenantVO.getPhone())){ if (!ValidateUtils.isValidPhone(tenantVO.getPhone())) { return R.fail("电话格式不正确"); } } //头像和昵称插入user表,其他的插入tenant表 User updateUser = new User(); updateUser.setAvatar(tenantVO.getAvatar()); updateUser.setName(tenantVO.getName()); updateUser.setTenantId(user.getTenantId()); updateUser.setAccount(user.getAccount()); Tenant tenant = new Tenant(); tenant.setTenantId(user.getTenantId()); tenant.setProvince(tenantVO.getProvince()); tenant.setCity(tenantVO.getCity()); tenant.setDistrict(tenantVO.getDistrict()); tenant.setTown(tenantVO.getTown()); tenant.setDetail(tenantVO.getDetail()); tenant.setPhone(tenantVO.getPhone()); tenant.setContact(tenantVO.getContact()); tenant.setDfMobile(tenantVO.getDfMobile()); if (StringUtils.isNotBlank(updateUser.getAvatar())){ uploadHandler.useUploadedFile(Sets.newHashSet(updateUser.getAvatar()), OSSApiService.avatarFolderName); } return R.status(userService.updateUserAndTenant(updateUser,tenant)); } /** * 个人信息查询 */ @GetMapping("/querySelfSetting") @ApiOperationSupport(order = 20) @ApiOperation(value = "查询个人设置", notes = "") public R<TenantVO> querySelfSetting() { BladeUser user = AuthUtil.getUser(); Tenant tenant = tenantService.getOne(Wrappers.<Tenant>query().lambda().eq(Tenant::getTenantId,user.getTenantId())); User localUser = userService.getOne(Wrappers.<User>query().lambda().eq(User::getId,user.getUserId())); TenantVO tenantVO = new TenantVO(); tenantVO.setPhone(tenant.getPhone()); tenantVO.setDfMobile(tenant.getDfMobile()); tenantVO.setMobile(tenant.getMobile()); tenantVO.setProvince(tenant.getProvince()); tenantVO.setCity(tenant.getCity()); tenantVO.setDistrict(tenant.getDistrict()); tenantVO.setTown(tenant.getTown()); tenantVO.setDetail(tenant.getDetail()); tenantVO.setContact(tenant.getContact()); tenantVO.setAvatar(localUser.getAvatar()); tenantVO.setName(localUser.getName()); return R.data(tenantVO); } /** * 添加用户 */ @PostMapping("/addUser") @ApiOperationSupport(order = 20) @ApiOperation(value = "添加用户", notes = "传入User") public R submit(@Valid @RequestBody UserSaveVO vo) { return R.status(userService.addUser(vo)); } /** * 找回密码 */ @PostMapping("/retrievePassword") @ApiOperationSupport(order = 21) @ApiOperation(value = "找回密码", notes = "找回密码") public R retrievePassword(@RequestBody UserSaveVO vo) { boolean temp = userService.retrievePassword(vo); return R.status(temp); } /** * 查询用户信息 */ @ApiOperationSupport(order = 1) @ApiOperation(value = "查看详情", notes = "传入id") @GetMapping("/userInfo") public R<UserDetailVO> userInfo() { BladeUser bladeUser = AuthUtil.getUser(); User detail = userService.getById(bladeUser.getUserId()); HashMap<String, Object> user = userService.masterAccountQuery(bladeUser.getUserId()); UserDetailVO userDetailVO = new UserDetailVO(); BeanUtils.copyProperties(detail, userDetailVO); if (user.get("id").equals(user.get("adminUserId"))){ userDetailVO.setType(0); } else { userDetailVO.setType(1); } String ownerPhone = !ObjectUtils.isEmpty(user.get("mobile")) ? user.get("mobile").toString() : null; if (StringUtils.isBlank(detail.getPhone())) { userDetailVO.setPhone(ownerPhone); } String account = StringUtils.isNotBlank(detail.getPhone()) ? detail.getPhone() : ownerPhone; userDetailVO.setAccount(account); if(bladeUser.getDetail() != null ){ if ( bladeUser.getDetail().containsKey(UserDetailType.tags.name())){ userDetailVO.setTags(bladeUser.getDetail().get(UserDetailType.tags.name()).toString()); } if(bladeUser.getDetail().containsKey(CommonConstant.LOGIN_SOURCE)){ userDetailVO.setLoginSource(bladeUser.getDetail().get(CommonConstant.LOGIN_SOURCE).toString()); } } return R.data(userDetailVO); } @PostMapping("/addPhone") @ApiOperationSupport(order = 30) @ApiOperation(value = "添加手机号码", notes = "") public R addPhone(@RequestBody SubUserSaveVO vo){ BladeUser bladeUser = AuthUtil.getUser(); if(StringUtils.isBlank(vo.getPhone()) || StringUtils.isBlank(vo.getUuid())){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } userService.addPhone(vo, bladeUser); return R.data(true); } @PostMapping("/addAccountPassword") @ApiOperationSupport(order = 30) @ApiOperation(value = "添加账号密码", notes = "") public R addAccountPassword(@RequestBody SubUserSaveVO vo){ BladeUser bladeUser = AuthUtil.getUser(); if(StringUtils.isBlank(vo.getPhone())){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } userService.addAccountPassword(vo, bladeUser); return R.data(true); } @PostMapping("/mergeAccounts") @ApiOperationSupport(order = 30) @ApiOperation(value = "合并账号", notes = "") public R<Long> mergeAccounts(@RequestBody @Valid MergeAccountsReq mergeAccountsReq){ return R.data(userService.mergeAccounts(mergeAccountsReq)); } @PostMapping("/addSubUser") @ApiOperationSupport(order = 30) @ApiOperation(value = "新增子账号", notes = "传入User") public R addSubUser(@RequestBody SubUserSaveVO vo) { BladeUser bladeUser = AuthUtil.getUser(); if(StringUtils.isBlank(vo.getAccount()) || StringUtils.isBlank(vo.getPassword()) || StringUtils.isBlank(vo.getPhone()) || StringUtils.isBlank(vo.getUuid())){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } userService.addSubUser(vo, bladeUser); return R.data(true); } @PostMapping("/updateSubUser") @ApiOperationSupport(order = 31) @ApiOperation(value = "修改子账号", notes = "传入User") public R updateSubUser(@RequestBody SubUserSaveVO vo) { BladeUser bladeUser = AuthUtil.getUser(); if(StringUtils.isBlank(vo.getAccount()) && StringUtils.isBlank(vo.getPassword()) && StringUtils.isBlank(vo.getRemark())){ return R.data(true); } if(vo.getId() == null){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } userService.updateSubUser(vo, bladeUser); return R.data(true); } @PostMapping("/deleteSubUser") @ApiOperationSupport(order = 32) @ApiOperation(value = "删除", notes = "传入User") public R deleteSubUser(@RequestBody SubUserSaveVO vo) { BladeUser bladeUser = AuthUtil.getUser(); if(vo.getId() == null){ throw new ServiceException(CommonErrorCode.PARAM_INVALID); } userService.deleteSubUser(vo.getId(), bladeUser); return R.data(true); } @ApiOperation(value = "查询子账号", notes = "传入User") @GetMapping("/subUserPage") public R<IPage<SubUserResp>> subUserPage(@ApiParam("登录账号/手机") String accountOrPhone, Query query) { BladeUser bladeUser = AuthUtil.getUser(); LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>query().lambda(); Tenant tenant = tenantService.getByTenantId(bladeUser.getTenantId()); queryWrapper.isNull(User::getShopPlatform).eq(User::getTenantId, bladeUser.getTenantId()).ne(User::getId, tenant.getAdminUserId()); if (StringUtils.isNotBlank(accountOrPhone)) { queryWrapper.and(t->t.eq(User::getAccount, accountOrPhone).or(t1->t1.eq(User::getPhone, accountOrPhone))); } IPage<User> pages = userService.page(Condition.getPage(query), queryWrapper); List<User> records = pages.getRecords(); IPage<SubUserResp> pageVo = new Page(pages.getCurrent(), pages.getSize(), pages.getTotal()); pageVo.setRecords(ConvertDomainUtils.convertList(records, SubUserResp.class)); return R.data(pageVo); } @ApiOperation(value = "验证本人手机号", notes = "传入User") @ApiOperationSupport(order = 40) @PostMapping("/checkMySelfPhone") public R checkMySelfPhone(@RequestBody SubUserSaveVO vo) { userService.checkMySelfPhone(vo); return R.success("验证成功"); } @ApiOperation(value = "修改用户手机号", notes = "传入User") @ApiOperationSupport(order = 41) @PostMapping("/update-phone") public R updatePhone(@RequestBody SubUserSaveVO vo) { boolean updateFlag = userService.updatePhone(vo); return R.status(updateFlag); } } 逐行解释一下
最新发布
07-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值