Design based on MVC (Java Web program)----library system

Design based on MVC----library system

This semester I learned JavaWeb development. At the end of the course, the task given by the teacher was to make a course design. The blogger used MVC (jsp, servlets, javabean) to develop a simple online library system, which also includes some html, css , JavaScript and other knowledge, interested friends can visit. Now give the running screenshot first, and then give the implementation steps of the specific project. Due to the large source code of the implementation program, this time I will talk about the MVC design of this program login .

Hahaha, an anonymous voting system was also made in the middle of the course before, you can also check it out here

My JavaWeb project----voting system

Go to github to download my project
to code cloud to download my project

Screenshot of the overall project operation

User login interface

insert image description here

Administrator login interface

insert image description here
Student User Registration Page

insert image description here
User interface (main page)

insert image description here

User operation page (main menu)

insert image description here

Admin manipulating the home page (main menu)

insert image description here
Wait for the interface to run screenshots.

Login Design (MVC Design Pattern)

Please imagine that if the user wants to log in, he must design a jsp page, and then submit the data entered by the user to the corresponding servlet for processing, and the servlet will then query the database by accessing the database to obtain the login result and return it to the servler. Jump or error message prompt. The basic steps are shown in the following figure (the first time to draw this kind of picture, hahaha, the logic may be a little unclear):

insert image description here

It looks a bit complicated, hahaha, it is my drawing that is messy, the logic is still relatively clear, the source code of each part is given below, but due to the large amount of associated data (css, javascript, database files, etc.), the possible effect It is not complete, all the source code of this project will be uploaded to github for your reference, hehe.

Login function source code

login.jsp

<%@ page import="vo.Students" %><%--
  Created by IntelliJ IDEA.
  User: Mr.Gao
  Date: 2020/6/2
  Time: 9:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login Page</title>                                                   <%--标题名称--%>
    <link rel="stylesheet" type="text/css" href="css/login.css">                <%--导入登录界面的css样式--%>

