Spring 4 Rest with Hibernate Validator不显示内联消息

时间:2015-12-09 14:15:02

标签: spring hibernate-validator

我有一个示例Spring Rest服务项目,我正在尝试实现hibernate验证器。我现在卡在向其他调用者显示错误消息。我有Spring Rest的代码,下面列出了DTO

控制器

import javax.validation.Valid;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.project.home.rest.SampleDTO;

@RestController(value = "/validator")
public class ValidatorController {

    @RequestMapping(method = RequestMethod.POST)
    public String validate(@Valid @RequestBody SampleDTO sampleDTO) {

        return "Hello User Validator Serivce in play";

    }
}

SampleDTO

public class SampleDTO {

    @NotNull
    @Min(value = 18, message = "ID must be greater than 18 characters long")
    @Max(value = 100, message = "ID must be less than 100 Characters Long")
    private int id;

    @NotNull(message = "Name is Compulsory")
    private String name;

    @Email(message = "Email address not Valid")
    @NotEmpty(message = "Email address can not be null")
    private String email;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

通过Rest Client访问Rest Service时,我确实看到400错误的请求错误,但错误消息不会被删除。 我在Tomcat控制台中遇到的错误是

ERROR: org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: public org.springframework.http.ResponseEntity<java.lang.String> com.matitech.it.advice.CentralControllerHandler.handleMethodArgumentException(java.lang.String)
java.lang.IllegalStateException: No suitable resolver for argument [0] [type=java.lang.String]
HandlerMethod details: 
Controller [com.matitech.it.advice.CentralControllerHandler]
Method [public org.springframework.http.ResponseEntity<java.lang.String> com.matitech.it.advice.CentralControllerHandler.handleMethodArgumentException(java.lang.String)]

    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:175)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:363)
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:60)
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136)
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1183)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1020)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

我还尝试了BindingResult的备用版本,但在这种情况下,我得到500内部服务器错误 修改后的代码

Controller
@RestController(value = "/validator")
public class ValidatorController {

    @RequestMapping(method = RequestMethod.POST)
    public String validate(@Valid @RequestBody SampleDTO sampleDTO, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new MethodArgumentNotValidException();
        }
        return "Hello User Validator Serivce in play";

    }
}

public class MethodArgumentNotValidException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = -7764697079393527116L;

    public MethodArgumentNotValidException() {
        super();
    }

    public MethodArgumentNotValidException(String message) {
        super(message);
    }
}

@ControllerAdvice

    public class CentralControllerHandler {


        @ExceptionHandler({MethodArgumentNotValidException.class})
        public ResponseEntity<String> handleMethodArgumentException(String message){
            return new ResponseEntity<String>(message,HttpStatus.BAD_REQUEST);
        }

    }

1 个答案:

答案 0 :(得分:1)

如果验证失败,您的RequestMapping应该抛出MethodArgumentNotValidException

 @RequestMapping(method = RequestMethod.POST)
public ResponseEntity validate(@Valid @RequestBody SampleDTO sampleDTO) {
    //this should throw a MethodArgumentNotValidException if the validation fails
    return new ResponseEntity<>("Validation successful", HttpStatus.OK)
}

创建一个这样的异常处理程序,并将验证消息返回给调用者。

@ExceptionHandler
@ResponseBody
public ResponseEntity handleValidationException(MethodArgumentNotValidException exception) {
     return new ResponseEntity<>(exception.getBindingResult(), HttpStatus.BAD_REQUEST)
}