Bean验证无效

时间:2015-01-29 16:15:09

标签: spring validation rest cxf javabeans

我有一个Reservation服务,使用请求 - 响应和DAO模式进行预订。我正在尝试使用Spring构建一个简单的REST API,允许我创建,搜索,编辑和删除有关预订的信息。信息通过JSON发送和返回。问题是我正在尝试使用Bean Validation,服务似乎完全忽略它。

Reservation.java

package org.prueba01.model;

import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

public class Reservation {

    private int id;

    @NotNull(message="El nombre es obligatorio.")
    @NotEmpty(message="El nombre no puede estar vacio.")
    private String name;

    @NotNull(message="Es obligatorio indicar el numero de personas.")
    @NotEmpty(message="El numero de personas no puede estar vacio.")
    @Length(min=1, max=15, message="El numero de personas debe ser entre 1 y 15.")
    private int people;

    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 int getPeople() {
        return people;
    }
    public void setPeople(int people) {
        this.people = people;
    }   

}

ReservationRequest.java

package org.prueba01.model;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;

public class ReservationRequest {

    @NotNull(message="No puede haber campos nulos.")
    @NotEmpty(message="No puede haber campos vacios.")
    @Valid
    private Reservation reservation;

    public Reservation getReservation(){
        return reservation;
    }

    public void setReserva (Reservation reservation){
        this.reservation=reservation;
    }

}

ReservationResponse.java

package org.prueba01.model;

import java.util.List;

public class ReservationResponse {

    private List<Reservation> reservations;
    private String errorMsg;    
    private boolean success=true;

    public List<Reservation> getReservations(){
        return reservations;
    }

    public void setReservations (List<Reservation> reservations){
        this.reservations=reservations;
    }

    public Boolean isSuccess(){
        return success;
    }

    public void setSuccess (boolean success){
        this.success=success;
    }

    public String getErrorMsg(){
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg){
        this.errorMsg=errorMsg;
    }

}

IReservationDao.java

package org.prueba01.reservation.dao;

import java.util.List;

import org.prueba01.model.Reservation;

    public interface IReservationDao {

        public Reservation searchReservation(int id);
        public List<Reservation> showAll();
        public void addReservation(Reservation reservation);
        public void changeReservation(Reservation reservation);
        public void cancelReservation (int id);
    }

ReservationDaoImpl.java

package org.prueba01.reservation.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.prueba01.model.Reservation;
import org.prueba01.reservation.dao.IReservationDao;

public class ReservationDaoImpl implements IReservationDao {

    private static final AtomicInteger counter = new AtomicInteger();

    List<Reservation> reservations = new ArrayList<Reservation>();

    public Reservation searchReservation (int id){
        for (Reservation reservation : reservations){
            if (reservation.getId()==id){
                return reservation;
            }
        }

        throw new RuntimeException ("Reserva con el id " +id + " no encontrada!");
    }

    public List<Reservation> showAll(){
        return reservations;
    }

    public void addReservation (Reservation reservation){
        reservations.add(reservation);
        reservation.setId(counter.getAndIncrement());

    }

    public void changeReservation (Reservation reservation){
        Reservation reservationToChange = searchReservation(reservation.getId());

        reservationToChange.setId(reservation.getId());
        reservationToChange.setName(reservation.getName());
        reservationToChange.setPeople(reservation.getPeople());
    }

    public void cancelReservation(int id){
        Reservation reservationToCancel = searchReservation(id);        
        reservations.remove(reservationToCancel);
    }
}

ReservationManager.java

package org.prueba01.manager;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.ws.rs.Consumes;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;

import org.hibernate.validator.constraints.NotEmpty;
import org.prueba01.model.ReservationRequest;
import org.prueba01.model.ReservationResponse;

public interface ReservationManager {

    @GET
    @Consumes("application/json")
    @Produces("application/json")
    @Path("/searchReservation/{a}")
    public ReservationResponse searchReservation(
    @PathParam ("a")
    @Pattern(regexp = "[0-9]+", message = "El id de la reserva debe ser un valor numerico.")
    int id);

    @GET
    @Produces("application/json")
    @Path("/showAll/")  
    public ReservationResponse showAll();   

    @POST
    @Consumes("application/json")
    @Produces("application/json")
    @Path("/addReservation/")
    @NotNull(message="No puede haber campos nulos.")
    @NotEmpty(message="No puede haber campos vacios.")
    @Valid
    public ReservationResponse addReservation(ReservationRequest request);

    @PUT
    @Consumes("application/json")
    @Produces("application/json")
    @Path("/changeReservation/")
    @NotNull(message="No puede haber campos nulos.")
    @NotEmpty(message="No puede haber campos vacios.")
    @Valid
    public ReservationResponse changeReservation(ReservationRequest request);

    @DELETE
    @Consumes("application/json")
    @Produces("application/json")
    @Path("/cancelReservation/{a}")
    public ReservationResponse cancelReservation(
    @PathParam ("a")        
    @Pattern(regexp = "[0-9]+", message = "El id de la reserva debe ser un valor numerico.")
    int id);

}

