如何使用登录/身份验证功能创建基本泽西RESTful CRUD示例

时间:2013-06-17 11:35:09

标签: rest login jersey crud

好吧所以我已经做了基本的休息示例,现在我想在我的示例中使用身份验证(用户登录)更进一步。

我只使用Java Collection来获取数据。没有数据库!!

我将用户数据存储在地图中,其中电子邮件是密码的关键!!

但是我被困在基本身份验证部分,其中表单请求被发布到我的rest -post方法,其中它从用户获取值...这样的事情:

@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED,
        public void newUser(
        @FormParam("email") String email,
        @FormParam("password") String password,@ContextHttpServletResponse servletResponse
) throws IOException {

    // Form Processing algo
if(emailexists){
servletResponse.sendRedirect("http://localhost:8080/xxx/LoginFailed.html");
  }
else{
    servletResponse.sendRedirect("http://localhost:8080/xxx/UserHomPage.html");
  }    
}

不知道我做错了什么.. 此外,还只使用Java集合(如Lists,Map.etc)。

我在这里使用正确的技术,或者任何人在处置时都有更好的技术。

任何帮助将不胜感激!

我在Windows上使用apache tomcat 6 ..

在这件事上总共有一个NOOB!

1 个答案:

答案 0 :(得分:0)

要在没有数据库的情况下保存持久性数据(如用户名和密码),您应该考虑将数据保存在文本文件服务器端,并将数据读回到构造函数中的地图中。

但是,您拥有的数据越多,此过程就越昂贵。如果你有大量的用户,你真的应该考虑使用数据库,因为它们更有条理,更有效,而且更容易使用。

    @Path("myPath")
    public class MyResource {

        private static final String FILE_PATH="my/path/to/userdata.txt";

        private HashMap<String, String> _userData;

        public MyResource() {
            try {
                Scanner scanner = new Scanner(new File(FILE_PATH));
                _userData = new HashMap<String, String>();
                while(scanner.hasNext()) {
                    String[] line = scanner.nextLine().split(",");
                    _userData.put(line[0].trim(), line[1].trim());
                }
            } catch(IOException e) {
                e.printStackTrace();
            }
        }

        @POST
        @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
        public Response addNewUser(@FormParam("email") String email,
                                   @FormParam("password") String password)
                                   throws IOException {

            PrintWriter writer = new PrintWriter(new File(FILE_PATH));
            int statusCode = 200;
            // If that email already exists, don't print to file
            if(_userData.containsKey(email))
                statusCode = 400;
            else
                writer.println(email + "," + password);
            writer.close();
            return Response.status(statusCode);
        }
    }