JAX-RS @CookieParam值从请求变为另一个

问题描述 投票:1回答:1

我正在尝试制作一种将产品添加到购物车中的资源。我正在尝试将产品添加到购物车,并将购物车作为JSON字符串保存在cookie中。 (这里Cart对象有2个字段,productId和数量)

@POST
@Path("/update")
@Produces(MediaType.APPLICATION_JSON)
public Response updateShoppingCart(@CookieParam(COOKIE_NAME) javax.ws.rs.core.Cookie cookie, Cart cart) {
    NewCookie newCookie = null;
    ObjectMapper mapper = new ObjectMapper();
    if (cookie !=null){
        try {
            List<Cart> shoppingCart = mapper.readValue(cookie.getValue(), new TypeReference<List<Cart>>() {
            });
            //the case where there is already something in the shopping cart
            //...
            String jsonString = mapper.writeValueAsString(shoppingCart);
            newCookie = new NewCookie(COOKIE_NAME, jsonString,"/", "", "shopping-cart", MAX_AGE, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }else{
        List<Cart> carts = new ArrayList<>();
        carts.add(cart);
        try {
            String jsonString = mapper.writeValueAsString(carts);
            newCookie = new NewCookie(COOKIE_NAME, jsonString,"/", "", "shopping-cart", MAX_AGE, false);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    return Response.ok(newCookie).cookie(newCookie).build();
}

我第一次运行它时,cookie设置正确,例如它设置了正确的值:[{\“productId \”:1,\“quantity \”:2}]如果我添加一个id为1的产品数量2.问题是,当我第二次运行此Cookie时,Cookie收到的Cookie值不正确,在这种情况下为[{\“productId \”:1。我正在使用Postman对此进行测试,并在正文中发送带有JSON {“productId”:1,“quantity”:2}的POST请求。我究竟做错了什么?

java json java-ee cookies jax-rs
1个回答
1
投票

饼干必须放在标题中,而不是身体。就像是:

Cookie: name=value; name2=value2; name3=value3

邮递员请参阅:https://www.getpostman.com/docs/postman/sending_api_requests/cookies

更新:根据我的经验,邮递员有时不发送cookie。尝试将postman命令转换为curl命令(请参阅:https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets),然后确保curl命令在标头或-b参数中有cookie(参见:https://curl.haxx.se/docs/manpage.html

© www.soinside.com 2019 - 2024. All rights reserved.