简体   繁体   中英

Java Servlet - using HashMap to store User then saving to file and reading

I've got an User class where I store a login, password and email (all of these are Strings).

I've got also a register.jsp site, where people can register. After completing the form, I send all data to registerServlet and I wanted to store all in HashMap, but Im not sure if it's good idea.

I created a HashMap looking like this:

HashMap <String, User> hash_map = new HashMap<String,User>();

Is it a good idea?

String login = (String)request.getParameter("login");
String password = (String)request.getParameter("password");
String email= (String)request.getParameter("email");
//upper I get parameters from inputs

User user = new User(login,password,email); // User class constructor
hash_map.put(Integer.toString(id), user); // Trying to put it to hashmap
id++;
request.getRequestDispatcher("login.jsp").forward(request, response);

After putting user into HashMap, I get output like this:

[{1=User@6d7a6891}]

How can I get acces to User attributes like login, password, email?

Which is the easiest way to save it to file and read it?

I need to store users logins in file.

The return you are getting is from the toString() Object class, that prints the Class name and some memory stuff. To access your fields, you need to get your User object inside your Hash map and use the accessors:

Example:

hashmap.get(i).getLogin();

hashmap.get(i) will return the object in the index i (which is an User instance).

.getLogin() gets your field Login (I'm supposing you have created your POJO correctly.

Another option is to override the toString() method in your User Class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM