简体   繁体   English

Java Spring Request正文中的转义引号

[英]Escape quotes in java spring request body

I have a Java Spring controller. 我有一个Java Spring控制器。 I want to escape all quotes in my request (sanitize it for using it in SQL queries for example). 我想对请求中的所有引号进行转义(例如,将其用于SQL查询中进行消毒)。

Is there a way to do that with Spring ? 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);
}

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM