wjingbo

我们一般使用的都是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>

 

实现效果

 

 如果有什么问题,欢迎交流!欢迎交流!欢迎交流!

相关文章:

猜你喜欢