JavaWeb login function implementation code

  • 2020-05-12 02:33:39
  • OfStack

The example of this article is to share the method of JavaWeb login function for your reference, the specific content is as follows

First we need the basic process of JavaWeb login: JSP page send request -- > Servlet - > Servlet gets the data from the database by calling the method and returns the result to the page.

We first set up three jsp pages, including login.jsp (login page), index.jsp (display information after successful login) and error.jsp (login failed page). The content of the last two pages can be written at will, while the main content of login.jsp page is as follows:


<form action="LoginServlet" method="post">
    The user name :<input type="text" name="userName"/>
    Password: <input type="password" name="password"/>
   <input type="submit" value=" submit "/>
  </form>

At the beginning of the login.jsp file, we need to change pageEncoding=" ISO-8859-1 "to pageEncoding=" utf-8" (and don't forget to set the development tool's encoding format, otherwise the jsp page will display the messy code)

According to the two attributes of user name and password, we build the corresponding entity class and add get and set methods. The code is as follows:


public class User {
 private String userName;
 private String password;
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
}

On the jsp page, action= "LoginServlet" means to send the request to Servlet for processing. Next, let's go to Servlet for processing:


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.dao.UserDao;
// Created for Servlet Rather than Class That need to be in web.xml Configuration, configuration of the code Myeclipse Will be generated automatically 
public class LoginServlet extends HttpServlet {
 // create UserDao Object in order to easily query the database 
 UserDao userDao=new UserDao();
 // The following doGet Methods and doPost Methods correspond to form In the form method="get" and method="post"
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
 }
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // using getParameter Method gets the value entered into the foreground text box, where the contents inside the parentheses are <input/> In the tag name attribute 
  String userName=request.getParameter("userName");
  String password=request.getParameter("password");
  // call UserDao In the getSelect Method and get the return value 
  boolean flag=userDao.getSelect(userName, password);
  // Forward to if username and password exist index.jsp Page, otherwise redirect to error.jsp page 
  if (flag) {
   request.getRequestDispatcher("index.jsp").forward(request, response);
  }
  else
   response.sendRedirect("error.jsp");
 }

}

You can look at lines 26 and 29, where 26 is forwarding and 29 is redirecting. Those of you who are interested can check the difference between the two. The remaining part 1 is the query operation about the database that we mentioned earlier. We made the call on line 23. Here is the method to complete the call:


package com.test.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDao {
 // The code to connect to the database 
 public Connection getCon() {
  // Database connection name 
  String username="root";
  // Database connection password 
  String password="";
  String driver="com.mysql.jdbc.Driver";
  // Among them test Is the database name 
  String url="jdbc:mysql://localhost:3306/test";
  Connection conn=null;
  try{
   Class.forName(driver);
   conn=(Connection) DriverManager.getConnection(url,username,password);
  }catch(Exception e){
   e.printStackTrace();
  }
  return conn;
 }
 // The method of the query that is returned if it contains data that meets the criteria true
 public boolean getSelect(String userName,String password) { 
  boolean flag=false;
   String sql = "select * from user where userName='"+userName+"' and password='"+password+"'"; 
   Connection conn = getCon();
   PreparedStatement pst = null;
   try {
    pst = (PreparedStatement) conn.prepareStatement(sql);
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
     flag=true;
    }
   } catch (Exception e) {
   }
   return flag;
  }
}

In this method, we first connect to the database, and then pass in the userName and password obtained from the jsp page in the query method to determine whether the user with this user name and password exists in the database. If so, we return true, otherwise we return false (don't forget to import the package linked to the database).

As for the fields in the database, please refer to the entity class User, which contains two attributes, userName and password. If there are any problems with the database link, please refer to the previous essay about the database section.

Finally, take a look at the configuration in web.xml:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <servlet>
 <servlet-name>LoginServlet</servlet-name>
 <servlet-class>com.test.servlet.LoginServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>LoginServlet</servlet-name>
 <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>
</web-app>

Among them < servlet > In the < servlet-name > You can write it any way you want, just make sure the top and bottom are the same.

And then the < servlet-class > Is the self-defined path to Servlet (including the package name), and finally is < url-pattern > , but the action property of the form form on the jsp page must have the same name (action does not include "/")

Finally, we need to publish the web project to tomcat and then type in the browser: http://localhost:8080/ project name/login.jsp to access and log in.

This is just a simple application, the purpose is to help you understand the basic process of jsp+servlet development, of course, we will carry out more refined segmentation in the actual development process, including interface, implementation class and so on.


Related articles: