Detailed Explanation of JSP+Servlet+JavaBean Implementation of Login Web Page Example

  • 2021-07-09 09:02:06
  • OfStack

This paper describes the method of JSP+Servlet+JavaBean to login web pages. Share it for your reference. The details are as follows:

There are four files involved here:

1. Login page: login. html
2. Welcome page for successful login: login_success. jsp
3. Login Failure Page: login_failure. jsp
4. Servlet processing file: LoginServlet. java

In fact, there is also a file involved: web. xml, which will be discussed later:

These files are described below:

1. Login page: login. html


<!--  The Login The page is 1 Simple login interface  -->
<!--
  The JSP The program is used to test and compare with MySQL Database connection, 
  Need 1 Databases: LearnJSP , and among them 1 Tables: userinfo
  There are two fields in the table: UserName varchar (20) not null,UserPwd varchar (20) not null
-->
<html>
 <head>
  <title> Login </title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta http-equiv="Content-Language" content="ch-cn">
 </head>
 <body>
 <!-- Form  Used to extract the information filled in and submitted by the user -->
 <form method="post" name="frmLogin" action="LoginServlet">
  <h1 align="center"> User login </h1><br>
  <div align="center"> User name: 
   <input type="text" name="txtUserName" value="Your name"
    size="20" maxlength="20"
    onfocus="if(this.value=='Your name')this.value='';"><br> Password: 
   <input type="password" name="txtPassword" value="Your password"
    size="20" maxlength="20"
    onfocus="if(this.value=='Your password')this.value='';"><br>
   <input type="submit" name="Submit"   value=" Submit " onClick="validateLogin();" >
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <input type="reset" name="Reset" value=" Reset "><br>
  </div>
 </form>
 <!-- javaScript  Function  validateLogin(), Used to verify that the username and password are empty  -->
  <script language="javaScript">
   function validateLogin()
   {
   var sUserName = document.frmLogin.txtUserName.value;
   var sPassword = document.frmLogin.txtPassword.value;
   if( sUserName=="" )
   {
    alert(" Please enter the user name! ");
    return false;
   }
   if( sPassword=="" )
   {
    alert(" Please enter the password! ");
    return false;
   }
   }
  </script>
 </body>
</html>

2. Welcome page for successful login: login_success. jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <title>My JSP 'login_failure.jsp' starting page</title>
 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 </head>
 <body>
 <%
  String userName = (String)session.getAttribute ( "UserName" );
 %>
 <div align=center>
  <%=userName%>
   Welcome, login is successful! 
 </div>
 </body>
</html>

3. Login Failure Page: login_failure. jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <title>My JSP 'login_failure.jsp' starting page</title>
 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 </head>
 <body>
 <%
 String userName = (String)session.getAttribute ( "UserName" );
 %>
 <div align=center>
  <%=userName%>
   Sorry, login failed! 
 </div>
 </body>
</html>

4. Servlet processing file: LoginServlet. java


/**
 *  The JSP The program is used to test and compare with MySQL Database connection, 
 *  Need 1 Databases: LearnJSP , and among them 1 Tables: userinfo
 *  There are two fields in the table: UserName varchar (20) not null,UserPwd varchar (20) not null
 */
