java开发

Springboot接口参数验证

2020-09-23  本文已影响0人  DragonRat

本人java新生,因为公司要开发个java项目在这里做个记录

归纳下分成三步:
1、引入pom文件

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.4.Final</version>
        </dependency>

2、废话少说直接贴代码,关键是@Validated和@Size这两个注解

package com.mpt.crm.controller.lms;

import com.mpt.crm.entity.PointChangeEnrollLog;
import com.mpt.crm.entity.PointChangeLog;
import com.mpt.crm.entity.PointEnrollment;
import com.mpt.crm.exception.CustomizeException;
import com.mpt.crm.service.MemberService;
import com.mpt.crm.service.PointService;
import com.mpt.crm.utils.FuncUtil;
import com.mpt.crm.utils.LmsResponseUtil;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Validated
@RestController
@RequestMapping("/unifiedID")
public class LmsPointController {
    @Autowired
    private MemberService memberService;

    @Autowired
    private PointService pointService;


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Value("${elasticsearch.index-prefix}")
    private String indexPrefix;

    @PostMapping("/getHistory")
    public LmsResponseUtil pointLogQueryList(@RequestParam(value = "MSISDN") @Size(min = 1,max = 20,message = "MSISDN must 1~20") String mobile,
                                             @RequestParam(value = "ENDINDEX", defaultValue = "5")  
 Integer limit,
                                             @RequestParam(value = "STARTINDEX", defaultValue = "0") 
 Integer page,
                                             @RequestParam(value = "STARTDATE") @Size(min = 1, max = 10,message = "STARTDATE must 1~10") String startTime,
                                             @RequestParam(value = "ENDDATE" ) @Size(min = 1, max = 10,message = "ENDDATE must 1~10") String endTime,
                                             @RequestParam(value = "REQUESTTYPE" ) @Size(min = 1, max = 3,message = "REQUESTTYPE must 1~3") String type
    ) throws CustomizeException  {

        //根据mobile获取member_id
        int member_id = memberService.findDetailByMobile(mobile.toString());
        if(member_id==0){
            return LmsResponseUtil.fail(1000,"fail");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("member_id", member_id);
        //int page_data  = Integer.parseInt(page)* Integer.parseInt(limit);
        int page_data  = page* limit;
        if(page_data<0){
            return LmsResponseUtil.fail(1001,"fail");
        }
        data.put("page", page_data);
        //data.put("limit", Integer.parseInt(limit));
        data.put("limit", limit);
        String startT = startTime+"000000";
        String reg = "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})";
        startT = startT.replaceAll(reg, "$1-$2-$3 $4:$5:$6");
        String endT = endTime+"235959";
        endT = endT.replaceAll(reg, "$1-$2-$3 $4:$5:$6");
        data.put("startTime", startT);
        data.put("endTime", endT);

        HashMap<String, Object> resData = new HashMap<>();
        if(type.equals("ACC")){
            List<String> action = new ArrayList<>(Arrays.asList("0","1","2"));
            data.put("action", action);
            data.put("changeType", 1);
            System.out.println(data);
            List<PointChangeLog> pointLogQueryList= pointService.pointChangeLogList(data);


            int totalCount = 0;
            List<Map<String ,Object>> list=new ArrayList<>();
            for (PointChangeLog dat : pointLogQueryList) {
                System.out.println(dat.toString());
                //总数计算
                totalCount = totalCount + dat.getAmount().intValue();
                Map<String, Object> map = new HashMap<>();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String transactionDate = formatter.format(dat.getChangeTime());
                map.put("transactionDate",transactionDate);
                map.put("transactionAmount",0);
                if(dat.getType() ==0){
                    map.put("transactionType","adjust");
                }else if (dat.getType()==1){
                    map.put("transactionType","invite");
                }else{
                    map.put("transactionType","handsel");
                }
                map.put("point",dat.getAmount());
                SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd");
                if(dat.getExpiredAt() ==null){
                    map.put("expiryDate",null);
                }else{
                    map.put("expiryDate",form.format(dat.getExpiredAt()));

                }
                list.add(map);
            }
            resData.put("totalCount",totalCount);
            resData.put("transactions",list);

        }else if(type.equals("RED")){
            List<String> action = new ArrayList<>(Arrays.asList("3","4"));
            data.put("action", action);

            List<PointChangeLog> pointLogQueryList= pointService.pointChangeLogList(data);
            int totalCount = 0;
            List<Map<String ,Object>> list=new ArrayList<>();
            for (PointChangeLog dat : pointLogQueryList) {
                //总数计算
                totalCount = totalCount+ dat.getAmount().intValue();
                Map<String, Object> map = new HashMap<>();
                //积分兑现商品:订单兑现填商品,优惠券兑换填coupon-优惠券id
                if(dat.getActionType()==3){
                    map.put("redemptionItem","Coupon-"+dat.getItemId());
                }else{
                    //订单号查询订单商品信息
                    try {
                        GetRequest request = new GetRequest(indexPrefix + ".order_goods", "order_goods", dat.getItemId());
                        GetResponse getRequest = restHighLevelClient.get(request);
                        boolean exists = getRequest.isExists();
                        if (exists) {
                            data = getRequest.getSource();
                            map.put("redemptionItem",data.get("goods_name"));
                        }else{
                            map.put("redemptionItem","");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String redemptionDate = formatter.format(dat.getChangeTime());
                map.put("redemptionDate",redemptionDate);
                map.put("redemptionType","MPT_CLUB");
                map.put("pointsRedeemed",dat.getAmount());
                list.add(map);
            }
            resData.put("totalCount",totalCount);
            resData.put("transactions",list);

        }else if(type.equals("TRA")){
            List<String> action = new ArrayList<>(Arrays.asList("5"));
            data.put("action", action);
            data.put("changeType", "1");

            List<PointChangeLog> pointLogQueryList= pointService.pointChangeLogList(data);
            int totalCount = 0;
            List<Map<String ,Object>> list=new ArrayList<>();
            for (PointChangeLog dat : pointLogQueryList) {
                //总数计算
                totalCount = totalCount+ dat.getAmount().intValue();
                Map<String, Object> map = new HashMap<>();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String transferDate = formatter.format(dat.getChangeTime());
                map.put("transferDate",transferDate);
                map.put("transferPoints",dat.getAmount());
                map.put("receiverMSISDN",dat.getItemId());
                list.add(map);
            }
            resData.put("totalCount",totalCount);
            resData.put("transactions",list);

        }else{
            throw new CustomizeException(-1,"NO REQUESTTYPE");
        }

        resData.put("code",200);
        resData.put("message","ok");
        //resData.put("totalCount",totalCount);
        return LmsResponseUtil.success(resData);
    }

}

3、接收验证异常

package com.mpt.crm.exception;

import com.mpt.crm.constant.ResponseCode;
import com.mpt.crm.utils.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 异常处理类
 */
@ControllerAdvice
@ResponseBody
public class CustomExceptionHandler {


    @ExceptionHandler(value =Exception.class)
    public ResponseUtil handle(Exception e){
        if(e instanceof CustomizeException){

            CustomizeException customizeException = (CustomizeException) e;

            return ResponseUtil.fail(customizeException.getCode(),customizeException.getMsg());

        }else{
            return ResponseUtil.fail(ResponseCode.ERROR);
        }
    }

//验证异常
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseUtil handleValidationException(ConstraintViolationException e){
        for(ConstraintViolation<?> s:e.getConstraintViolations()){
            return ResponseUtil.fail(1000,s.getInvalidValue()+": "+s.getMessage());
        }
        return ResponseUtil.fail(1000,"fail");

    }

}

4、调用结果


接口调用.png
上一篇下一篇

猜你喜欢

热点阅读