Servlet – 登录表单
使用Java,我们可以准备用于注册/登录应用程序的优雅网页,并且在获得授权的身份验证凭据后,可以看到其余的应用程序屏幕。因此,有一个登录表单来接受用户的输入然后验证数据是非常重要的。为了验证数据,我们可以在客户端使用 javascript。即像验证强制输入(需要用户名/需要密码)/如果用户名是电子邮件模式,则需要验证输入的文本是否满足电子邮件模式等,
客户端验证结束后,将根据数据库存储的数据检查输入的凭据。此过程只能在服务器端完成。这意味着这些类型的验证需要作为请求发送到服务器,并且代码需要用 Servlet 编写。通常,由于登录表单凭据很敏感,并且在传递时应该隐藏,因此它必须作为 POST 方法发送。在本文中,让我们看看我们可以设计一个基本的登录表单并通过 servlet 进行处理。让我们看看实现此功能所需的页面
login.jsp 文件:
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Login Application
Java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
// From login.jsp, as a post method only the credentials are passed
// Hence the parameters should match both in jsp and servlet and
// then only values are retrieved properly
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// We can able to get the form data by means of the below ways.
// Form arguments should be matched and then only they are recognised
// login.jsp component names should match and then only
// by using request.getParameter, it is matched
String emailId = request.getParameter("emailId");
String password = request.getParameter("password");
// To verify whether entered data is printing correctly or not
System.out.println("emailId.." + emailId);
System.out.println("password.." + password);
// Here the business validations goes. As a sample,
// we can check against a hardcoded value or pass
// the values into a database which can be available in local/remote db
// For easier way, let us check against a hardcoded value
if (emailId != null && emailId.equalsIgnoreCase("admin@gmail.com") && password != null && password.equalsIgnoreCase("admin")) {
// We can redirect the page to a welcome page
// Need to pass the values in session in order
// to carry forward that one to next pages
HttpSession httpSession = request.getSession();
// By setting the variable in session, it can be forwarded
httpSession.setAttribute("emailId", emailId);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}
}
}
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Welcome <%=session.getAttribute("emailId") %>
HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Login Application