如何设置和检查cookie与JAX-RS? [英] How to set and check cookies wih JAX-RS?

查看:264
本文介绍了如何设置和检查cookie与JAX-RS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个noobie与RESTful API,我正在尝试建立一个登录服务,其中我提供一个电子邮件和密码,如果验证成功 - 存储一个cookie。
此外,如何检查cookie(如果存储)?

I am a noobie with RESTful API and I am trying to build a Login service in which I provide an email and password and if the validation is successful - to store a cookie. In addition, how do I check the cookie(if stored)?

如何实现?

@Path("/login")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON})
public Response Login(final String i_LoginDetails) throws JSONException {
    final JSONObject obj = new JSONObject(i_LoginDetails);
    try {
        if (isValidUser(obj.getString("email"), obj.getString("password"))) {
            // Set a cookie
        } else {
            // return error invalid-credentials message
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Response.ok("TEST").build();
}

如何检查cookie(如果设置)?

And how do I check the cookie(if set)?

推荐答案

您可以执行以下操作:


  • p>储存新的Cookie:
  • To store a new cookie:

@GET
@Path("/login")
@Produces(MediaType.TEXT_PLAIN)
public Response login() {
    NewCookie cookie = new NewCookie("name", "123");
    return Response.ok("OK").cookie(cookie).build();
}


  • 检索cookie( javax。 ws.rs.core.Cookie ):

    @GET
    @Path("/foo")
    @Produces(MediaType.TEXT_PLAIN)
    public Response foo(@CookieParam("name") Cookie cookie) {
        if (cookie == null) {
            return Response.serverError().entity("ERROR").build();
        } else {
            return Response.ok(cookie.getValue()).build();
        }
    }
    

    但是,您只能使用值:

    @GET
    @Path("/foo")
    @Produces(MediaType.TEXT_PLAIN)
    public Response foo(@CookieParam("name") String value) {
        System.out.println(value);
        if (value == null) {
            return Response.serverError().entity("ERROR").build();
        } else {
            return Response.ok(value).build();
        }
    }
    


  • 顺便说一下,您可以尝试以下代码:

    By the way, you may want to try the following code:

    @GET
    @Path("/logout")
    @Produces(MediaType.TEXT_PLAIN)
    public Response logout(@CookieParam("name") Cookie cookie) {
        if (cookie != null) {
            NewCookie newCookie = new NewCookie(cookie, null, 0, false);
            return Response.ok("OK").cookie(newCookie).build();
        }
        return Response.ok("OK - No session").build();
    }
    

    这会移除浏览器中的Cookie。行为取决于JAX-RS的实现。使用RESTEasy(JBoss AS 7.0)和Google Chrome可以正常工作。

    This removes the cookie in the browser. The behavior depends on the implementation of JAX-RS. With RESTEasy (JBoss AS 7.0) and Google Chrome works fine.

    这篇关于如何设置和检查cookie与JAX-RS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