package zieckey.login.servlet;
import java.sql.Statement;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet implements Servlet
{
 public LoginServlet ()
 {
 // TODO Auto-generated constructor stub
 }
 /*
 * (non-Javadoc)
 *
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 * javax.servlet.http.HttpServletResponse)
 */
 @Override
 protected void doGet ( HttpServletRequest arg0, HttpServletResponse arg1 )
  throws ServletException, IOException
 {
 }
 /*
 * (non-Javadoc)
 *
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 * javax.servlet.http.HttpServletResponse)
 */
 @Override
 protected void doPost ( HttpServletRequest request, HttpServletResponse response )
  throws ServletException, IOException
 {
 response.setContentType ( "text/html" );
 String result = "";
 //  Get User Name 
 String sUserName = request.getParameter ( "txtUserName" );
 if ( sUserName == "" || sUserName == null || sUserName.length ( ) > 20 )
 {
  try
  {
  result = " Please enter a user name (no more than 20 Characters)! ";
  request.setAttribute ( "ErrorUserName", result );
  response.sendRedirect ( "login.html" );
  } catch ( Exception e )
  {
  }
 }
 //  Get the password 
 String sPasswd = request.getParameter ( "txtPassword" );
 if ( sPasswd == "" || sPasswd == null || sPasswd.length ( ) > 20 )
 {
  try
  {
  result = " Please enter your password (no more than 20 Characters)! ";
  request.setAttribute ( "ErrorPassword", result );
  response.sendRedirect ( "login.html" );
  } catch ( Exception e )
  {
  }
 }
 //  Registration JDBC Driver 
 try
 {
  Class.forName ( "org.gjt.mm.mysql.Driver" ).newInstance ( );
 } catch ( InstantiationException e )
 {
  // TODO Auto-generated catch block
  e.printStackTrace ( );
  System.out.println ("InstantiationException");
 } catch ( IllegalAccessException e )
 {
  // TODO Auto-generated catch block
  e.printStackTrace ( );
  System.out.println ("IllegalAccessException");
 } catch ( ClassNotFoundException e )
 {
  // TODO Auto-generated catch block
  e.printStackTrace ( );
  System.out.println ("ClassNotFoundException");
 }
 //  Connection parameters and Access Different 
 String url = "jdbc:mysql://localhost/LearnJSP";
 //  Establish a connection 
 java.sql.Connection connection = null;
 Statement stmt = null;
 ResultSet rs = null;
 try
 {
  connection = DriverManager.getConnection ( url, "root", "011124" );
  stmt = connection.createStatement ( );
  // SQL Statement 
  String sql = "select * from userinfo where username='" + sUserName
   + "' and userpwd = '" + sPasswd + "'";
  rs = stmt.executeQuery ( sql );//  Return query results 
 } catch ( SQLException e )
 {
  // TODO Auto-generated catch block
  e.printStackTrace ( );
 }
 try
 {
  if ( rs.next ( ) )//  If the recordset is not empty, it indicates that there is a matching username and password, and the login is successful 
  {
  //  After successful login, the sUserName Set to session Variable UserName
  //  So that you can pass in the back  session.getAttribute("UserName")  To get the user name, 
  //  At the same time, it can also be used as the basis for judging whether users log in or not 
  request.getSession ( ).setAttribute ( "UserName", sUserName );
  response.sendRedirect ( "login_success.jsp" );
  } else
  {
  //  Otherwise login fails 
  //response.sendRedirect ( "MyJsp.jsp" );
  response.sendRedirect ( "login_failure.jsp" );
  }
 } catch ( SQLException e )
 {
  // TODO Auto-generated catch block
  e.printStackTrace ( );
 }
 try
 {
  if ( null!=rs )
  {
  rs.close ( );
  }
  if ( null!=stmt )
  {
  stmt.close ( );
  }
  if ( null!=connection )
  {
  connection.close ( );
  }
 } catch ( SQLException e )
 {
  // TODO Auto-generated catch block
  e.printStackTrace ( );
 }
 }
 /**
 *
 */
 private static final long serialVersionUID = 1L;
}

In order to make this website run normally, you have to register 1 in web. xml.
The contents of this document are now revised as follows:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <servlet>
  <display-name>LoginServlet</display-name>
  <servlet-name>LoginServlet</servlet-name>
  <servlet-class>zieckey.login.servlet.LoginServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>LoginServlet</servlet-name>
  <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>
</web-app>

Ok, these files can form our login interface.

Precautions:

1. Document directory form

login. html, login_success. html and login_failure. html are placed in the same directory.
LoginServlet. java the bytecode file for this file, LoginServlet. class, is placed in the WEB-INF/classes directory (note the jar packet order)
Now the directory form of the whole project is:
Directory for M:/Tomcat5.5/webapps/JSP_Servlet_JavaBean_Login
007-01-18 15:16 < DIR > META-INF
007-01-18 15:16 < DIR > WEB-INF
007-01-18 16:17 1,801 login.html
007-01-18 15:48 858 login_failure.jsp
007-01-18 15:40 234 login_success.html
007-01-18 15:46 781 MyJsp.jsp
007-01-18 16:12 859 login_success.jsp
Directory for M:/Tomcat5.5/webapps/JSP_Servlet_JavaBean_Login/WEB-INF
007-01-18 15:16 < DIR > classes
007-01-18 15:16 < DIR > lib
007-01-18 16:21 606 web.xml
M:/Tomcat5.5/webapps/JSP_Servlet_JavaBean_Login/WEB-INF/classes/zieckey/login/servlet
2007-01-18 16:18 3,900 LoginServlet.class

2. Other considerations

The database MySQL server program should be started first.

I hope this article is helpful to everyone's JSP programming.


Related articles: