Vamos a implementar un código con lo siguiente:
package com.login.web; public class Usuario { private String username; private String pass; public Usuario(String parameter, String parameter2) { this.pass = parameter2; this.username = parameter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
package com.login.web; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Hashtable; /** * Servlet implementation class InsertarUsuario */ public class InsertarUsuario extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public InsertarUsuario() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); //request.getRequestDispatcher("destino.html").forward(request, response); Hashtable<String, Usuario> usuarios = (Hashtable<String, Usuario>) request.getServletContext().getAttribute("TABLAUSUARIOS"); if(usuarios == null) { usuarios = new Hashtable<String, Usuario>(); request.getServletContext().setAttribute("TABLAUSUARIOS", usuarios); } Usuario usuario = new Usuario(request.getParameter("usuario"),request.getParameter("pass")); usuarios.put(usuario.getUsername(), usuario); System.out.println("Usuarios del sistema" + usuarios.size()); request.getRequestDispatcher("index.html").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Login</title> </head> <body> <h1>Login</h1> <form action="Login" method="loguear"> Nombre:<input type ="text" name="usuario" /><br> Clave:<input type = "text" name="pass"/><br> <input type ="submit"/> <a href="registro.html">Formulario de registro</a> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Login</title> </head> <body> <h1>Registro</h1> <form action="InsertarUsuario" method="registrar"> Nombre:<input type ="text" name="usuario" /><br> Clave:<input type = "text" name="pass"/><br> <input type ="submit"/> <a href="registro.html">Formulario de registro</a> </body> </html>