</head>
<body>
    <%
        Cookie[] cookies = request.getCookies();                               /*获取本机的cookie数据, 以cookie类型的数组返回*/
        String user = "";                                                      /*定义用户名字符串, 默认为空字符串*/
        String password = "";                                                  /* 定义用户密码字符串, 默认为空字符串密码*/
        String check="checked";                                                /* 定义check数据表示用户上次登录选择的登录方式,默认为选中*/
        if(cookies != null && cookies.length > 0){                             /* 若成功获取cookie数组cookies,并且不为null且长度大于0*/

            for(int i = 0; i < cookies.length; i++){                           /* 对cookie内存放的所有数据进行循环遍历*/
                if(cookies[i].getName().equals("user")){                       /* 若匹配到键名为"user"的cookie数据,说明其存取的为该用户的账户数据*/
                    user = cookies[i].getValue();                              /* 获取键值,获取该用户的账号 */
                }
                if(cookies[i].getName().equals("password")){                    /*若匹配到键名为"password"的cookie数据,说明其存放的为该用户的密码数据*/
                    password = cookies[i].getValue();                           /*获取键值,获取该用户的密码*/
                }
                if(cookies[i].getName().equals("check")){                       /*若匹配到键名为"check"的cookie数据,为上次用户选择学生登录或管理员登录的信息*/
                    check = cookies[i].getValue();                              /*获取键值,获取登录状态*/
                }
            }
        }

        Students student = (Students) session.getAttribute("student");          //每次返回登录界面都获取session对象中的学生用户
        if(student != null){                                                            //若student对象存在,说明此时为退出登录状态,则进行以下操作
            session.removeAttribute("student");                                         //移除session对象中的用户信息
            String person = (String)application.getAttribute("person");                 //获取application对象中的所有用户数量,为字符串类型
            application.setAttribute("person",(Integer.parseInt(person)-1) + "");       //重新设置application对象中的用户数量,为原来数据减1,字符串类型存入
        }

    %>
    <div class="htmleaf-container">
        <div class="login-wrap">                            <%-- 登录界面的div块--%>
            <div class="login-html">
                <h2>图书馆系统</h2>                          <%--二级标题, 登录信息--%>

                <%--分为两种登录方式, 学生登录和管理员身份登录--%>
                <input id="tab-1" type="radio" name="tab" class="sign-in" checked>
                <label for="tab-1" class="tab">学生</label>
                <input id="tab-2" type="radio" name="tab" class="sign-up" ${requestScope.check}>     <%--若获取的请求信息为checked时,下次以管理员登录为默认--%>
                <label for="tab-2" class="tab">管理员</label>
                <div class="login-form">
                    <div class="sign-in-htm">
                        <form action="userLoginServlet" method="post" name="form_user">            <%--学生学号登录的表单,提交给userLoginServlet进行处理--%>
                            <div class="group">
                                <label class="label">学号</label>
                                <input name="user" type="text" class="input" placeholder="输入您的学号,9位数字" autocomplete="off" value="<%=user%>">
                            </div>
                            <div class="group">
                                <label class="label">密码</label>
                                <input name="password" type="password" class="input" placeholder="输入您的登录密码" autocomplete="off" value="<%=password%>">
                            </div>
                            <div class="group">
                                <input id="check" type="checkbox" class="check" name="check" <%=check%>>
                                <label for="check"><span class="icon"></span> 记住密码</label>
                                <a href="reg.jsp" class="reg">没有学号?立即注册</a>
                                <p class="error">&nbsp;${requestScope.msg}</p>              <%--若用户登录失败,将在此显示用户登录失败的信息--%>
                            </div>
                            <div class="group">
                                <%--以button方式进行javascript点击函数处理,验证登录格式,并提交--%>
                                <input type="button" class="button" οnclick="onclick_user()" value="登录">
                            </div>
                        </form>
                    </div>
                    <div class="sign-up-htm">
                        <form action="adminLoginServlet" method="post" name="form_admin">   <%--管理员登录的表单,提交给AdminLoginServlet进行处理--%>
                            <div class="group">
                                <label class="label">管理员账号</label>
                                <input name="a_user" type="text" class="input" placeholder="输入管理员账号,9位数字" autocomplete="off">
                            </div>
                            <div class="group">
                                <label class="label">管理员密码</label>
                                <input name="a_password" type="password" class="input" placeholder="输入您的管理员密码" autocomplete="off">
                            </div>
                            <div class="group">
                                <p>暂不支持记住密码及注册</p>
                                <p class="error">&nbsp;${requestScope.a_msg}</p>            <%--若管理员登录失败,将在此显示管理员登录失败的信息--%>
                            </div>
                            <div class="group">
                                <%--以button方式进行javascript点击函数处理,验证管理员登录格式,并提交--%>
                                <input type="button" class="button" οnclick="onclick_admin()" value="登录">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="js/login.js"></script>             <%--导入javascript登录验证函数js文件--%>
</body>
</html>

UserLoginServlet.java (user submits servlet operations)

package servlets;


import dao.StudentDAO;
import vo.Students;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(urlPatterns = "/userLoginServlet")
public class UserLoginServlet extends HttpServlet {
    
    

