JAX-RS 和 AngularJS 之间的请求和响应

Request and response between JAX-RS and AngularJS

嗨,我有一个简单的休息服务:

    @POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Product createProduct(Product product) {
    if (!(productDao.findByName(product.getProductName()).isEmpty())) {
                //?????
    } else {
        productDao.create(product);
                //?????
    }
    return product;
}

当输入名称不正确且方法 findByName return 不为空时,我希望 return 从我的其余服务方法到 angular 只有信息,示例 "Product exist"。当方法 findByName return null 和产品被创建时,我希望 return Product 从我的方法到 Angular 控制器。怎么处理? Return实体和信息?

我在 angular 控制器中处理什么?当我 return 实体时,下面的控制器工作正常,但我现在不处理信息 "Product exist" 而不是实体?

            $scope.addProduct = function (product) {
            $http.post(serviceURI + "products", product).success(function (data) {
                $scope.products.push(data);
                $('.success-message').fadeIn(1000).delay(5000).fadeOut(1000);
                $scope.message = "Product added";
            }).error(function (error) {
                $('.error-message').fadeIn(1000).delay(5000).fadeOut(1000);
                $scope.message = "Error";
            });
        }

从 JAX-RS return 数据和信息并在 Angular 控制器中获取数据和信息的最佳做法是什么?

由于 RESTFul 网络服务使用 HTTP 词汇,我建议 return 根据您的操作结果使用不同的 HTTP 状态代码。

在第一种情况下,您可以抛出带有 4xx 系列状态代码的 WebApplicationException

在第二种情况下,您可以使用默认状态代码(我认为在本例中为 200)或通过 returning a [= 提供更具体的状态代码,例如 201(已创建) 11=] 对象而不是直接使用 Product。 例如。 Response.created 可能对你有帮助。

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

在我的例子中,当响应正常时,我使用 JAX-RS 作为输入,使用 Gson 作为输出,因为我需要操作日期 (long/Calendar) 并且使用 Gson 很容易添加适配器。当响应不正常时,我return一个状态错误代码。

 @POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Product createProduct(Product product) {
    try {
        Gson gson = new GsonBuilder()
        //.registerTypeAdapter(Calendar.class, new CalendarSerializer())
        //          .registerTypeAdapter(Calendar.class, new CalendarDeserializer())
        //          .registerTypeAdapter(GregorianCalendar.class,
        //                  new CalendarSerializer())
                            .create();

        String json = null;

        //do something

        json = gson.toJson(product);
        return Response.ok(json, MediaType.APPLICATION_JSON).build();


        }catch (IllegalArgumentException ex){
            return Response.serverError().status(Status.BAD_REQUEST).build();

        }catch (Exception ex) {
            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
        }
        finally{
    }
}

AngularJs 的客户:

.success (function(data) {
        //ok -> get data

})
.error (function(resp) {
    if (resp.errorCode == 400){
        ...
    }
    ...
    ...
}