首页 > 编程语言 > 详细

springboot集成参数校验实例

时间:2021-07-02 15:20:19      阅读:22      评论:0      收藏:0      [点我收藏+]

一 引入JAR

<!--数据校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

二实体类添加注解
package com.gllic.workweixin.mqdto;

import com.alibaba.fastjson.JSONArray;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Data
@NoArgsConstructor
public class ReportMsg {
/**
* 系统赋权
*/
@NotBlank(message = "系统赋权参数不能为空")
private String system;

/**
*操作类型
*/
@NotBlank(message = "操作类型不能为空")
private String type;


/**
* 消息数据统计日期
* */
@NotBlank(message = "消息数据统计日期不能为空")
private String date;
/**
* 消息数据统计开始日期
* */
@NotBlank(message = "消息数据统计开始日期不能为空")
private String startTime;
/**
* 消息数据统计结束日期
* */
@NotBlank(message = "消息数据统计结束日期不能为空")
private String endTime;
/**
应用ID
* */
private String agentid;
/**
播报数据
* */
@Size(min = 1)
private JSONArray listData;
/**
* 表示是否开启id转译
*/
private String enable_id_trans;
/**
* 表示是否开启重复消息检查,0表示否,1表示是,默认0
*/
private String enable_duplicate_check;
/**
* 表示是否重复消息检查的时间间隔,默认1800s,最大不超过4小时
*/
private String duplicate_check_interval;
}


三 在需要校验的类加上@Valid
package com.gllic.workweixin.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gllic.workweixin.mqdto.AppMsg;
import com.gllic.workweixin.mqdto.ReportMsg;
import com.gllic.workweixin.mqdto.System;
import com.gllic.workweixin.service.AppMsgService;
import com.gllic.workweixin.service.PublicService;
import com.gllic.workweixin.service.SwicthToImageService;
import com.gllic.workweixin.service.WxAppMsgService;
import com.gllic.workweixin.utils.HttpUtil;
import com.gllic.workweixin.utils.JFreeChartUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.ArrayList;

/**
* @program: projectOfWechat
* @ClassName AppMesServiceImpl
* @description:
* @author: Marlo
* @create: 2021-04-25 10:47
* @Version 1.0
**/
@Validated
@Slf4j
@Service
public class AppMesServiceImpl implements AppMsgService {
@Autowired
PublicService publicService;
@Autowired
SwicthToImageService swicthToImageService;
@Autowired
WxAppMsgService wxAppMsgService;

@Value("${IMAGES.URL}")
private String imgURL;
@Value("${IMAGES.msgSkipURL}")
private String msgSkipURL;
@Value("${workweixin.Totag}")
private String Totag;
@Value("${IMAGES.PATH}")
private String PATH;

@Override
public void sendMsgToUser(String missionId, AppMsg appMsg) {
System sysPermission = publicService.checkSystemPer(appMsg.getSystem());
if (sysPermission == null) {
log.warn("missionId:{},系统赋权失败,system:{},接收报文:{}", missionId, appMsg.getSystem(), appMsg);
return;
}
String agentid = sysPermission.getAgentid();
appMsg.setAgentid(agentid);
String content = appMsg.getContent();
/*JSONObject msgJsonObj = new JSONObject();
msgJsonObj.put("touser", appMsg.getTouser());
msgJsonObj.put("toparty", appMsg.getToparty());
msgJsonObj.put("totag", appMsg.getTotag());
msgJsonObj.put("msgtype", appMsg.getMsgtype());
msgJsonObj.put("agentid", appMsg.getAgentid());
msgJsonObj.put("safe", appMsg.getSafe());
msgJsonObj.put(appMsg.getMsgtype(), appMsg.getMessageBody());
msgJsonObj.put("enable_id_trans", appMsg.getEnable_id_trans());
msgJsonObj.put("enable_duplicate_check", appMsg.getEnable_duplicate_check());
msgJsonObj.put("duplicate_check_interval", appMsg.getDuplicate_check_interval());*/
JSONObject text = new JSONObject();
text.fluentPut("content", content);
appMsg.setText(text);
String token = publicService.getAppMedssageToken();
String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
log.info("missionId:{},企业微信发送应用消息请求报文:{}", missionId, JSON.toJSONString(appMsg));
String resStr = HttpUtil.postJson(url, JSON.toJSONString(appMsg));
log.info("missionId:{},企业微信发送应用消息返回报文:{}", missionId, resStr);
JSONObject response = JSONObject.parseObject(resStr);
if (response.get("errcode").toString().equals("0")) {
log.info("missionId:{},企业微信发送应用消息成功:{}", missionId, JSON.toJSONString(appMsg));
} else {
log.info("missionId:{},企业微信发送应用消息失败:{}, 返回报文:{}", missionId, JSON.toJSONString(appMsg), resStr);
}
}

/**
* @return
* @Author Marlo
* @Description 应用发送各种类型的消息(文本、图片、视频等)给成员
* @Date 9:34 2021/6/17
* @Param
**/
@Override
public void sendAllTypeMsgToUser(String missionId,@Valid ReportMsg reportMsg) {
System sysPermission = publicService.checkSystemPer(reportMsg.getSystem());
if (sysPermission == null) {
log.warn("missionId:{},系统赋权失败,system:{},接收报文:{}", missionId, reportMsg.getSystem(), reportMsg);
return;
}
reportMsg.setAgentid(sysPermission.getAgentid());
JSONObject msgJsonObj = this.setMsgData(reportMsg);
wxAppMsgService.sendMsg(missionId, msgJsonObj, sysPermission.getSecret());
}

/**
* @return
* @Author Marlo
* @Description 接收的数据转为图片消息
* @Date 17:57 2021/6/21
* @Param
**/
public JSONObject setMsgData(ReportMsg reportMsg) {
log.info("封装消息开始,reportMsg:{}", reportMsg);
//封装子消息体start
JSONObject msgJsonObj = new JSONObject();
//根据不同消息类型,进行子消息封装
JSONObject msgBody = setChildMsg(reportMsg);
msgJsonObj.put("news", msgBody);
//封装子消息体end
//封装最外层消息体start
//发送消息的标签ID,可在外部配置
msgJsonObj.put("totag", Totag);
msgJsonObj.put("msgtype", "news");
msgJsonObj.put("agentid", reportMsg.getAgentid());
//封装最外层消息体end
log.info("封装消息结束msgJsonObj:{}", msgJsonObj.toString());
return msgJsonObj;
}

/**
* @return
* @Author Marlo
* @Description 根据消息类型封装子消息
* @Date 14:01 2021/6/22
* @Param
**/
public JSONObject setChildMsg(ReportMsg reportMsg) {
JSONObject msgBody = new JSONObject();
ArrayList<JSONObject> msgList = new ArrayList<>();
JSONObject msg = new JSONObject();
//图文消息
//if (appMsg.getMsgtype().equals(AppMsgType.NEWS.value())) {
//PATH:图片本地路径
log.info("HTML转图片开始:{}", reportMsg.getListData());
//个人业绩十强排名
JSONObject namaJSON = JFreeChartUtil.makeBarChart(PATH, reportMsg.getListData());
log.info("HTML转图片结束namaJSON:{}", namaJSON);
msg.put("title", "每日业绩播报(" + reportMsg.getDate() + ")");
msg.put("description", "查看详情");
//点击后跳转的URL
msg.put("url", msgSkipURL + "imageName1=" + namaJSON.getString("imageName1") + "&imageName2=" + namaJSON.getString("imageName2") + "&startDate=" + reportMsg.getStartTime() + "&endDate=" + reportMsg.getEndTime());
//消息封面的图片地址
msg.put("picurl", imgURL);
msgList.add(msg);
msgBody.put("articles", msgList);
// }
return msgBody;
}
}

