使用安全 jsp 与 servlet 完成用户登录(登录错误时账号密码回填)。登录成功后才能上传图片的图片管理系统。

这里写目录标题

  • 一、数据库准备和创建安全jsp与servlet完成用户登录
  • 二、数据库表的创建
  • 三、核心代码如下
      • ①dao层相关代码
      • ②entity层相关代码
      • ③filter层相关代码
      • ④servlet层相关代码
      • ⑤WEB-INF下面的jsp目录文件
      • ⑥WEB-INF下面的lib目录文件
      • ⑦web.xml
  • 四、系统测试结果展示如下:

一、数据库准备和创建安全jsp与servlet完成用户登录

  1.数据库准备步骤地址
  2.安全jsp与servlet创建过程

二、数据库表的创建

使用安全 jsp 与 servlet 完成用户登录(登录错误时账号密码回填)。登录成功后才能上传图片的图片管理系统。_第1张图片
使用安全 jsp 与 servlet 完成用户登录(登录错误时账号密码回填)。登录成功后才能上传图片的图片管理系统。_第2张图片
使用安全 jsp 与 servlet 完成用户登录(登录错误时账号密码回填)。登录成功后才能上传图片的图片管理系统。_第3张图片

三、核心代码如下

使用安全 jsp 与 servlet 完成用户登录(登录错误时账号密码回填)。登录成功后才能上传图片的图片管理系统。_第4张图片

①dao层相关代码

1.UserDao

package com.allen.dao;

import com.allen.entity.User;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;

public class UserDao {
    public User login(String loginName,String loginPassword) throws ClassNotFoundException, SQLException, NoSuchAlgorithmException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql:///picture?useSSL=false", "root", "123456");
        PreparedStatement statement = connection.prepareStatement("select * from user where login_name=? and login_password=?");
        statement.setObject(1,loginName);
        statement.setObject(2,loginPassword);
        ResultSet resultSet = statement.executeQuery();
        User user=null;
        if (resultSet.next()) {
            user = new User();
            user.setId(resultSet.getInt("id"));
            user.setTrueName(resultSet.getString("true_name"));
            user.setEmail(resultSet.getString("email"));
            user.setLoginName(resultSet.getString("login_name"));
            user.setLoginPassword(resultSet.getString("login_password"));
            user.setTelephone(resultSet.getString("telephone"));
        }
        resultSet.close();
        statement.close();
        connection.close();
        return user;
    }
//    MD5加密方法
    private String md5(String loginPassword) throws NoSuchAlgorithmException {
        StringBuffer stringBuffer = new StringBuffer(32);
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(loginPassword.getBytes());
        for (int i = 0; i < bytes.length; i++) {
           stringBuffer.append(Integer.toHexString((bytes[i]&0xFF)|0x100).toUpperCase(),1,3);
        }
        return stringBuffer.toString();
    }
}

2.ImageDao

package com.allen.dao;

import com.allen.entity.Image;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ImageDao {
    public boolean add(Image image) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql:///picture?useSSL=false", "root", "123456");
        PreparedStatement statement = connection.prepareStatement("insert into image (original_file_name,relative_paths,create_time,user_id) values (?,?,now(),?)");
        statement.setObject(1,image.getOriginalFileName());
        statement.setObject(2,image.getRelativePaths());
        statement.setObject(3,image.getUserId());
        int i = statement.executeUpdate();
        statement.close();
        connection.close();
        return i!=0;
    }

    public List<Image> list() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql:///picture?useSSL=false", "root", "123456");
        PreparedStatement statement = connection.prepareStatement("select * from image");
        ResultSet resultSet = statement.executeQuery();
        List<Image> list=new ArrayList<>();
        while (resultSet.next()) {
            Image image = new Image();
            image.setUserId(resultSet.getInt("user_id"));
            image.setRelativePaths(resultSet.getString("relative_paths"));
            image.setOriginalFileName(resultSet.getString("original_file_name"));
            image.setId(resultSet.getInt("id"));
            image.setCreateTime(resultSet.getTime("create_time"));
            list.add(image);
        }
        resultSet.close();
        statement.close();
        connection.close();
        return list;
    }
}

②entity层相关代码

1.Image

package com.allen.entity;


import java.util.Date;

public class Image {

    private Integer id;
    private String originalFileName;
    private String relativePaths;
    private Date createTime;
    private Integer userId;

    public Integer getId() {
        return id;
    }

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

    public String getOriginalFileName() {
        return originalFileName;
    }

    public void setOriginalFileName(String originalFileName) {
        this.originalFileName = originalFileName;
    }

    public String getRelativePaths() {
        return relativePaths;
    }

    public void setRelativePaths(String relativePaths) {
        this.relativePaths = relativePaths;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }
}

2.User

package com.allen.entity;
public class User {
  private Integer id;
  private String trueName;
  private String loginName;
  private String loginPassword;
  private String telephone;
  private String email;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }
  
  public String getTrueName() {
    return trueName;
  }

  public void setTrueName(String trueName) {
    this.trueName = trueName;
  }

  public String getLoginName() {
    return loginName;
  }

  public void setLoginName(String loginName) {
    this.loginName = loginName;
  }


  public String getLoginPassword() {
    return loginPassword;
  }

  public void setLoginPassword(String loginPassword) {
    this.loginPassword = loginPassword;
  }

  public String getTelephone() {
    return telephone;
  }

  public void setTelephone(String telephone) {
    this.telephone = telephone;
  }

  public String getEmail() {
    return email;
  }
  public void setEmail(String email) {
    this.email = email;
  }
}

