gpt4 book ai didi

java - java spring请求体中的转义引号

转载 作者:行者123 更新时间:2023-12-02 11:27:17 25 4
gpt4 key购买 nike

我有一个 Java Spring Controller 。我想转义请求中的所有引号(例如,对其进行清理以便在 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);
}

最佳答案

如果您想验证 Controller 中的所有请求参数,您可以使用自定义 validator 。有关完整信息,请查看 Complete Example

简要概述:

validator 实现

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

}

关于java - java spring请求体中的转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49528750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com