四添加全局异常处理
package com.gllic.workweixin.config;

import cn.hutool.core.util.StrUtil;
import com.gllic.workweixin.mqdto.LogKey;
import com.gllic.workweixin.mqdto.ResultOfAll;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
* 全局异常处理器
*
* @author Marlo
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

/**
* 自定义验证异常
*/
@ExceptionHandler(BindException.class)
public ResultOfAll validatedBindException(BindException e) {
log.error(e.getMessage());
String message = e.getAllErrors().get(0).getDefaultMessage();
log.info(ResultOfAll.error(MDC.get(LogKey.missionId), message).toString());
return ResultOfAll.error(MDC.get(LogKey.missionId), message);
}

/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object validExceptionHandler(MethodArgumentNotValidException e) {
log.error(e.getMessage());
FieldError fieldError = e.getBindingResult().getFieldError();
if (null != fieldError) {

String message = fieldError.getDefaultMessage();
return ResultOfAll.error(MDC.get(LogKey.missionId), message);
}
log.info(ResultOfAll.error(MDC.get(LogKey.missionId), "").toString());
return ResultOfAll.error(MDC.get(LogKey.missionId), "");
}

@ExceptionHandler(ConstraintViolationException.class)
public Object processException(ConstraintViolationException exception, HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> msg = new HashMap<>();
exception.getConstraintViolations().forEach(error -> {
String message = error.getMessage();
String path = error.getPropertyPath().toString();
msg.put(StrUtil.toUnderlineCase(path), message);
});
log.info(ResultOfAll.error(MDC.get(LogKey.missionId), msg.toString()).toString());
return ResultOfAll.error(MDC.get(LogKey.missionId), msg.toString());
}
}
package com.gllic.workweixin.mqdto;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
* @program: workweixin-mobile-api
* @ClassName ResultOfAll
* @description:
* @author: Marlo
* @create: 2021-07-02 10:16
* @Version 1.0
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResultOfAll {
@JsonInclude(JsonInclude.Include.NON_NULL)
private String tradeDate;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String missionId;
private int respCode;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String respMsg;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Object respData;


public static ResultOfAll ok(String missionId,String message){
return new ResultOfAll(getNowDate(),missionId,ResultCodes.OK,message,null);
}

public static ResultOfAll ok(String missionId,String message,Object data){
return new ResultOfAll(getNowDate(),missionId,ResultCodes.OK,message,data);
}

public static ResultOfAll error(String message){
return new ResultOfAll(getNowDate(),null,ResultCodes.ERROR,message,null);
}

public static ResultOfAll error(String missionId,String message){
return new ResultOfAll(getNowDate(),missionId,ResultCodes.ERROR,message,null);
}

public static ResultOfAll error(String missionId,int code,String message){
return new ResultOfAll(getNowDate(),missionId,code,message,null);
}

public static ResultOfAll unauthorized(String message){
return new ResultOfAll(getNowDate(),null,ResultCodes.UNAUTHORIZED,message,null);
}

public static String getNowDate(){
LocalDateTime now=LocalDateTime.now();
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyyMMdd HHmmss");
return dtf.format(now);
}
}
package com.gllic.workweixin.mqdto;

public final class LogKey {
private LogKey(){}
public static String missionId="missionid";
}
package com.gllic.workweixin.mqdto;

public final class ResultCodes {
private ResultCodes(){}
public static final int OK=0;
public static final int WARN=100;
public static final int ERROR=400;
public static final int UNAUTHORIZED=401;
}


springboot集成参数校验实例

原文:https://www.cnblogs.com/Marlo/p/14962912.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!