    @Override           //覆写Servlet类的doGet()方法
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        req.setCharacterEncoding("utf-8");                      //设置req对象接收的数据以utf-8编码格式进行编码
        String user = req.getParameter("user");             //获取提交的用户名
        String password = req.getParameter("password");     //获取提交的密码
        String check = req.getParameter("check");           //获取记住密码是否选中按钮状态
        HttpSession session = req.getSession();                //获取session的对象
        StudentDAO s_dao = new StudentDAO();                    //实例化学生dao类对象,对学生数据库表中的学生信息进行操作
        try{
    
    
            if(s_dao.isExist(user,password)){
    
                   //通过调用dao对象的isExist()方法,判断此用户在学生数据库表中是否存在
                    //若存在,则进行以下操作
                  if(check != null){
    
                            //若check不为null,说明用户点击记住密码按钮
                      Cookie user_cookie = new Cookie("user",user);                         //将用户名、密码、选中状态存入cookie中,以便下次浏览器直接读取
                      Cookie password_cookie = new Cookie("password",password);
                      Cookie check_cookie = new Cookie("check","checked");
                      user_cookie.setMaxAge(7*24*60*60);                                        //设置生存周期为1周
                      password_cookie.setMaxAge(7*24*60*60);
                      check_cookie.setMaxAge(7*24*60*60);
                      resp.addCookie(user_cookie);                                              //存入resp对象中
                      resp.addCookie(password_cookie);
                      resp.addCookie(check_cookie);
                  }else{
    
                                                                            //否则表示用户未选择记住密码
                      Cookie user_cookie = new Cookie("user",user);
                      Cookie password_cookie = new Cookie("password",password);
                      Cookie check_cookie = new Cookie("check","");
                      user_cookie.setMaxAge(0);                                             //设置其生命周期为0,即无数据
                      password_cookie.setMaxAge(0);
                      check_cookie.setMaxAge(0);
                      resp.addCookie(user_cookie);                                          //存入resp对象中
                      resp.addCookie(password_cookie);
                      resp.addCookie(check_cookie);
                  }
                  Students student = s_dao.getStudentByName(user);                          //通过学生学号,过去该学生对象
                  ServletContext application = this.getServletContext();                    //获取服务器的application对象
                  String person = (String)application.getAttribute("person");           //取得application对象中的person数据,表示当前学生在线人数
                  if(person == null){
    
                                                       //若为null,表示此为第一个用户
                      person = "1";                                                     //person初始化为1
                  }else{
    
    
                      person = (Integer.parseInt(person) + 1) + "";                     //否则person累加,以字符串形式存储
                  }


                  session.setAttribute("student", student);                         //将用户信息存入session对象中
                  application.setAttribute("person",person);                        //将当前在线人数存入application对象中,供在线人数实时更新
                  resp.sendRedirect(req.getContextPath() + "/user.jsp");            //跳转到学生操纵主页
            }else {
    
    
                                                                                        //若数据库中无该学生信息,说明登陆失败
                String msg = (String)req.getAttribute("msg");

                if(msg == null) msg = "账号或密码输入有误,请重试!";                         //赋值错误信息
                req.setAttribute("msg",msg);                                            //存入req对象中,返还给用户提示

                req.getRequestDispatcher("/login.jsp").forward(req,resp);            //继续跳转到登录界面
            }
        }catch (Exception e){
    
                                               //出现异常,数据库查询失败
            System.out.println("数据库查询失败!");
        }

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        this.doGet(req, resp);
    }
}

AdminLoginServlet.java (admin login submit operation)

package servlets;

import com.sun.deploy.net.HttpRequest;
import dao.AdminDAO;
import vo.Admins;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/adminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    
    

    @Override//覆写doGet()方法
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        req.setCharacterEncoding("utf-8");
        String a_user = req.getParameter("a_user");                 //获取管理员提交的用户名、密码
        String a_password = req.getParameter("a_password");
        HttpSession session = req.getSession();                         //获取session对象

        AdminDAO a_dao = new AdminDAO();                                //实例化管理员数据库表的操纵对象
        Admins admin = null;                                            //admin对象为null
        try{
    
    
            if(a_dao.isExist(a_user,a_password)){
    
                           //调用dao类判断该管理员在数据库管理员表中是否存在
                admin = a_dao.getAdminByUser(a_user);                   //若存在,获取该管理员对象
                session.setAttribute("admin",admin);                //存入session对象中
                resp.sendRedirect(req.getContextPath() + "/admin.jsp");             //跳转到管理员主页面
            }else{
    
    
                                                                                //若数据库管理员表中查询失败
                String a_msg = (String) req.getAttribute("a_msg");
                String check = (String) req.getAttribute("check");
                a_msg = "管理员账户或密码输入错误!";                                //设置查询失败信息
                check = "checked";                                               //管理员登录方式锁定
                req.setAttribute("a_msg",a_msg);                            //将它们存取req对象中,返回给客户端
                req.setAttribute("check",check);

                req.getRequestDispatcher("/login.jsp").forward(req,resp);           //跳转到login.jsp登录界面
            }
        }catch (Exception e){
    
                                                       //出现异常状况,数据库查询失败
            System.out.println("数据库管理员表查询错误!");
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req,resp);
    }
}


The above code is the main jsp and java code of the login design, which involves the DAO operation class of JavaBean. Since there are too many codes, I will not show too much here. Interested partners can download this project to test, haha!

Summarize

This is the login interface design of the library system. As long as the little friends master the principle of MVC design, I believe that thousands of systems will be made. Hahaha, charge yourself!

Guess you like

Origin blog.csdn.net/weixin_43479947/article/details/106744538