ReservationManagerService.java

package org.prueba01.manager.impl;

import java.util.Arrays;

import org.prueba01.manager.ReservationManager;
import org.prueba01.model.ReservationRequest;
import org.prueba01.model.ReservationResponse;
import org.prueba01.reservation.dao.IReservationDao;

public class ReservationManagerService implements ReservationManager {

    private IReservationDao reservationDao;

    public IReservationDao getReservationDao(){
        return reservationDao;
    }

    public void setReservationDao (IReservationDao reservationDao){
        this.reservationDao=reservationDao;
    }

    public ReservationResponse searchReservation(int id){
        ReservationResponse response = new ReservationResponse();

        try{
            response.setReservations(Arrays.asList(getReservationDao().searchReservation(id)));
        }

        catch (Exception e){
            response.setSuccess(false);
            response.setErrorMsg(e.getClass()+": " + e.getMessage());
        }

        return response;
    }

    public ReservationResponse showAll(){
        ReservationResponse response = new ReservationResponse();

        try {
            response.setReservations(getReservationDao().showAll());
        }

        catch (Exception e){
            response.setSuccess(false);
            response.setErrorMsg(e.getClass()+": " + e.getMessage());
        }

        return response;
    }

    public ReservationResponse addReservation(ReservationRequest request){
        ReservationResponse response = new ReservationResponse();

        try{
            getReservationDao().addReservation(request.getReservation());
        }

        catch (Exception e){
            response.setSuccess(false);
            response.setErrorMsg(e.getClass()+": " + e.getMessage());
        }

        return response;
    }

    public ReservationResponse changeReservation (ReservationRequest request){
        ReservationResponse response = new ReservationResponse();

        try{
            getReservationDao().changeReservation(request.getReservation());
        }

        catch (Exception e){
            response.setSuccess(false);
            response.setErrorMsg(e.getClass()+": " + e.getMessage());
        }

        return response;

    }

    public ReservationResponse cancelReservation (int id){
        ReservationResponse response = new ReservationResponse();

        try{
            getReservationDao().cancelReservation(id);
        }

        catch (Exception e){
            response.setSuccess(false);
            response.setErrorMsg(e.getClass()+": " + e.getMessage());
        }

        return response;
    }

}

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.pruebas</groupId>
  <artifactId>prueba01</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>prueba01 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.neethi</groupId>
        <artifactId>neethi</artifactId>
        <version>3.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>wsdl4j</groupId>
        <artifactId>wsdl4j</artifactId>
        <version>1.6.3</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.11</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.3.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.0-m10</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>prueba01</finalName>
  </build>
</project>

context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:cxf="http://cxf.apache.org/core"
        xmlns:jaxws="http://cxf.apache.org/jaxws"
        xmlns:jaxrs="http://cxf.apache.org/jaxrs"
        xsi:schemaLocation="
            http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

    <cxf:bus>
        <cxf:features>
            <cxf:logging/>
        </cxf:features>
    </cxf:bus>

    <bean id="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

    <bean id="reservationDao" 
        class="org.prueba01.reservation.dao.impl.ReservationDaoImpl">
    </bean>

    <bean id="reservationManagerService" 
        class="org.prueba01.manager.impl.ReservationManagerService">
        <property name="reservationDao" ref="reservationDao"/>
    </bean>

    <bean id="jsonProvider" 
        class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>

    <jaxrs:server id="reservationManagerDao" address="/rest/ReservationManager">
        <jaxrs:serviceBeans>
            <ref bean="reservationManagerService"/>
        </jaxrs:serviceBeans>
        <jaxrs:providers>
            <ref bean='jsonProvider' />
        </jaxrs:providers>
    </jaxrs:server>

</beans>

的web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    metadata-complete="true">

    <display-name>Rest Test</display-name>
    <description>Rest Test</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</web-app>

我尝试过Apache 7和8个版本。请求通过

进行
  

本地主机:8080 / prueba01 /服务/休息/ ReservationManager / REST_CALL

所有这些似乎都很好。但是,如果我尝试测试任何Bean验证;例如,发送POST请求

  

本地主机:8080 / prueba01 /服务/休息/ ReservationManager / addReservation

部分为空的JSON,如

  

{ “预订”:{ “人”: “3”}}

该服务正常工作,它为“name”值引入了一个空值,而不是使服务崩溃。任何想法为什么会发生这种情况?

注意1:我还将cxf-2.7.6 jar添加到我的lib文件夹中,因为我无法通过Maven使用它,不知道为什么。

注意2:我还没有尝试过处理Bean Validation Exceptions,因为我只是想确保它们暂时发生。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您是否尝试过遵循CXF提供的ValidationFeature文档? 也许这可以解决你的问题: http://cxf.apache.org/docs/validationfeature.html#ValidationFeature-CommonBeanValidation1.1Interceptors

另一种解决方案是使用Validator手动验证请求。如果第一个解决方案无效,我可以为您提供一个示例。

祝你有个美好的一天。