当前位置:网站首页>Reuse of data validation framework Apache bval

Reuse of data validation framework Apache bval

2022-07-07 18:54:00 sp42a

About Apache BVal, I N Used a long time ago , He also wrote even the only Jianzhong tutorial in the whole network 《 Data validation framework Apache BVal brief introduction 》, I still hold that view :

Apache BVal ( Source code ) Is entity data validation Java Bean Validation Reference implementation of .Apache BVal Provides JSR 303 All built-in... In the specification constraint The implementation of the , Used to deal with Bean The value of the field in the constraint definition 、 Describe and verify . If only JSR The specification of large slag may not be clear , But I did POJO Of Hibernate Validator Annotated friends know what it is ,—— Then why not use mainstream Hibernate Validator Well ? Because the goods are all compressed packages 13mb 了 ( Although there can be documentation 、 The source code includes others ),BVal Only 400 many kb, And I just need the server to verify ,—— Innocent children can't afford to be hurt . My ORM It's also Mybatis Of , Try to be as lightweight as possible .

 Insert picture description here

usage

Maven quote

Add the following two Maven rely on :

<dependency>
	<groupId>org.apache.bval</groupId>
	<artifactId>bval-jsr</artifactId>
	<version>2.0.6</version>
</dependency>

<dependency>
	<groupId>javax.validation</groupId>
	<artifactId>validation-api</artifactId>
	<version>2.0.1.Final</version>
</dependency>

2.0 requirement Java 8,Apache CommonUtils Not strong dependence , meanwhile JSR The validation specification is also upgraded to 2.x.

Integrate Spring

Spring Injected inside Provider.

/** *  Data validation framework  * * @return */
@Bean
LocalValidatorFactoryBean localValidatorFactoryBean() {
    
	LocalValidatorFactoryBean v = new LocalValidatorFactoryBean();
	v.setProviderClass(ApacheValidationProvider.class);
	
	return v;
}

Call verification

Manual verification method , Try it first

@Autowired
LocalValidatorFactoryBean v;

public List<DataDict> getDataDict(Long parentId) {
    
	List<DataDict> list = DataDictDao.DataDictDAO.setWhereQuery("parentId", parentId).findList();

	Validator validator = v.getValidator();
	Set<ConstraintViolation<DataDict>> violations = validator.validate(list.get(0));
	System.out.println(violations.size()); //  Verification results 

	System.out.println(list.get(0).getParentId());
	if (CollectionUtils.isEmpty(list))
		list = new ArrayList<>();

	return list;
}

The above code is for a Java Bean:DataDict check ,Bean The fields of can be configured with the following constraints .

public class DataDict implements CommonEntity {
    
	/** *  Primary key  id, Self increasing  */
	private Long id;

	/** *  Father  id */
	@NotNull
	private Long parentId;

	/** *  type  id */
	@NotNull
	private Long type;
	……
}

For more verification notes, see Old language .

Spring MVC Automatic verification

It's simple , adding annotations @Valid stay Bean Parameter .

/** *  newly build  * @return */
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid T news, Model model) {
    
	System.out.println(" newly build ");
	if (result.hasErrors()) {
    
		LOGGER.info("create error!");
	}else{
    
		LOGGER.info("create ok!");
	}
	news.setService(getService());
	try {
    
		getService().create(news);
		model.addAttribute("newlyId", news.getId());
	} catch (ServiceException e) {
    
		model.addAttribute("errMsg", e.toString());
	}
	
	return "common/entity/json_cud";
}

Then talk about how to deal with errors , Or do not handle the default handover Servlet Processing can also . The following is the handler of the custom exception , Turn into JSON return .

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.ajaxjs.util.WebHelper;

/** *  Back end form 、 Exception capture of data verification  * * @author Frank Cheung<[email protected]> * */
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
    
	static final String TPL = " Input field  [%s]  Failed verification , reason  [%s], The input value is  [%s], Please check before submitting .";

	@ExceptionHandler(value = BindException.class)
	public void exceptionHandler(HttpServletRequest req, HttpServletResponse resp, BindException e) {
    
		String msg = "";
		List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

		for (FieldError err : fieldErrors) {
    
			msg += String.format(TPL, err.getField(), err.getDefaultMessage(), err.getRejectedValue());
// msg += "\\\\n";
		}

		ResponseResult result = new ResponseResult();
		result.setErrorCode("400");
		result.setMessage(msg);

		WebHelper.outputJson(resp, result.toString());
	}
}

This RestResponseEntityExceptionHandler Inject according to normal Spring Component mode is ok , Here's a way :

@Bean
RestResponseEntityExceptionHandler initRestResponseEntityExceptionHandler() {
    
	return new RestResponseEntityExceptionHandler();
}

JSR 303 You can customize the reason for the constraint , This will not output the default English , But it is troublesome to explain one by one .

There's another one getAllErrors, This is not for fields , Estimation is for Verification method .

List<ObjectError> allErrors = e.getAllErrors();
for (ObjectError err : allErrors) {
    
	msg += err.getDefaultMessage();
	msg += StringUtils.arrayToDelimitedString(err.getCodes(), ",");
}

Advanced usage

Apache BVal The function of is far more than that , You can refer to foreigners article Learn more advanced usage .

原网站

版权声明
本文为[sp42a]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071651433707.html