③filter层相关代码

1.LoginFilter

package com.allen.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        if (request.getRequestURI().endsWith("login")) {
            filterChain.doFilter(request,response);
            return;
        }

        if (request.getSession().getAttribute("UserInfo")!=null) {
            filterChain.doFilter(request,response);
            return;
        }
        response.sendRedirect(request.getContextPath()+"/login");
    }
    @Override
    public void destroy() {

    }
}

④servlet层相关代码

1.IndexServlet

package com.allen.servlet;

import com.allen.dao.ImageDao;
import com.allen.entity.Image;
import com.allen.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

@WebServlet("/index")
@MultipartConfig
public class IndexServlet extends HttpServlet {
    ImageDao imageDao = new ImageDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Image> list = imageDao.list();
            request.setAttribute("imageLsit",list);
            request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Part file = request.getPart("file");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = file.getSubmittedFileName();
        String type = fileName.substring(fileName.lastIndexOf("."));
        file.write("H:\\demotest\\picture-system\\images\\"+uuid+type);
        Image image = new Image();
        image.setOriginalFileName(fileName);
        image.setRelativePaths("/images/"+uuid+type);
        User userInfo = (User) request.getSession().getAttribute("UserInfo");
        image.setUserId(userInfo.getId());
        try {
            imageDao.add(image);
            response.sendRedirect(request.getContextPath()+"/index");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

2.LoginServlet

package com.allen.servlet;

import com.allen.dao.UserDao;
import com.allen.entity.User;

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;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserDao userDao = new UserDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            User user = userDao.login(username, password);
            if (user!=null) {
                request.getSession().setAttribute("UserInfo",user);
                response.sendRedirect(request.getContextPath()+"/index");
                return;
            }
            request.setAttribute("username",username);
            request.setAttribute("password",password);
            request.setAttribute("msg","账号或密码错误!!!请重新输入");
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

3.LogoutServlet

package com.allen.servlet;

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;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
    }
}

⑤WEB-INF下面的jsp目录文件

1.login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.25/examples/signin/signin.css" rel="stylesheet">
    <style>
        h4{
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <form class="form-signin" method="post" action="login">
        <h2 class="form-signin-heading text-center">登录页面</h2>

        <input type="text" name="username" class="form-control" placeholder="请输入账号" required autofocus value="${username}">
        <br>

        <input type="password" name="password" class="form-control" placeholder="请输入密码" required value="${password}">
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me"> 记住我
            </label>
        </div>
        <br>
        <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
        <h4 id="p1" style="color: red">${msg}</h4>
    </form>
</div> <!-- /container -->
</body>
</html>

2.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>首页</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            //首先将#back-to-top隐藏
            $("#back-to-top").hide();
            //当滚动条的位置处于距顶部600像素以下时,跳转链接出现,否则消失
            $(function () {
                $(window).scroll(function () {
                    if ($(window).scrollTop() > 300) {
                        $("#back-to-top").fadeIn(500);
                    } else {
                        $("#back-to-top").fadeOut(500);
                    }
                });
                //当点击跳转链接后,回到页面顶部位置
                $("#back-to-top").click(function () {
                    $('body,html').animate({
                        scrollTop: 0
                    }, 500);
                    return false;
                });
            });
        });
    </script>
    <style>
        p#back-to-top {
            position: fixed;
            bottom: 30px;
            right: 12px;
        }

        p#back-to-top a {
            text-align: center;
            text-decoration: none;
            color: #000;
            display: block;
            width: 60px;
            /*使用CSS3中的transition属性给跳转链接中的文字添加渐变效果*/
            -moz-transition: color1s;
            -webkit-transition: color1s;
            -o-transition: color1s;
        }

        p#back-to-top a:hover {
            color: #000011;
        }

        p#back-to-top a span {
            background-color: #d4bbbb;
            z-index: -100;
            border: 1px solid #cccccc;
            border-radius: 6px;
            display: block;
            height: 30px;
            width: 30px;
            margin-bottom: 5px;
            /*使用CSS3中的transition属性给标签背景颜色添加渐变效果*/
            -moz-transition: background1s;
            -webkit-transition: background1s;
            -o-transition: background1s;
        }

        #back-to-top a:hover span {
            background-color: #f0f0f0;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <form method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="inputFile">文件</label>
                    <input type="file" id="InputFile" accept="image/*" name="file">
                </div>
                <button type="submit" class="btn btn-success">上传</button>
                <span style="position: fixed;right: 140px"> <a href="logout" class="btn btn-success"
                                                               style="float: right">退出登录</a></span>
            </form>
        </div>
        <c:forEach items="${imageLsit}" var="z">
            <div class="col-xs-4">
                <img src="${z.relativePaths}" class="img-rounded" style="max-width: 100%">
                <p>${z.originalFileName}${z.createTime}</p>
            </div>
        </c:forEach>
        <p id="back-to-top" style="margin-right: 140px">
            <a href="#top">
			<span class="fa fa-chevron-up" aria-hidden="true" style="width: 80px; height: 30px;">返回顶部
			</span>
            </a>
        </p>
    </div>
</div>
</body>
</html>

⑥WEB-INF下面的lib目录文件

jstl-1.2.jar
mysql-connector-java-5.1.48.jar

⑦web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <welcome-file-list>
        <welcome-file>login</welcome-file>
    </welcome-file-list>
</web-app>

四、系统测试结果展示如下:

测试视频

简单的上传图片系统

视频地址:

你可能感兴趣的