基于springBoot进行表单验证

1.通过maven导入相关依赖:

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

2. 对表单数据绑定的对象添加相关的注解 可参考:https://www.jianshu.com/p/9e33ec934ff0

package com.yzy.sell.form;


import lombok.Data;

import javax.validation.constraints.NotEmpty;

@Data
public class OrderForm {


    /**
     * 买家姓名
     */
    @NotEmpty(message = "姓名必填")
    private String name;

    /**
     * 买家手机号
     */
    @NotEmpty(message = "手机号必填")
    private String phone;

    /**
     * 买家地址
     */
    @NotEmpty(message = "地址必填")
    private String address;

    /**
     * 买家微信openid
     */
    @NotEmpty(message = "openid必填")
    private String openid;

    /**
     * 购物车
     */
    @NotEmpty(message = "购物车不能为空")
    private String items;
}

3. 在controller中调用

package com.yzy.sell.Controller;
import com.yzy.sell.DTO.OrderDTO;
import com.yzy.sell.Enums.ResultEnum;
import com.yzy.sell.Service.OrderService;
import com.yzy.sell.VO.ResultVO;
import com.yzy.sell.converter.OrderForm2OrderDtoConverter;
import com.yzy.sell.exception.SellException;
import com.yzy.sell.form.OrderForm;
import com.yzy.sell.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    //@Valid 和 BindingResult 是一一对应的,
    //如果有多个@Valid,那么每个@Valid后面跟着的BindingResult就是这个@Valid的验证结果,顺序不能乱
    public ResultVO<OrderDTO> create(@Valid OrderForm orderForm, BindingResult bindingResult) { 
        if(bindingResult.hasErrors()){   //判断表单验证是否通过
            log.error("【创建订单】参数不正确, orderForm={}", orderForm);
            throw  new SellException(ResultEnum.PARAM_ERROR.getCode()
            ,bindingResult.getFieldError().getDefaultMessage());  
           //bindingResult可获取表单验证的信息
        }
        OrderDTO orderDTO = OrderForm2OrderDtoConverter.converter(orderForm);

        OrderDTO createResult = orderService.create(orderDTO);
        String orderId = createResult.getOrderId();
        Map<String,String> orderIdMap=new HashMap<>();
        orderIdMap.put("orderId",orderId);
        ResultVO resultVO = ResultVOUtil.success(orderIdMap);
        return resultVO;
    }
}

 

 

 

//bindingResult可获取表单验证的信息
posted @ 2020-06-17 23:06  shouyaya  阅读(227)  评论(0编辑  收藏  举报