我的控制器中有以下GET请求:
@Controller
public class TestController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new ProfileTokenValidator());
}
@RequestMapping(value = "/more/{fromLocation:.+}/to/{toLocation:.+}", method = RequestMethod.GET)
@ResponseBody
public void copyProfile(@PathVariable @Valid String fromLocation, @PathVariable String toLocation) {
...
}
}
我有一个简单的字符串fromLocation验证器
public class ProfileTokenValidator implements Validator{
@Override
public boolean supports(Class validatedClass) {
return String.class.equals(validatedClass);
}
@Override
public void validate(Object obj, Errors errors) {
String location = (String) obj;
if (location == null || location.length() == 0) {
errors.reject("destination.empty", "Destination should not be empty.");
}
}
}
当fromLocation与toLocation相同时,我需要为case提供验证的问题。 请帮忙咨询一下,有没有办法编写验证器,它会同时检查两个参数的Get请求? 感谢。
块引用
答案 0 :(得分:0)
这是一个坏主意。我走了另一条路,在控制器中创建了一个简单的方法来验证我的参数。如果出现错误,它会抛出特殊异常,由处理程序处理。此处理程序在抛出之前返回400状态错误请求和消息。所以它的行为与自定义验证器完全相同。通过此链接http://doanduyhai.wordpress.com/2012/05/06/spring-mvc-part-v-exception-handling/
的文章提供了很大的帮助以下是我的代码:
@Controller
public class TestController {
@RequestMapping(value = "/more/{fromLocation:.+}/to/{toLocation:.+}", method = RequestMethod.GET)
@ResponseBody
public void copyProfile(@PathVariable String fromLocation, @PathVariable String toLocation) {
validateParams(fromLocation, toLocation);
...
}
private void validateParams(String fromLocation, String toLocation) {
if(fromLocation.equals(toLocation)) {
throw new BadParamsException("Bad request: locations should differ.");
}
}
@ExceptionHandler(BadParamsException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleBadParamsException(BadParamsException ex) {
return ex.getMessage();
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public static class BadParamsException extends RuntimeException {
public BadParamsException(String errorMessage) {
super(errorMessage);
}
}
}