0

我的控制器中有以下 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相同时,我需要为案例提供验证的问题。请提供建议或其他帮助,有没有办法编写验证器来同时检查两个参数以获取获取请求?谢谢。

块引用

4

1 回答 1

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);
        }
    }
}
于 2012-11-23T10:37:00.400 回答