我有一个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);
}
答案 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);
}
}