简单的登录注册功能 JavaWeb

​ 最近工作室考核,需要我们做一个简单的登录注册功能

项目要求连接数据库(以Mysql数据库为例子)

1.连接数据库

package com.gl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//这个类用来获取与数据库的连接
public class Butil {
    public static Connection getcoonection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysqldata?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai","root","gl010924");
       //mysqldata是你自己的库名
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}

2.设置编码为UTF-8,防止乱码

package com.gl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//这个类用来对编码形式进行规范 :UTF-8
@WebFilter("/*")
public class EncodingFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

3.编写数据库的一些操作(增删改查)

package com.person;

import com.gl.Butil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public  class Student {

     //数据库添加
    public static void add(String name, String password){
        Connection  con = Butil.getcoonection();
        PreparedStatement pstmt;
        int number = 1;
        try {
            pstmt = con.prepareStatement("select * from data ");  //获取数据库表单的信息
            ResultSet resultSet = pstmt.executeQuery();
            while (resultSet.next()){
                number++;              //如果数据库还有信息就加1,间接获得数据库表单的数量
            }
            String id =""+number;

            pstmt = con.prepareStatement("insert into data (id,name,password) values ('"+id.trim()+"','"+name.trim()+"','"+password.trim()+"')");
             //在数据库添加新的信息
            pstmt.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
      //数据库修改
    public static void Update(String psd, String username){
        Connection  con = Butil.getcoonection();
        PreparedStatement pstmt;
        try {
            pstmt = con.prepareStatement("update data set password = '"+ psd.trim()+"'where name ='"+username.trim()+"' ");
            //对数据库进行修改操作
            pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    }

4.首页的jsp页面(页面中的背景图片大家自己可以随便找找)

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2020/6/23
  Time: 23:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录界面</title>
    <style>
        body{
            background-size: 1540px 720px;
        }
        .x1{
            margin-top: 200px;
            margin-left: 600px;
        }
        .x2{
            background-color:lightskyblue;
            border-radius: 20%;
            width: 200px;
            height: 30px;
            margin-left: 30px;
            font-size: 18px;
        }
        .label_input{
            font-size: 18px;
        }
        .text_field{
            border-color: lightpink;
            border-radius: 10%;
        }
        .x4{
            background-color:lightskyblue;
            border-radius: 20%;
            width: 200px;
            height: 30px;
            margin-left: 30px;
            font-size: 18px;
        }
    </style>
</head>
<body background="Image/x5.jpg">
<div class="x1">
    <form action="/Servlet_war_exploded/login" method="post" >
        <p><label class="label_input">用户名:</label><input  type="text" style= "background-color:transparent" name="username" class="text_field"/></p>
        <p><label class="label_input">&nbsp;密&nbsp;码&nbsp;:</label><input type="text" style= "background-color:transparent" name="password" class="text_field"/></p>
        <div>
            <button class="x2" type="submit">登录</button>
        </div>
    </form>
    <from  >
        <input class="x4" type="submit" name="Submit" value="注册" οnclick=window.open("http://localhost:8080/Servlet_war_exploded/register.jsp")>
    </from>
</div>
</body>
</html>

5.登录功能的实现

package com.gl;

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;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");   //获取登录页面输入的用户名
        String password = req.getParameter("password");   //获取登录页面输入的密码
//        String sql = "select * from data where username = '"+username + "'";    //不安全,容易被扒 防sql注入
        PrintWriter writer = resp.getWriter();
        try {
            Connection coon = Butil.getcoonection();       //获得数据库连接
            PreparedStatement  stmt = coon.prepareStatement("select * from projectdata where username = ?");  //sql语句,获取数据库数据
            stmt.setString(1,username);
            ResultSet resultSet = stmt.executeQuery();
            if (!resultSet.next()){
                req.getRequestDispatcher("/NotExist").forward(req,resp);   //如果用户不存在,跳转到用户不存在界面
                return;
            }
            String pwd = resultSet.getString("password");     //获得数据库的密码
            if(password.equals(pwd)){
            writer.print("登录成功");
                HttpSession session = req.getSession();
                session.setAttribute("user",username);          //保存用户名信息
                session.setMaxInactiveInterval(1000);
                req.getRequestDispatcher("/home").forward(req,resp);     //跳转到HomeServletjava程序
            }
            else{
                System.out.println("密码错误");                              //密码错误
                req.getRequestDispatcher("/PsdError").forward(req,resp); //跳转到密码错误界面
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
}

6.注册的jsp页面(页面中的背景图片大家自己可以随便找找)

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2020/6/26
  Time: 20:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
    <style>
        body{
            background-size: 1540px 720px;
        }
        .x1{
            margin-top: 150px;
            margin-left: 600px;
        }
        .x2{
            background-color:antiquewhite;
            border-radius: 20%;
            width: 200px;
            height: 30px;
            margin-left: 30px;
            font-size: 18px;
        }
        .label_input{
            font-size: 18px;
        }
        .text_field{
            border-color: lightpink;
            border-radius: 10%;
        }
        </style>
</head>
<body background="Image/x6.jpg">
<div class="x1">
    <form action="/Servlet_war_exploded/register" method="post" >
        <p><label class="label_input">用户名:</label><input  type="text" style= "background-color:transparent" name="username" class="text_field"/></p>
        <p><label class="label_input">&nbsp;密&nbsp;码&nbsp;:</label><input type="text" style= "background-color:transparent" name="password" class="text_field"/></p>
        <div >
            <button class="x2" type="submit">注册</button>
        </div>
    </form>
</body>
</html>

7.注册功能的实现

package com.gl;

import com.person.Student;
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("/register")
public class Register extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

          String username = req.getParameter("username");       //获取注册输入的用户名
          String psd = req.getParameter("password");            //获取注册输入的密码
          Student.add(username,psd);            //调用Student的Add()方法,添加到数据库
         resp.sendRedirect(req.getContextPath() + "/login.jsp");
        //重定向,这时如果用转换,浏览器的地址是register程序,如果刷新,会重新再执行一次register程序,数据库会添加相同的数据
        //重定向就很好的解决了这一问题,浏览器的地址会变为登陆界面的jsp形式!防止刷新再次执行servlet程序!

    }
}

8.登录成功的jsp页面

如果未登录直接访问会跳转到登录界面

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2020/6/24
  Time: 15:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>神的网站</title>
 <style>
        body{
            background-size: 1540px 720px;
        }
        .s1{
            color: antiquewhite;
            margin-bottom: 260px;
            margin-left: 620px;
        }
        .s2{
            color: antiquewhite;
            margin-top: 220px;
            margin-left: 600px;
        }
        .s3{
            color: antiquewhite;
            margin-top: 100px;
            margin-left:580px;
        }
        .s4{
            color: antiquewhite;
            margin-left: 600px;
        }
     .x1{
         background-color:lightskyblue;
         border-radius: 20%;
         width: 200px;
         height: 30px;
         margin-left: 600px;
         font-size: 18px;
         margin-top: 0px;
     }
     .x2{
         background-color:lightskyblue;
         border-radius: 20%;
         width: 200px;
         height: 30px;
         margin-left: 600px;
         font-size: 18px;
         margin-top:10px ;
     }
    </style>
</head>
<body background="Image/x4.jpg">
<c:if test="${sessionScope.user == null}">
    <h1 class="s2">您的账号未登录!</h1>
    <h1 class="s1">请您先登录</h1>
    <%
            response.setHeader("refresh", "1 ;url=login.jsp");   //在当前页面停顿1秒,然后跳转到登录界面
    %>

<%--    <h1>${username}</h1>--%>
</c:if >
<c:if test="${sessionScope.user !=null}">
    <h1 class="s3">欢迎来到${sessionScope.user}的世界!</h1>
    <h1 class="s4">您已登录成功!</h1>
    <form>
        <input class="x1" type="submit" name="Submit" value="修改密码" οnclick=window.open("http://localhost:8080/Servlet_war_exploded/ModifyMessage.jsp")>
    </form>
        <from >
            <input class="x2" type="submit" name="Submit" value="退出登录" οnclick=window.open("http://localhost:8080/Servlet_war_exploded/login.jsp")>
        </from>
</c:if>
</body>
</html>

9.登录成功的Sevlet程序

package com.gl;

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

@WebServlet("/home")
public class HomeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = (String)req.getSession().getAttribute("user");   //获取在登录界面输入的username,在LoginServlet有保存
        req.setAttribute("username",username);
        req.getRequestDispatcher("home.jsp").forward(req,resp);    //跳转到HomeServlet程序
    }
}

10.登录时用户不存在的jsp页面

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2020/6/26
  Time: 15:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户不存在</title>
    <style>
        body{
            background-size: 1540px 720px;
        }
        h1{
            text-align: center;
            margin-top: 100px;
            color: bisque;
        }
        .x1{
            background-color:lightskyblue;
            border-radius: 20%;
            width: 200px;
            height: 30px;
            margin-left: 650px;
            font-size: 18px;
        }
    </style>
</head>
<body background="Image/x3.jpg">
<h1>输入的用户不存在</h1>
<%
    response.setHeader("refresh", "1 ;url=login.jsp");   //在当前页面停顿1秒,然后跳转到登录界面
%>
<from >
    <input class="x1" type="submit" name="Submit" value="返回登录界面" οnclick=window.open("http://localhost:8080/Servlet_war_exploded/login.jsp")>
</from>
</body>
</html>

11.用户不存在的Sevlet程序

package com.gl;

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("/NotExist")
public class NotExistServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("NotExist.jsp").forward(req,resp);  //用户不存在跳转到用户不存在界面
    }
}

