连接MySql实现对(form表单)登录界面数据的增(注册)删(注销)改 查(登录)

javaweb
开发工具:IDEA
连接MySql实现对登录界面数据的增删改查
以及cookie的使用

小白一个,有说的不对点请多多指教。
先放成果图吧
登录界面注册界面

注销界面

我的项目列表

数据库的int值要设置为自增长,int值同时也是主键。
这是数据库

好了,开始正文。我也是菜鸟,所以我会写的详细写,希望能帮助更多初学者。有不对的地方欢迎指教。

首先创建工程,我就不多说了,可以参考一下别人写的。
导包,我的数据库用的是8.0版本 如果是5.0版本的话驱动和url要改一下不然会报错,具体的话可以去百度一下。
我的配置文件
创建数据库连接,我用的是加载文件的方式,下面是代码。要注意的是必须使用DbConnection.class.getClassLoader().getResourceAsStream()用classloader.getsystemclassload.getresourceasstream()方式连接tomcat时会报异常 。下面是我的代码:
public class DbConnection { public static Connection getConnect() { Connection con = null; InputStream is=null;
try {
//读取配置文件 必须使用DbConnection.class.getClassLoader().getResourceAsStream()方式
//classloader.getsystemclassload.getresourceasstream()方式会报异常
is = DbConnection.class.getClassLoader().getResourceAsStream(“Jdbc.properties”);
Properties pro = new Properties();
pro.load(is);
//读取配置信息
String user = pro.getProperty(“user”);
String password = pro.getProperty(“password”);
String url = pro.getProperty(“url”);
String driver = pro.getProperty(“driver”);
//加载配置文件
Class.forName(driver);
//获取连接
con = DriverManager.getConnection(url, user, password);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return con;
}

接着创建jdbc工具类,方便我们后面取用。代码就不放了,方法都是大同小异。

接着我们创建jsp文件。记得实在web目录下。

放一个代码参考一下,其他的都是差不多的。要注意的是这个代码除了一个表单之外,还有一段java代码,这是用来获取cookie值并把他显示到表单。其中value="<%=password%>“和
value=”<%=username%>"这两句就是让把值显示出来

因为后面的servlet程序中需要给cookie编码。所以这一段是解码的,毕竟cookie一般是不存中文的。
username=URLDecoder.decode(cookies[i].getValue()

<%@ page import="com.lsg.jdbcutil.DbConnection" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="com.lsg.jdbcutil.DbConnection" %>
<%@ page import="java.net.URLDecoder" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/9/11
  Time: 17:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
      <%--获取cookie值,并填充到表单--%>
      <%
          String username ="";
          String password ="";
                  Cookie[] cookies = request.getCookies();
          for (int i=0; i<cookies.length;i++){
              if ("username".equals(cookies[i].getName())){
                  username=URLDecoder.decode(cookies[i].getValue(), "UTF-8");
              }else if("password".equals(cookies[i].getName())){
                  password = cookies[i].getValue();
              }
          }
      %>
          <title>登录界面</title>
  </head>
  <body>
  <form action="ServletLogin" method="post" >
      <table  border="1" >
          <tr >
              <td colspan="2" bgcolor="#7fffd4" align="center"></td>
          </tr>
          <tr>
              <td>用户名:</td>
              <td> <input type="text" name="username" value="<%=username%>"></td>
          </tr>
          <tr>
              <td>密码:</td>
              <td> <input type="password" name="password" value="<%=password%>"></td>
          </tr>
          <tr>
              <td colspan="2">记住密码 <input type="checkbox" id ="remeber"  name="remeber" value="true"></td>
          </tr>
          <tr>
              <td  colspan="2" align="center" bgcolor="#7fffd4" > <input type="submit" name="submit" value="登录"  ></td>
          </tr>
          <tr>
              <td  colspan="2" align="center" bgcolor="#7fffd4"> <input type="button" onclick="window.location.href='cancel.jsp';" value="注销"  name="cancel"/></td>
          </tr>
          <tr>
              <td  colspan="2" align="center" bgcolor="#7fffd4"><input type="button" onclick="window.location.href='register.jsp';" value="注册"  name="register"/></td>
          </tr>
      </table>
  </form>
  </body>
</html>

login界面会提交到Servlerlogin,下面是代码。我做了注释,就不多说废话了

package com.lsg.servlet;

import com.lsg.jdbcutil.DbConnection;
import com.lsg.jdbcutil.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet( "/ServletLogin")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType ("text/html,charset=UTF-8");
        //设置服务器响应编码
        response.setCharacterEncoding("UTF-8");
        //获取表单提交的参数值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        //获取数据库连接
        Connection con = DbConnection.getConnect();
//        request.getSession().setAttribute("username",username);
//        request.getSession().setAttribute("passeord",password);
        //判断用户名密码是否一致
        boolean existInfo = JdbcUtils.isExistInfo(username, password);
//        System.out.println(con);
//        System.out.println(existInfo);

        //用户名密码正确则跳转并把数据保存到cookie中
        if (existInfo){
//            System.out.println("对");
            String remeber = request.getParameter("remeber");
            String a = URLEncoder.encode("登录成功", "UTF-8");
            out.print("<script>alert(decodeURIComponent('"+a+"') );window.location.href='loginsuccess.jsp'</script>");
            if ("true".equals(remeber)){
                Cookie cookie1 = new Cookie("remeber", remeber );
                cookie1.setMaxAge(60*60*666);
                response.addCookie(cookie1);
                cookie1.setPath("/");
                Cookie cookie2 = new Cookie("username",  URLEncoder.encode(username, "UTF-8"));
                cookie2.setMaxAge(60*60*60);
                cookie2.setPath("/");
                response.addCookie(cookie2);
                Cookie cookie3 = new Cookie("password", password);
                cookie3.setMaxAge(60*60*66);
                cookie3.setPath("/");
                response.addCookie(cookie3);}
            //用户名密码错误则重新登录 跳转到登录界面
        }else{
            String a = URLEncoder.encode("用户名密码错误或不存在!请重新登录", "UTF-8");
            out.print("<script>alert(decodeURIComponent('"+a+"') );window.location.href='login.jsp'</script>");

//            out.print("<script>alert('用户名密码错误');window.location.href='login.jsp'</script>");
//            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
        //关闭资源
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

这一段是为cookie存中文值而做的编码,对应上面的解码
```bash
    Cookie cookie2 = new Cookie("username",  URLEncoder.encode(username, "UTF-8"));

这是注册界面的servletRegister

package com.lsg.servlet;

import com.lsg.jdbcutil.DbConnection;
import com.lsg.jdbcutil.JdbcUtils;

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;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet("/ServletRegister")
public class ServletRegister extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //统一设置编码方式
        request.setCharacterEncoding("UTF-8");
        response.setContentType ("text/html,charset=UTF-8");
        //获取输出流
        PrintWriter out = response.getWriter();
        //获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//       String username = (String) request.getSession().getAttribute("username");
//       String password = (String) request.getSession().getAttribute("password");
//        System.out.println(password);
//        System.out.println(username);
        //连接数据库
        Connection con = DbConnection.getConnect();
        //判断表单是否输入了数据
        if (username.equals("")){
            String a = URLEncoder.encode("用户名为空!请重新填写!", "UTF-8");
            out.print("<script>alert(decodeURIComponent('"+a+"') );window.location.href='register.jsp'</script>");

        }else if(password.equals("")){
            String a = URLEncoder.encode("请填写用户密码!", "UTF-8");
            out.print("<script>alert(decodeURIComponent('"+a+"') );window.location.href='register.jsp'</script>");
        //判断数据库是否有重名的用户
        }else if(JdbcUtils.findByName(username)){

            String a = URLEncoder.encode("用户已存在!请重新注册!", "UTF-8");
            out.print("<script>alert(decodeURIComponent('"+a+"') );window.location.href='register.jsp'</script>");
        } else{
            //保存数据
            JdbcUtils.saveValues(username,password);
            String a = URLEncoder.encode("注册成功!请返回登录!", "UTF-8");
            out.print("<script>alert(decodeURIComponent('"+a+"') );window.location.href='login.jsp'</script>");
        }

        //关闭资源
        out.flush();
        //关闭资源
        out.close();
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

下面是注销ServletRegister的代码

package com.lsg.servlet;

import com.lsg.jdbcutil.DbConnection;
import com.lsg.jdbcutil.JdbcUtils;

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;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet( "/ServletCancel")
public class ServletCancel extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType ("text/html,charset=UTF-8");
        设置服务器响应编码
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        //获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Connection con = DbConnection.getConnect();
        //判断数据库是否存在改数据
        boolean existInfo = JdbcUtils.isExistInfo( username, password);
        if (existInfo){
            //存在数据则删除并跳转至登录界面
            JdbcUtils.delect(username,password);
            String a = URLEncoder.encode("注销成功", "UTF-8");
            out.print("<script>alert(decodeURIComponent('"+a+"') );window.location.href='login.jsp'</script>");

        }else {
            //不存在则弹出警告
            String a = URLEncoder.encode("用户信息错误!请重新输入", "UTF-8");
            out.print("<script>alert(decodeURIComponent('" + a + "') );window.location.href='register.jsp'</script>");
        }
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

除了jsp代码之外,基本的的代码都在这里了。下面顺便讲一下一些小的知识点。
这是浏览器界面用来弹出小警告的,挺好玩的小玩意。照着格式改下就可以用了。

 String a = URLEncoder.encode("用户信息错误!请重新输入", "UTF-8");
            out.print("<script>alert(decodeURIComponent('" + a + "') );window.location.href='register.jsp'</script>

按道理说原本设置前面两个就可以了解决乱码了,但是我竟然还是乱码,还来百度来第三句代码才解决了乱码。所以就放上去了。哈哈

       request.setCharacterEncoding("UTF-8");
        response.setContentType ("text/html,charset=UTF-8");
        设置服务器响应编码
        response.setCharacterEncoding("UTF-8");

这是注解,"/ServletCancel")是他的映射路径

@WebServlet( "/ServletCancel")

只要点了记住密码,参数就会到cookie里,可以在浏览器下按f12 点击application–>cookie中查看保存了的cookie值

if ("true".equals(remeber)){
                Cookie cookie1 = new Cookie("remeber", remeber );
                cookie1.setMaxAge(60*60*666);
                response.addCookie(cookie1);
                cookie1.setPath("/");
                Cookie cookie2 = new Cookie("username",  URLEncoder.encode(username, "UTF-8"));
                cookie2.setMaxAge(60*60*60);
                cookie2.setPath("/");
                response.addCookie(cookie2);
                Cookie cookie3 = new Cookie("password", password);
                cookie3.setMaxAge(60*60*66);
                cookie3.setPath("/");
                response.addCookie(cookie3);}
            //用户名密码错误则重新登录 跳转到登录界面

这是在jsp页面中写的代码,用来获取我们的cookie值,然后填充到表单中,最后在界面显示出来。

 String username ="";
          String password ="";
                  Cookie[] cookies = request.getCookies();
          for (int i=0; i<cookies.length;i++){
              if ("username".equals(cookies[i].getName())){
                  username=URLDecoder.decode(cookies[i].getValue(), "UTF-8");
              }else if("password".equals(cookies[i].getName())){
                  password = cookies[i].getValue();
              }
          }

差不多也就是这些。如果还报异常的话,记得一定去百度,靠自己才是最好的,不要太过依赖别人。如果有表达不当的,请多谅解,也请多多指教。
代码我传到华为云了,有需要的可以去下载一下。

华为云链接

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值