当前位置:网站首页>Servlet connects to database to realize user login function

Servlet connects to database to realize user login function

2022-06-12 15:14:00 xiaoweiwei99

Make a small case and review it by the way jdbc Knowledge

One 、 demand :

The user enters the user name and password in the browser , If there is data in the database , Remind the user that the login is successful , If there is no data , Remind the user to log in again

Two 、 Just to review JDBC, I forgot some details when I used it today , Knowledge still needs to be reviewed many times , It doesn't mean that learning is your own .

1. summary :

use java A technique by which a program operates a database , yes java A set of standards for connecting programs to databases , It's essentially a bunch of API.

2. Development steps :

2.1. guide jar package :

about java project , Direct will jar The package is copied to the project and then parsed jar(add as library) You can use it ; about web project , Need to put jar Put the bag in tomcat Of lib Objective c Record , stay web In the project , When Class.forName(“com.mysql.jdbc.Driver”); when idea It doesn't look for strings , I won't look for drivers . So just put mysql-connector-java-5.1.7-bin.jar copy to tomcat Next lib The catalogue will do . There is a problem here today , Find this solution .

2.2. step : The specific steps are in the code

Registration drive —>

Class.forName(“com.mysql.jdbc.Driver”);

Get the connection —>

String url = “ agreement ://IP Address : Port number / Database name /”;
String url = “jdbc:mysql://localhost:3306/person”;
Connection c = DriverManager.getConnection(url, “root”, “root”);

Write sql sentence —>

String sql = "select * from user where name = and pwd = ";

Get the transmitter —>

PreparedStatement preparedStatement = connection.prepareStatement(sql);

Set the value —>

preparedStatement.setObject(1,username);
preparedStatement.setObject(2,pwd);

Get the result set —>

ResultSet resultSet = preparedStatement.executeQuery();

Parse the result set —>

resultSet.next()

3、 ... and 、 Code implementation :

1. Login interface code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> User login interface </title>
</head>
<body>
<h3 style="text-align: center"> The user login </h3>
 <form action="userLogin" method="post" style="text-align: center" >
      user name :<input type="text" name="username"><br/>
     <br/>
      The secret &nbsp;&nbsp;&nbsp;&nbsp; code :<input type="password" name="pwd"><br/>
     <br>
     <input type="submit" value=" Submit ">
 </form>
</body>
</html>

2. Login success screen :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Successful login interface </title>
</head>
<body>
<h1>  Congratulations on login success !!!</h1>
</body>
</html>

3.servlet Code :

package cn.tedu;

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 java.io.IOException;
import java.sql.*;
// Configure access path 
@WebServlet(urlPatterns = "/userLogin")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Solve the Chinese garbled code 
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");
        //2. Get the name and password entered by the user 
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //3. Connect to database 
        try {
            //3.1 Registration drive 
            Class.forName("com.mysql.jdbc.Driver");
            //3.2 Get the connection 
            String url = "jdbc:mysql://localhost:3306/person";
            connection = DriverManager.getConnection(url,"root","root");
            //3.3 Write sql
            String sql = "select * from user where name = ? and pwd = ?";
            //3.4 Get the transmitter 
            preparedStatement = connection.prepareStatement(sql);
            //3.5 Set the value 
            preparedStatement.setObject(1,username);
            preparedStatement.setObject(2,pwd);
            //3.6 Return result set 
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                // relocation , If the result returns true," Jump " To success.html
                response.sendRedirect("success.html");
            }else{
                String urls = "login.html";
                response.getWriter().write(" The user doesn't exist "+""+"<a href = '"+urls+"'> Click login again </a>");
            }

        } catch (Exception e) {
            e.printStackTrace();
            //3.6 close resource 
        }finally {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

4. Database data

5. Login success page :

6. Login failure interface :

7. Login screen :

原网站

版权声明
本文为[xiaoweiwei99]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121512015887.html