Escape quotes in java spring request body

2019-08-22 01:50发布

I have a Java Spring controller. I want to escape all quotes in my request (sanitize it for using it in SQL queries for example).

Is there a way to do that with Spring ?

Example :

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

1条回答
三岁会撩人
2楼-- · 2019-08-22 02:18

If you want to validate all your request parameters in controllers, you can use custom validators. For Complete info, check Complete Example

Brief Overview:

Validator Implementation

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

Controller

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

}

查看更多
登录 后发表回答