在java spring请求体中转义引号

时间:2018-03-28 07:42:34

标签: java spring rest spring-boot

我有一个Java Spring控制器。 我想在我的请求中转义所有引号(例如,在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);
}

1 个答案:

答案 0 :(得分:1)

如果要验证控制器中的所有请求参数,可以使用自定义验证器。有关完整信息,请查看Complete Example

简要概述:

验证器实施

@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);
}

}