且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Jersey REST服务中对用户进行身份验证并将其重定向到“自己的”页面

更新时间:2023-12-01 11:28:04

您对 userdata [地图] 对我来说不对。它是用户类的一部分,是非静态还是静态?
如果它是非静态的,那么每次你将 new User() ..那个地图将被初始化并且它将没有数据。因此 u1.userdata.containsKey(emailc); 将始终为false。

Your usage of userdata [Map] looks wrong to me. Is it a part of user class, is it non static or static ? If it is non static then every time you will do new User() .. that map will be initialized and it will have no data in it. Hence u1.userdata.containsKey(emailc); will be always false.

如果您使用的是hashmap一个用于开发目的的临时数据库,使其静态而不是像UserStore或某个DB访问层一样保留在不同的类中。例如:

If you are using a hashmap as a temporary database for dev purposes then, make it static rather keep it in a different class like UserStore or some DB access layer. Exmaple below:

public class UserDAO(){

private static Map<String,User> userdata = new HashMap<String,User>();
public boolean hasUser(String email){
 return userdata.contains(email);
}

public User saveUser(String email, String password ...){
//make user object save it in map and return the same
}

// more methods for delete and edit etc.

}

并在你的REST层类中使用它

And use this in your REST layer classes like this

exists = userDao.hasUser(email);

优点:


  1. 您的问题将得到解决。

  2. 稍后当您转到实际的数据库实现时,您只需要更改UserDao代码,其余的应用程序代码就可以了。 - 松耦合:)

关于使用电子邮件转发

servletResponse.sendRedirect("http://localhost:8080/MySite/{email}");  <<<< How to redirect using @FormParam("email")

仅在网址中添加电子邮件参数,如果那就是你想要的:

add the email parameter there in the url only, if thats what you want:

servletResponse.sendRedirect("http://localhost:8080/MySite/"+emailc);

更新:

看到根本的是你获得请求参数 [email,password] 。你检查它是否存在于地图中。现在你在做错的是你创建一个像这样的新用户用户u =新用户(); 然后从中获取电子邮件和密码 emailc = u.getEmail(); 。此 emailc 将始终为 null ,您的 userdata地图将总是返回 false 。您有两种选择:

See the fundamental thing is that you get request parameters [email , password]. You check it whether it is present in map or not. Now what you are doing wrong here is you create a new user like this User u = new User(); and then get email and password from it emailc = u.getEmail();. This emailc will always be null and your userdata map will always return false for that. You have two choices :


  1. 在用户对象中设置电子邮件和密码,然后从用户对象获取数据。

  2. 使用从请求参数获取的电子邮件和密码作为逻辑。不要改变它们

编程时要遵循的一个好习惯是始终将方法参数视为最终参数。

更新2:

if(mypass==pass){
                checked=true;
            }else{
                checked=false;
            }

更改 == 等于方法。 字符串匹配应该由等于 equalsIgnoreCase 方法来完成==。

Change == to equals method. String matching should be done by equals or equalsIgnoreCase method not ==.