12.登录时密码错误的jsp页面

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2020/6/26
  Time: 15:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>密码错误</title>
    <style>
        h1{
            text-align: center;
            margin-top: 100px;
            color: bisque;
        }
        .x1{
            background-color:lightskyblue;
            border-radius: 20%;
            width: 200px;
            height: 30px;
            margin-left: 650px;
            font-size: 18px;
        }
        body{
            background-size: 1540px 720px;
        }
    </style>
</head>
<body background="Image/x2.jpg">
<h1>你输入的密码错误</h1>
<%
    response.setHeader("refresh", "1 ;url=login.jsp");   //在当前页面停顿1秒,然后跳转到登录界面
%>
<from >
    <input class="x1" type="submit" name="Submit" value="返回登录界面" onclick=window.open("http://localhost:8080/Servlet_war_exploded/login.jsp")>
</from>
</body>
</html>

13.密码错误的Sevlet程序

package com.gl;

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("/PsdError")
public class PadErrorServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("PsdError.jsp").forward(req,resp);   //密码错误跳转到密码错误界面!
    }
}

登录成功后有修改密码的功能

14.修改密码的Servlet程序

package com.gl;

import com.person.Student;
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;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/modifymessage")
public class ModifyMessage  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String psd = req.getParameter("password");   //获取用户修改的用户密码
        String username =(String)req.getSession().getAttribute("user");   //获取用户名
        Student.Update(psd,username);
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
        //重定向,这时如果用转换,浏览器的地址是modifymessage程序,如果刷新,会重新再执行一次modifymessage程序,数据库会添加相同的数据
        //重定向就很好的解决了这一问题,浏览器的地址会变为登陆界面的jsp形式!防止刷新再次执行servlet程序!
    }
}

15.修改密码的jsp页面

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2020/6/26
  Time: 19:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改密码</title>
    <style>
        body{
            background-size: 1540px 720px;
        }
        .x1{
            margin-top: 200px;
            margin-left: 600px;
        }
        .label_input{
            font-size: 18px;
            color: bisque;
        }
        .text_field{
            border-color: lightpink;
            border-radius: 10%;
        }
        .x2{
            margin-left: 70px;
            width: 150px;
            height: 30px;
            background-color: bisque;
            border-radius: 20%;
            font-size: 18px;
        }
    </style>
</head>
<body background="Image/x7.jpg">
<div class="x1">
<form action="/Servlet_war_exploded/modifymessage" method="post">
    <p><label class="label_input">输入修改后的密码:</label><input  type="text" style= "background-color:transparent" name="password" class="text_field"/></p>
    <button class="x2" type="submit">提交</button>
    <form>
    </form>
    </form>
</div>
</body>
</html>

这就完成了一个简单的登录和注册的功能!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只小猪~~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值