java spring请求正文中的转义引号 [英] Escape quotes in java spring request body
本文介绍了java spring请求正文中的转义引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Java Spring 控制器.我想转义我的请求中的所有引号(例如在 SQL 查询中使用它来清理它).
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).
有没有办法用 Spring 做到这一点?
Is there a way to do that with Spring ?
示例:
@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
简要概述:
@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);
}
}
这篇关于java spring请求正文中的转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文