layui使用html+servlet+ajax實現登入驗證

權。發表於2021-11-19

我們一般使用的都是form表單提交到Servlet來實現前端和後端的互動的。這次我使用的是ajax提交資料,實現登入操作。

首先我們需要的是一套layui模板,這裡用到layui的js和css介面。

第一步自己建立資料表,這裡只需要username 和password。我使用的是主要使用的是mysql。

這邊是我的工程目錄,來看一下我的目錄結構吧。

 

 這裡就主要寫一下servlet和前端html的互動。

Servlet

login.java

package com.Serlvet;

import com.Bean.User;
import com.Dao.mannger;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name ="login", value = "/login")
public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action=request.getParameter("action");//action'是html傳來的一個欄位
        if(action.equals("doLogin")){
            doLogin(request,response);
        }
    }
protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");//設定相應的文字型別
    response.setContentType("text/html;charset=utf-8");//設定響應型別,並防止中文亂碼
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String fangshi = request.getParameter("fangshi");
    mannger dao = new mannger();//dao層物件
    User student = new User();//實體類物件
    User admin = new User();//實體類物件
    student.setUsername(username);//獲取前端傳來的資料
    student.setPassword(password);
    admin.setUsername(username);
    admin.setPassword(password);
    int i = 0;
    if ("0".equals(fangshi)) {   //判斷登入方式
        i = dao.loginstu(student);   //執行登入操作
        if (i==0) {
            request.setAttribute("msg", "使用者名稱或者密碼錯誤");
            System.out.println("使用者名稱或者密碼錯誤");
            response.getWriter().print("error"); //響應ajax的data值,
        } else {
            System.out.println("ok");
            response.getWriter().print("ok");//響應ajax的data值,成功則進響應到前端
            request.getSession().setAttribute("student", student.getUsername());
            System.out.println("登陸成功");
        }
    }
    else if ("1".equals(fangshi)) {
        i = dao.loginadmin(admin);
        System.out.println(i);
        if (i == 0) {
            request.setAttribute("msg", "使用者名稱或者密碼錯誤");
            System.out.println("使用者名稱或者密碼錯誤");
            response.getWriter().print("error"); //響應ajax的data值,
        } else {
            System.out.println("ok");
            response.getWriter().print("ok");//響應ajax的data值,成功則進響應到前端
            request.getSession().setAttribute("student", student.getUsername());
            System.out.println("登陸成功");
        }
    }
}
}

dao層,這個程式碼是封裝的一些進行資料庫操作的方法。

mannger.java

