1. 程式人生 > >JavaWeb,不使用框架下的MVC模式簡單登陸模組實現

JavaWeb,不使用框架下的MVC模式簡單登陸模組實現

專案結構圖
專案結構圖

1. 前期準備

本專案使用的jdk版本是:jdk1.8.0_181
本專案使用的tomcat版本是:apache-tomcat-7.0.90
本專案使用的mysql資料庫版本是:mysql8.0
本專案使用的資料庫驅動是:mysql-connector-java-8.0.12.jar
本專案使用的編輯器是:IntelliJ IDEA 2017.1
如果環境不一致,請修改相應的程式碼,資料庫部分請按照自己的使用者名稱密碼資料庫的名稱進行相應的修改,資料庫連線部分請在檔案JDBCUtil中進行相應的修改,資料表名稱的修改請在UserDaoImpl中進行修改。

2. 專案程式碼

後臺原始碼
com.cx.bean.User.java

package com.cx.bean;

/**
 * Created by admin on 2018/8/14.
 */
public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public
String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }

com.cx.dao.user.UsrDao.java

package com.cx.dao.user;

import com.cx.bean.User;

/**
 * Created by admin on 2018/8/14.
 */
public interface UserDao {
    User queryByUsername(String username);//返回查詢到的使用者

}

com.cx.dao.user.impl.UserDaoImpl.java

package com.cx.dao.user.impl;

import com.cx.bean.User;
import com.cx.dao.user.UserDao;
import com.cx.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by admin on 2018/8/14.
 */
public class UserDaoImpl implements UserDao{
    User user = null;
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    @Override
    public User queryByUsername(String username) {
        //根據使用者名稱查詢使用者,並返回使用者

        try {
            connection = JDBCUtil.getConnect();//首先連線資料庫
            String sql = "select * from user_table where name=?";//寫出sql語句
            preparedStatement = connection.prepareStatement(sql);//執行sql語句
            preparedStatement.setString(1,username);//為sql語句中的變數賦值
            resultSet = preparedStatement.executeQuery();//獲得查詢結果集
            if (resultSet.next()){
                user = new User();
                user.setId(Integer.parseInt(resultSet.getString("ID")));//將資料庫中取出來的id欄位字元型別轉換為整型並賦給user物件
                user.setPassword(resultSet.getString("password"));
                user.setUsername(resultSet.getString("name"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(preparedStatement,connection,resultSet);
        }



        return user;
    }
}

com.cx.service.user.UserService.java

package com.cx.service.user;

import com.cx.bean.User;

/**
 * Created by admin on 2018/8/14.
 */
public interface UserService {
    User queryByUsername(String username);
}

com.cx.service.impl.UserServiceImpl.java

package com.cx.service.user.impl;

import com.cx.bean.User;
import com.cx.dao.user.impl.UserDaoImpl;
import com.cx.service.user.UserService;

/**
 * Created by admin on 2018/8/14.
 */
public class UserServiceImpl implements UserService {

    UserDaoImpl userDaoImpl = null;
    @Override
    public User queryByUsername(String username) {
        User user = new User();
        userDaoImpl = new UserDaoImpl();
        user = userDaoImpl.queryByUsername(username);
        return user;
    }
}

com.cx.controller.LoginController.java

package com.cx.controller;

import com.cx.bean.User;
import com.cx.dao.user.impl.UserDaoImpl;
import com.cx.utils.MD5Util;

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 java.io.IOException;

/**
 * Created by admin on 2018/8/14.
 */
@WebServlet("/login.do")
public class LoginController extends HttpServlet {
    public LoginController(){
        super();
    }

    private UserDaoImpl userDaoImpl = null;

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

    }

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

        //呼叫login方法
        User user = login(req);
        if (user != null){
            req.setAttribute("user",user);
            req.getRequestDispatcher("/success.jsp").forward(req,resp);
        }else {
            req.getRequestDispatcher("/error.jsp").forward(req,resp);
        }
    }

    public User login(HttpServletRequest request) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        userDaoImpl = new UserDaoImpl();
        User user = userDaoImpl.queryByUsername(username);
        if (MD5Util.string2MD5(password).equals(user.getPassword())){
            return user;
        }else {
            return null;
        }



    }
}

