jsp built in object login cookie + session

Posted by daynah on Tue, 03 Dec 2019 18:49:28 +0100

Summary

Two pages in total
When accessing the product list directly, it will judge whether the user is logged in. If the user is not logged in, it will jump for 3 seconds
If the user logs in, there is no jump
Login page: for login page, enter user name and password directly. Compare with database to login
And save the password locally

ps usually needs to save password encryption locally

The code is as follows

configuration file

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>login</servlet-name>
    <jsp-file>/Login.jsp</jsp-file>
    <init-param>
      <param-name>driver</param-name>
      <param-value>com.mysql.cj.jdbc.Driver</param-value>
    </init-param>
    <init-param>
      <param-name>url</param-name>
      <param-value>jdbc:mysql://47.94.95.84:32786/test</param-value>
    </init-param>
    <init-param>
      <param-name>user</param-name>
      <param-value>test</param-value>
    </init-param>
    <init-param>
      <param-name>password</param-name>
      <param-value>**</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login.html</url-pattern>
  </servlet-mapping>
</web-app>

Login interface

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.DriverManager" %><%--
  Created by IntelliJ IDEA.
  User: ming
  Date: 19-3-13
  Time: 10 p.m.:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login page</title>
</head>
<form action="./login.html" method="post">
    <input type="text" name="username" id="username"/>
    <input type="password" name="password" id="password"/>
    <input type="submit" value="submit"/>
</form>
<script>
    // js script, read client's cookie
    let cookie = {};
    let all = document.cookie;
    let list = all.split(";");
    for(let i = 0; i < list.length; i++){
        let p = list[i].indexOf("=");
        let space = list[i].indexOf(" ");
        let name = list[i].substring(space + 1, p);
        let value = list[i].substring(p+1);
        value = decodeURIComponent(value);
        cookie[name]=value;
    }
    // Fill to value
    if(cookie["flage"] == "true") {
        document.getElementById("username").setAttribute("value", cookie["user"]);
        document.getElementById("password").setAttribute("value", cookie["password"]);
    }
</script>
<body>
<%
    String dbdriver = config.getInitParameter("driver");
    String dburl = config.getInitParameter("url");
    String dbuser = config.getInitParameter("user");
    String dbpassword = config.getInitParameter("password");
    // Connection object
    Connection connection = null;
    // operation
    PreparedStatement preparedStatement = null;
    // Result
    ResultSet resultSet = null;
    // User id
    String mid = null;
    // Flag bit
    boolean falge = false;
    try{
        Class.forName(dbdriver);
        // Get connected
        connection = DriverManager.getConnection(dburl, dbuser, dbpassword);
        // Write sql verification ID password
        String sql = "SELECT mid FROM member WHERE name = ? AND password = ?";
        // Instantiate operands
        preparedStatement = connection.prepareStatement(sql);
        // Set query content
        preparedStatement.setString(1, request.getParameter("username"));
        preparedStatement.setString(2, request.getParameter("password"));
        // Execution query
        resultSet = preparedStatement.executeQuery();
        // If it can be found, it means legal user
        if(resultSet.next()){
            mid = resultSet.getString(1);
            // Modify flag bit
            falge = true;
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try{
            resultSet.close();
            preparedStatement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    // Determine whether the login is successful
    if(falge){
        // Login successfully
        // Save session save cookie
        session.setAttribute("mid", mid);
        // Save cookie
        Cookie cookieMid = new Cookie("mid", mid);
        Cookie cookieUser = new Cookie("user", request.getParameter("username"));
        Cookie cookiePassword = new Cookie("password", request.getParameter("password"));
        // Add login cookie
        Cookie cookieFlage = new Cookie("flage", "true");
        // Client add Cookie
        response.addCookie(cookieMid);
        response.addCookie(cookieUser);
        response.addCookie(cookiePassword);
        response.addCookie(cookieFlage);
        // Set timing jump
        response.setHeader("refresh", "3;URL=product.jsp");
        %>
            //Login success will jump to the homepage product interface
            //Click here without skipping</a>
        <%
    }else{
        // Query whether the user has logged in
        if(session.getAttribute("mid") == null) {
            Cookie cookieFlage = new Cookie("flage", "false");
            response.addCookie(cookieFlage);
        }
    }
%>
</body>
</html>

Product interface

<%--
  Created by IntelliJ IDEA.
  User: ming
  Date: 19-3-14
  Time: 2 p.m.:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
//This is a list of products
<script>
    // Judge current login status
    // js script, read client's cookie
    let cookie = {};
    let all = document.cookie;
    let list = all.split(";");
    for(let i = 0; i < list.length; i++){
        let p = list[i].indexOf("=");
        let space = list[i].indexOf(" ");
        let name = list[i].substring(space + 1, p);
        let value = list[i].substring(p+1);
        value = decodeURIComponent(value);
        cookie[name]=value;
    }
    // Get login status
    if(cookie["flage"] != "true"){
        // Logon status
        alert("Please log in for 3 seconds and you will jump");
    }
</script>
<%
    // Server side authentication
    if(session.getAttribute("mid") == null) {
        // Execute page Jump
        response.setHeader("refresh", "2;URL=/login.html");
    }
%>
</body>
</html>

Be careful

The product interface is verified by local cookie and server session

Topics: Java SQL Session JSP