package com.Dao;
import com.Bean.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.Util.utils;
public class mannger {
    public int registerstu(User stu){
        int i=0;
        try {
            Connection connection = utils.getConnection();
            String sql = "insert into stuuser(username,password,email,name,tel,gender,birthday) values(?,?,?,?,?,?,?)";
            PreparedStatement ps = null;
            ps = connection.prepareStatement(sql);
            ps.setString(1,stu.getUsername());
            ps.setString(2, stu.getPassword());
            ps.setString(3,stu.getEmail());
            ps.setString(4,stu.getName());
            ps.setString(5, stu.getTel());
            ps.setString(6, stu.getGengder());
            ps.setString(7, stu.getBirthday());
            i = ps.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
          return i;
    }
    public int registeradimn(User admin){
        int i=0;
        try {
            Connection connection = utils.getConnection();
            String sql = "insert into adminuser(username,password,email,name,tel,gender,birthday) values(?,?,?,?,?,?,?)";
            PreparedStatement ps = null;
            ps = connection.prepareStatement(sql);
            ps.setString(1,admin.getUsername());
            ps.setString(2, admin.getPassword());
            ps.setString(3,admin.getEmail());
            ps.setString(4,admin.getName());
            ps.setString(5, admin.getTel());
            ps.setString(6, admin.getGengder());
            ps.setString(7, admin.getBirthday());
            i = ps.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    public int loginstu(User stu){
        int i = 1;
        try {
            Connection connection = utils.getConnection();
            String sql="select * from stuuser where username=? and password=?";
            PreparedStatement ps = null;
            ps = connection.prepareStatement(sql);
            ps.setString(1,stu.getUsername());
            ps.setString(2, stu.getPassword());
            ResultSet rs = ps.executeQuery();
            if(rs.next()==false){
                i = 0;
            }
            rs.close();
            ps.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    public int loginadmin(User admin){
        int i = 1;
        try {
            Connection connection = utils.getConnection();
            String sql="select * from adminuser where username=? and password=?";
            PreparedStatement ps = null;
            ps = connection.prepareStatement(sql);
            ps.setString(1,admin.getUsername());
            ps.setString(2, admin.getPassword());
            ResultSet rs = ps.executeQuery();
            if(rs.next()==false){
                i = 0;
            }
            rs.close();
            ps.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
}

下面是介面

login.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>後臺管理-登陸</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta http-equiv="Access-Control-Allow-Origin" content="*">
  <meta name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="format-detection" content="telephone=no">
  <link rel="stylesheet" href="WebContent/layui/css/layui.css"
        media="all">
  <!--[if lt IE 9]>
  <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
  <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->
  <style>
    body {
      background-image: url("WebContent/layuimini/images/bg.jpg");
      height: 100%;
      width: 100%;
    }

    #container {
      height: 100%;
      width: 100%;
    }

    input:-webkit-autofill {
      -webkit-box-shadow: inset 0 0 0 1000px #fff;
      background-color: transparent;
    }

    .admin-login-background {
      width: 300px;
      height: 300px;
      position: absolute;
      left: 50%;
      top: 40%;
      margin-left: -150px;
      margin-top: -100px;
    }

    .admin-header {
      text-align: center;
      margin-bottom: 20px;
      color: #ffffff;
      font-weight: bold;
      font-size: 40px
    }

    .admin-input {
      border-top-style: none;
      border-right-style: solid;
      border-bottom-style: solid;
      border-left-style: solid;
      height: 50px;
      width: 300px;
      padding-bottom: 0px;
    }

    .admin-input::-webkit-input-placeholder {
      color: #a78369
    }

    .layui-icon-username {
      color: #a78369 !important;
    }

    .layui-icon-username:hover {
      color: #9dadce !important;
    }

    .layui-icon-password {
      color: #a78369 !important;
    }

    .layui-icon-password:hover {
      color: #9dadce !important;
    }

    .admin-input-username {
      border-top-style: solid;
      border-radius: 10px 10px 0 0;
    }

    .admin-input-verify {
      border-radius: 0 0 10px 10px;
    }

    .admin-button {
      margin-top: 20px;
      font-weight: bold;
      font-size: 18px;
      width: 300px;
      height: 50px;
      border-radius: 5px;
      background-color: #a78369;
      border: 1px solid #d8b29f
    }

    .admin-icon {
      margin-left: 260px;
      margin-top: 10px;
      font-size: 30px;
    }

    i {
      position: absolute;
    }

    .admin-captcha {
      position: absolute;
      margin-left: 205px;
      margin-top: -40px;
    }
  </style>
</head>
<body>
<div id="container">
  <div></div>
  <div class="admin-login-background">
    <div class="admin-header">
      <span>login</span>
    </div>
    <form class="layui-form" >
      <div>
        <i class="layui-icon layui-icon-username admin-icon"></i> <input
              type="text"
              name="username"
              id="username"
              placeholder="請輸入使用者名稱"
              autocomplete="off"
              class="layui-input admin-input admin-input-username" >
      </div>
      <div>
        <i class="layui-icon layui-icon-password admin-icon"></i> <input
              type="password"
              name="password"
              id="password"
              placeholder="請輸入密碼"
              autocomplete="off"
              class="layui-input admin-input" >
      </div>
      <div class="layui-form-item">
       <div class="layui-show-sm-inline">
          <select name="fangshi" id="fangshi" >
            <option value="0">學生</option>
            <option value="1" selected>管理員</option>
          </select>
        </div>
        </div>
      <button type="button" class="layui-btn admin-button" id="login" >登 陸</button>
      <br><br>
    </form>
      <div class="layui-col-md-offset7">沒有賬戶?
        <a href="register.html" class="layui-btn-warm">注 冊</a>
      </div>

  </div>
</div>
<script src="WebContent/layui/layui.all.js" charset="utf-8"></script>
<script>
  layui.use([ 'form','jquery','layer' ], function() {
    var form = layui.form,
            layer = layui.layer,
            $= layui.jquery;
    form.render();//這句一定要加,佔坑
    $("#login").click(function(){
      var $1 = $.trim($("#username").val());
      var $2 = $.trim($("#password").val());
      var $3 = $.trim($("#fangshi").val());
      if($1 == ''){
        layer.msg('使用者名稱不能為空',function() {time:2000});
        return false;
      }
      if($2 == ''){
        layer.msg('密碼不能為空',function() {time:2000});
        return false;
      }
      $.ajax({
        url:'login?action=doLogin',//發出請求
        type:'post',
        data:{"username":$1,"password":$2,"fangshi":$3},

        success:function (data)  {
         console.log(data)
          if(data=="ok"){//ok說明登入成功
            layer.msg('登陸成功!',function() {time:2000})
            window.location.href="layui-doc-master/web/demo/admin.html";//然後跳轉到你係統的主介面
          }else if(data=="error"){
            layer.msg('使用者名稱或密碼錯誤!',function() {time:2000});
          }
        }
      });
    });
  });
</script>
</body>
</html>

 

實現效果

 

 如果有什麼問題,歡迎交流!歡迎交流!歡迎交流!

相關文章