This article shares the JavaWeb login function method for your reference. The specific content is as follows
First of all, we need the basic process of JavaWeb login: send requests on JSP page -> Servlet -> Servlet gets data from the database by calling methods and returns the result to the page.
We first create three jsp pages, including login.jsp (login page), index.jsp (displays the information after login success), and error.jsp (page that fails to login). The contents of the last two pages can be written at will, and the main contents of the login.jsp page are as follows:
<form action="LoginServlet" method="post"> Username:<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" (at the same time, don't forget to set the encoding format of the development tool, otherwise the jsp page will display garbled code)
Based on the two attributes of username and password, we create corresponding entity classes 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; }} The action="LoginServlet" in the jsp page refers to sending a request to the Servlet for processing. Next we go to Servlet to process:
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;//It is a Servlet instead of Class when created. It needs to be configured in web.xml. The configured code Myeclipse will automatically generate public class LoginServlet extends HttpServlet { //Create UserDao object to facilitate querying the database UserDao userDao=new UserDao(); //The following doGet methods and doPost methods correspond to method="get" and method="post" in the form form respectively public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Use the getParameter method to get the value entered in the foreground text box, where the content in the brackets is the name attribute in the <input/> tag String userName=request.getParameter("userName"); String password=request.getParameter("password"); //Call the getSelect method in UserDao and get the return value boolean flag=userDao.getSelect(userName, password); //Forward to the index.jsp page if (flag) { request.getRequestDispatcher("index.jsp").forward(request, response); } else response.sendRedirect("error.jsp"); }} What I have already said in the comments is very clear, so I won’t repeat it anymore. You can look at lines 26 and lines 29, of which 26 are forwarding and 29 are redirecting. Interested friends can check the difference between the two. The rest part is the query operation about the database that we mentioned before. We called it on line 23, and the following method we completed 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 { //Connecting the database public Connection getCon() { //Database connection name String username="root"; //Database connection password String password=""; String driver="com.mysql.jdbc.Driver"; //Where 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 querying, if there are data that meets the conditions, it returns 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 query method userName and password obtained from the jsp page to determine whether the user with this username and password exists in the database. If it exists, it returns true, otherwise it returns false (don't forget to import the package linked to the database).
As for the fields in the database, you can just use the entity class User to create it, that is, you include two attributes: userName and password. If you have any questions about the database link, please refer to the previous essay about the database part.
Finally, let’s 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 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>
The <servlet-name> in <servlet> can be written at will, just make sure that the upper and lower parts are the same.
Then there is the path of the servlet defined by yourself (including the package name), and finally <url-pattern>. The contents inside can also be written at will, but the action attribute of the form form in the jsp page must be the same as this name (the action does not contain "/")
Finally, we need to publish the web project to tomcat and then enter: http://localhost:8080/project name/login.jsp in the browser to access and log in.
This is just a simple application, and the purpose is to help all friends understand the basic process of jsp+servlet development. Of course, we will perform more detailed segmentation in the actual development process, including interfaces, implementation classes, etc.