com.cx.utils.JDBCUtil.java

package com.cx.utils;

import java.sql.*;

/**
 * Created by admin on 2018/8/14.
 */
public class JDBCUtil {
    //定義出來資料庫連線的資訊
    private static String url = "jdbc:mysql://192.168.99.206:3306/homework?serverTimezone=UTC&useSSL=false";//資料庫連線地址
    private static String user = "root";//資料庫連線使用者名稱
    private static String password = "123456";//資料庫連線密碼
    private static String driver = "com.mysql.cj.jdbc.Driver";//資料庫連線驅動

    static {
        //獲取驅動類
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //資料庫連線
    public static Connection getConnect() throws SQLException {
        Connection conn = null;
        conn = (Connection) DriverManager.getConnection(url,user,password);
        return conn;
    }

    //資料庫關閉
    public static void close(PreparedStatement preparedStatement, Connection connection, ResultSet resultSet){

        if (preparedStatement != null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

com.cx.utils.MD5Util.java

package com.cx.utils;

import java.security.MessageDigest;

/**
 * Created by admin on 2018/8/14.
 */
public class MD5Util {

    /***
     * MD5加碼 生成32位md5碼
     */
    public static String string2MD5(String inStr){
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++){
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 加密解密演算法 執行一次加密,兩次解密
     */
    public static String convertMD5(String inStr){

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++){
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;

    }

    // 測試主函式
    public static void main(String args[]) {
        String s = new String("123456");
        System.out.println("原始:" + s);
        System.out.println("MD5後:" + string2MD5(s));
        System.out.println("加密的:" + convertMD5(s));
        System.out.println("解密的:" + convertMD5(convertMD5(s)));

    }
}

前端JSP
index.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/8/14
  Time: 9:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首頁</title>
  </head>
  <body>
  <H1>這是首頁</H1>
  <h1><a href="../login.jsp">登陸</a> </h1>
  </body>
</html>

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/8/14
  Time: 11:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陸介面</title>
</head>
<body>
<form action="../login.do" method="post">
    <table>
        <tr>
            <td>使用者名稱:</td>
            <td><input name="username" type="text" value=""/></td>
        </tr>
        <tr>
            <td>密  碼:</td>
            <td><input name="password" type="password" value=""/></td>
        </tr>
        <tr>
            <td><input type="reset" value="重置"></td>
            <td><input type="submit" value="提交"/></td>
        </tr>
    </table>
</form>
</body>
</html>

success.jsp

<%@ page import="com.cx.bean.User" %>
<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/8/14
  Time: 10:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陸成功頁面</title>
</head>
<body>
<%
    User user = (User) request.getAttribute("user");

%>
<h1>登陸成功!</h1>
<h1>使用者ID:<%=user.getId() %></h1>
<h1>使用者名稱:<%=user.getUsername() %></h1>
</body>
</html>

error.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/8/14
  Time: 11:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陸失敗頁面</title>
</head>
<body>
<h1>登陸失敗!請重新<a href="../login.jsp">登陸</a> </h1>
</body>
</html>

3. 執行結果

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

4. 其他注意事項

本專案中的資料庫名為homgwork,資料表名為user_table,其中的欄位有ID、name、password等。
本專案中用於驗證的密碼都是通過MD5Util類進行了md5加密,請首先通過該類將加密後的password寫入到對應的資料表中的password欄位,否則就會登入不成功,也可以在登陸驗證的地方去掉md5加密驗證。
本專案中的執行時可能會出現缺少servlet-api.jar的錯誤提示,這時候只需要將tomcat目錄下的lib目錄中的jsp-api.jar和servlet-api.jar兩個jar包匯入專案中即可。