java web jsp實現登錄功能

1.jsp實現登錄

思維過程:
1.index.jsp登錄界面
2.提交跳轉到a.jsp密碼匹配檢查
3.密碼正確就跳轉到登陸後界面

Index.jsp代碼:

<%--
  Created by IntelliJ IDEA.
  User: 張川
  Date: 2020/4/30
  Time: 14:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>form表單交互練習</title>
    <style>
      .btn-submit{
        padding: 0 16px;
        font-size: 16px;
        color: #fff;
        border: none;
        border-radius: 4px;
        white-space: nowrap;
        background-color: #ca0c16;
        cursor: pointer;
      }
    </style>
  </head>
  <body>

  <form  method="post"  action="a.jsp"  class="form-login">
    請輸入姓名: <input type="text" name="username"><br>
    請輸入密碼: <input type="text" name="password"><br>
    <input  class="btn-submit" type="submit" value="提交" >
  </form>

<%--  action表示接收數據的頁面
method表示請求方法  因爲是修改數據 一般是post
name是後臺request.getParmter("uername")的參數
--%>
  </body>
</html>

image

a.jsp代碼:

<%--
  Created by IntelliJ IDEA.
  User: 張川
  Date: 2020/5/9
  Time: 21:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page import="java.sql.*"    contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>從index獲取數據</title>

</head>
<body>
<%
    //獲取前端index的登錄數據
    request.setCharacterEncoding("UTF-8");//編碼一定設置
    String username=(String)request.getParameter("username");
    String password=(String)request.getParameter("password");//取出login.jsp的值
/**
 * 查詢獲得多條數據
 * */
//1.將Driver驅動加載進jvm
    Class.forName ("com.mysql.jdbc.Driver");
    //數據庫鏈接地址 格式 jdbc:mysql:數據庫網址/數據庫名
    String url="jdbc:mysql://localhost:3306/javaweb_learning";
    String user="root";
    String pwd="123456";
    Connection cnn=null;
    Statement st = null;

    try {
        //2.創建鏈接對象
        cnn = (Connection) DriverManager.getConnection (url, user, pwd);
        //3。創建sql語句

        String sql = "select * from user where name=" + "'" + username + "'";//定義一個查詢語句
        System.out.println (sql);
        //創建鏈接管道
        st = cnn.createStatement ();
        //4.執行sql語句
        ResultSet res=st.executeQuery(sql);//運行上面的語句
        String password2 = null;
        while (res.next ()){
            password2=res.getString ("password");

        }
        System.out.println (password2);
        if (password.equals (password2)) {
            response.sendRedirect ("logined.jsp");

        } else {
            out.print ("<script language='javaScript'> alert('密碼錯誤');</script>");
            response.setHeader ("refresh", "0;url=index.jsp");
        }
    }catch (Exception e){

    }
    %>


</body>
</html>

注意:密碼正確是跳轉頁面使用的是:

if (password.equals (password2)) {
            response.sendRedirect ("logined.jsp");

}

2.密碼正確就返回logined.jsp

登陸後:
image

密碼錯誤的話:

image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章