欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaWeb,不使用框架下的MVC模式简单登陆模块实现

程序员文章站 2024-02-26 10:01:28
...

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. 运行结果

JavaWeb,不使用框架下的MVC模式简单登陆模块实现

JavaWeb,不使用框架下的MVC模式简单登陆模块实现

JavaWeb,不使用框架下的MVC模式简单登陆模块实现

JavaWeb,不使用框架下的MVC模式简单登陆模块实现

4. 其他注意事项

本项目中的数据库名为homgwork,数据表名为user_table,其中的字段有ID、name、password等。
本项目中用于验证的密码都是通过MD5Util类进行了md5加密,请首先通过该类将加密后的password写入到对应的数据表中的password字段,否则就会登录不成功,也可以在登陆验证的地方去掉md5加密验证。
本项目中的运行时可能会出现缺少servlet-api.jar的错误提示,这时候只需要将tomcat目录下的lib目录中的jsp-api.jar和servlet-api.jar两个jar包导入项目中即可。

相关标签: JavaWeb MVC