逃生用Java春天请求主体报价(Escape quotes in java spring reque

2019-10-29 22:40发布

我有一个Java春季控制器。 我想要逃避的所有报价,我请求(消毒它在SQL查询中使用它,例如)。

有没有办法做到这一点与Spring?

例如:

@RequestMapping(method = RequestMethod.POST)
public List<String[]> myEndpoint(@RequestBody Map<String, String> params, @AuthenticationPrincipal Account connectedUser) throws Exception{
    return myService.runQuery(params, connectedUser);
}

Answer 1:

如果你想验证在控制器所有的请求参数,你可以使用自定义的验证。 对于完整的信息,请查看完整的例子

简要概述:

验证实施

@Component
public class YourValidator implements Validator {

@Override
    public boolean supports(Class<?> clazz) {
        return clazz.isAssignableFrom(YourPojoType.class);
}

@Override
    public void validate(Object target, Errors errors) {
        if (target instanceof YourPojoType) {
           YourPojoType req = (YourPojoType) target;
           Map<String, String> params = req.getParams();
           //Do your validations.
           //if any validation failed, 
           errors.rejectValue("yourFieldName", "YourCustomErrorCode", "YourCustomErrorMessage");
        }
    }
}

调节器

@RestController
public class YourController{

   @Autowired
   private YourValidator validator;

   @RequestMapping(method = RequestMethod.POST)
   public List<String[]> myEndpoint(@Valid YourPojoType req, BindingResult result, @AuthenticationPrincipal Account connectedUser) throws Exception{

    if (result.hasErrors()) {
       //throw exception
    }
    return myService.runQuery(params, connectedUser);
} 

@InitBinder
private void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}

}



文章来源: Escape quotes in java spring request body