首页 > 数据库 >Javaweb实现简易记事簿 jdbc实现Java连接数据库

Javaweb实现简易记事簿 jdbc实现Java连接数据库

时间:2024-06-18 14:34:56浏览次数:23  
标签:username jdbc Java request 记事簿 stmt SQLException null public

//注册- [ ] 获取register的数据,从表单传过来

将(账户,密码,用户名)上面的数据写入数据库中,用jdbc(插入)加载数据库驱动,连接数据库,发送SQL

加载数据库有可能失败保险起见抛一个异常

返回判断,如果注册成功则提醒用户注册成功,并且跳转到登录页面进行登录。如果注册失败则提醒用户注册失败,并返回到注册页面。

最后关闭数据库

等等

//登录- [ ] 去数据库里面的user表中查询看能不能找到对应相应的用户,如果找到能不能匹配他相应的密码看一不一样。

接收来自login输入的值:用户名和密码。将用户名与数据库的usercode进行查找(加载数据库驱动,然后连接数据库,然后发送SQL)

将密码取出来与接收到的密码进行匹配,如果两个密码一致,则证明登录成功。如果不一致则说明密码输入错误。

如果找不到则说明用户名错误

然后加入语句来提示。
//相关代码
import jakarta.servlet.;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.
;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.time.LocalDate;

//主界面
@WebServlet("/Main")
public class Main implements Servlet{
private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException{
    this.config = config;
}

@Override
public ServletConfig getServletConfig(){
    return config;
}

@Override
public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException{
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;UTF-8");

    Connection conn = null;
    Statement stmt = null;
    ResultSet rsId = null, rsEvent = null;

    try{
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HTTPServer", "root", "lcy333668");
        stmt = conn.createStatement();

        HttpSession session = ((HttpServletRequest)request).getSession(false);

        if(session == null || session.getAttribute("username") == null){
            RequestDispatcher dispatcher = request.getRequestDispatcher("/LogOutMain.html");
            dispatcher.forward(request, response);
        }
        else{
            PrintWriter out = response.getWriter();
            String username = (String)session.getAttribute("username");

            boolean hasEvent = false;
            rsId = stmt.executeQuery("select userid from users where username = '" + username + "'");
            rsId.next();
            int userid = rsId.getInt(1);
            rsEvent = stmt.executeQuery("select date from e" + userid + " order by date");
            if(rsEvent.next()){
                Date eventDate = rsEvent.getDate(1);
                Date now = Date.valueOf(LocalDate.now());
                if(now.equals(eventDate)) hasEvent = true;
            }

            out.print("""
                <html lang="zh-CN">
                    <head>
                        <meta charset="utf-8"/>
                        <title>日历</title>
                        <style>
                            .right-align{
                              text-align: right;
                            }
                          </style>
                    </head>
                    <body>
                        <div class="right-align">
                            <strong>你好 <a href="/crm/UserInfo">""" + username + """
                        </a><strong>
                        </div>
                        <br><br><br><br><br><br><br><br>
                        <script type="text/javascript">
                            var date = new Date();
                            var year = date.getFullYear();
                            var month = date.getMonth();
                            var day = date.getDate();
                            var dayOfWeek = date.getDay();
                            var arr = ["日", "一", "二", "三", "四", "五", "六"];
                            document.write("<h1><center>" + year + "年" + (month + 1) + "月" + day + "日</center></h1><br><center><h2>星期" + arr[dayOfWeek] + "</h2></center>");
                        </script>
                                    
                        <br><br><br><br><br><br><br><br>
                        <center>
                            <a href="/crm/LogOut">退出登录</a>&nbsp;&nbsp;&nbsp;
                            <a href="/crm/Close">账号注销</a>&nbsp;&nbsp;&nbsp;
                            <a href="/crm/Events">查看事件""" + (hasEvent ? "(今日有待办)" : "<br>") + """
                        </a>
                        </center>
                    </body>
                </html>
                """);
        }
    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(conn != null)
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(stmt != null)
            try{
                stmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsId != null)
            try{
                rsId.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsEvent != null)
            try{
                rsEvent.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
    }
}

@Override
public String getServletInfo(){
    return "Main";
}

@Override
public void destroy(){

}

}
{
private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException{
    this.config = config;
}

@Override
public ServletConfig getServletConfig(){
    return config;
}

@Override
public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException{
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;UTF-8");

    Connection conn = null;
    Statement stmt = null;
    ResultSet rsId = null, rsEvent = null;

    try{
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HTTPServer", "root", "lcy333668");
        stmt = conn.createStatement();

        HttpSession session = ((HttpServletRequest)request).getSession(false);

        String year = request.getParameter("year");
        String month = request.getParameter("month");
        String date = request.getParameter("date");
        String event = request.getParameter("event");

        String username = (String)session.getAttribute("username");
        rsId = stmt.executeQuery("select userid from users where username = '" + username + "'");
        rsId.next();
        int userid = rsId.getInt(1);

        if(year == null || year.isEmpty() || month == null || month.isEmpty() || date == null || date.isEmpty()
            || event == null || event.isEmpty()){
            RequestDispatcher dispatcher = request.getRequestDispatcher("/UserAct/NullEvent.html");
            dispatcher.forward(request, response);
        }
        else{
            rsEvent = stmt.executeQuery("select * from e" + userid + " where date = '" + year + "-" + month + "-" + date + "' and info = '" + event + "'");
            if(rsEvent.next()){
                RequestDispatcher dispatcher = request.getRequestDispatcher("/UserAct/SameEvent.html");
                dispatcher.forward(request, response);
            }
            else{
                stmt.executeUpdate("insert into e" + userid + " values('" + year + "-" + month + "-" + date + "', '" + event + "')");
                stmt.executeUpdate("update users set eventCnt = eventCnt + 1 where username = '" + username + "'");
            }

            ((HttpServletResponse)response).sendRedirect("/crm/Events");
        }

    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(conn != null)
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(stmt != null)
            try{
                stmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsId != null)
            try{
                rsId.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsEvent != null)
            try{
                rsEvent.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
    }
}

@Override
public String getServletInfo(){
    return "UserAct.AddEvent";
}

@Override
public void destroy(){

}

}
package UserAct;

import jakarta.servlet.;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.
;
import java.io.;
import java.sql.
;

//登出
try{
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HTTPServer", "root", "lcy333668");
stmt = conn.createStatement();

        rs = stmt.executeQuery("select userid from users where username = '" + username + "'");
        rs.next();
        int userid = rs.getInt(1);

        stmt.executeUpdate("delete from users where username = '" + username + "'");
        stmt.execute("drop table e" + userid);

        session.invalidate();
        PrintWriter out = response.getWriter();
        out.print("""               
                <html>
                    <head>
                        <meta charset="utf-8"/>
                        <title>注销成功</title>
                    </head>
                    <body>
                        <h1>账号已注销!</h1>
                        <a href="/crm/Main">回到主页面</a>
                    </body>
                </html>
        """);

    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(conn != null)
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(stmt != null)
            try{
                stmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rs != null)
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
    }
}

@Override
public String getServletInfo(){
    return "UserAct.Close";
}

@Override
public void destroy(){

}

package UserAct;

import jakarta.servlet.;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.
;
import java.io.;
import java.sql.
;

//登出
@WebServlet("/UserAct.DeleteEvent")
public class DeleteEvent implements Servlet{
private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException{
    this.config = config;
}

@Override
public ServletConfig getServletConfig(){
    return config;
}

@Override
public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException{
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;UTF-8");

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null, rsId = null, rsEvent = null;;

    try{
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HTTPServer", "root", "lcy333668");
        stmt = conn.createStatement();

        HttpSession session = ((HttpServletRequest)request).getSession(false);
        String username = (String)session.getAttribute("username");

        String req = request.getParameter("delete");
        int line = 0;
        if(req == null || req.isEmpty()){
            RequestDispatcher dispatcher = request.getRequestDispatcher("/UserAct/NullDelete.html");
            dispatcher.forward(request, response);
        }
        else{
            line = Integer.parseInt(req);

            rs = stmt.executeQuery("select eventCnt from users where username = '" + username + "'");
            rs.next();
            int eventCnt = rs.getInt(1);

            if(line > eventCnt){
                RequestDispatcher dispatcher = request.getRequestDispatcher("/UserAct/SegmentationFault.html");
                dispatcher.forward(request, response);
            }
            else{
                rsId = stmt.executeQuery("select userid from users where username = '" + username + "'");
                rsId.next();
                int userid = rsId.getInt(1);

                rsEvent = stmt.executeQuery("select * from e" + userid + " order by date");
                while(line -- > 0) rsEvent.next();
                String event = rsEvent.getString("info");
                stmt.executeUpdate("delete from e" + userid + " where info = '" + event + "'");
                stmt.executeUpdate("update users set eventCnt = eventCnt - 1 where username = '" + username + "'");

                ((HttpServletResponse)response).sendRedirect("/crm/Events");
            }
        }

    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(conn != null)
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(stmt != null)
            try{
                stmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rs != null)
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsEvent != null)
            try{
                rsEvent.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsId != null)
            try{
                rsId.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
    }
}

@Override
public String getServletInfo(){
    return "UserAct.DeleteEvent";
}

@Override
public void destroy(){

}

}
package UserAct;

import jakarta.servlet.;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.
;
import java.io.;
import java.sql.
;
import java.time.LocalDate;

//登出
@WebServlet("/UserAct.Events")
public class Events implements Servlet{
private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException{
    this.config = config;
}

@Override
public ServletConfig getServletConfig(){
    return config;
}

@Override
public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException{
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;UTF-8");

    Connection conn = null;
    Statement stmt = null;
    ResultSet rsId = null, rsEvent = null;

    try{
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HTTPServer", "root", "lcy333668");
        stmt = conn.createStatement();

        HttpSession session = ((HttpServletRequest)request).getSession(false);
        String username = (String)session.getAttribute("username");

        rsId = stmt.executeQuery("select userid from users where username = '" + username + "'");
        rsId.next();
        int userid = rsId.getInt(1);
        rsEvent = stmt.executeQuery("select * from e" + userid + " order by date");

        int eventCnt = 0;
        String result = "";
        Date now = Date.valueOf(LocalDate.now());
        Date lastDate = null;
        while(rsEvent.next()){
            Date eventDate = rsEvent.getDate("date");
            if(eventDate.compareTo(now) < 0){
                int cnt = stmt.executeUpdate("delete from e" + userid + " where date = '" + eventDate + "'");
                stmt.executeUpdate("update users set eventCnt = eventCnt - " + cnt + " where username = '" + username + "'");
            }
            else if(!eventDate.equals(lastDate)){
                lastDate = eventDate;
                if(eventDate.equals(now))
                    result += "<h2>今日</h2>";
                else result += "<h2>" + eventDate + "</h2>";
            }

            eventCnt ++;
            result += "<strong>" + eventCnt + "</strong>&nbsp;&nbsp;&nbsp;" + rsEvent.getString("info") + "<br>";
        }

        PrintWriter out = response.getWriter();
        out.print("""
                <html>
                    <head>
                        <meta charset="utf-8"/>
                        <title>事件簿</title>
                    </head>
                    <body>
                        <form action="DeleteEvent" method="post">
                            <label for="username">删除事件(输入事件编号)</label> <br>
                            <input type="text" name="delete"/> <br><br>
                            <input type="submit" value="删除"/> *过期事件会自动删除,添加过期事件是无效添加<hr>
                        </form>
                        <form action="AddEvent" method="post">
                            <label for="username">添加事件</label> <br>
                            
                            <label for="username">日期</label>&nbsp;&nbsp;
                            <input type="text" name="year"/>年&nbsp;
                            <input type="text" name="month"/>月&nbsp;
                            <input type="text" name="date"/>日 <br><br>
                            
                            <textarea rows="10" cols="40" name="event" placeholder="在此输入具体内容"></textarea> <br><br>
                            
                            <input type="submit" value="添加"/><hr>
                        </form>
                        <a href="Main">返回主界面</a> <br><br>
                        <h1>事件簿</h1>""" + result + """
                    </body>
                </html>
        """);

    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(conn != null)
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(stmt != null)
            try{
                stmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsEvent != null)
            try{
                rsEvent.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rsId != null)
            try{
                rsId.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
    }
}

@Override
public String getServletInfo(){
    return "UserAct.Events";
}

@Override
public void destroy(){

}

}
package UserAct;

import jakarta.servlet.;
import jakarta.servlet.annotation.WebServlet;
import java.io.
;
import jakarta.servlet.http.;
import java.sql.
;

//用户信息
@WebServlet("/UserAct.UserInfo")
public class UserInfo implements Servlet{
private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException{
    this.config = config;
}

@Override
public ServletConfig getServletConfig(){
    return config;
}

@Override
public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException{
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;UTF-8");

    HttpSession session = ((HttpServletRequest)request).getSession(false);
    String username = (String)session.getAttribute("username");
    int userid = 0, eventCnt = 0;

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    try{
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/HTTPServer", "root", "lcy333668");
        stmt = conn.createStatement();

        PrintWriter out = response.getWriter();

        rs = stmt.executeQuery("select userid, eventCnt from users where username = '" + username + "'");
        rs.next();
        userid = rs.getInt(1);
        eventCnt = rs.getInt(2);

        out.print("""
                <html lang="zh-CN">
                    <head>
                        <meta charset="utf-8"/>
                        <title>用户信息</title>
                    </head>
                    <body>
                        <h1>""" + username + """
                        </h1> <hr>
                        <h2>用户id</h2>""" + userid + """
                        <br>
                        <h2>用户事件数量</h2>""" + eventCnt + """
                        <br><br>
                        <a href="#" onclick="window.history.back(); return false">返回</a>
                    </body>
                </html>
        """);

    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(conn != null)
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(stmt != null)
            try{
                stmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        if(rs != null)
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
    }
}

@Override
public String getServletInfo(){
    return "UserAct.UserInfo";
}

@Override
public void destroy(){

}

}

标签:username,jdbc,Java,request,记事簿,stmt,SQLException,null,public
From: https://www.cnblogs.com/qgmz/p/18254267

相关文章

  • java之sql注入代码审计
    java之sql注入代码审计前言其实找到漏洞原因很简单,主要想学习一下JDBCsql的过程JDBC简单介绍Java通过java.sql.DriverManager来管理所有数据库的驱动注册,所以如果想要建立数据库连接需要先在java.sql.DriverManager中注册对应的驱动类,然后调用getConnection方法才能连接上数......
  • 基于Java+SpringBoot+Vue+elementUI的学生宿舍管理平台的设计与开发
    第一章绪论1.1选题背景和意义1.2国内外学生宿舍管理平台现状第二章相关技术简介2.1开发工具介绍2.1.1IDEA2.1.2VSCode2.1.3Navicat2.1.4宝塔面板2.2关键技术介绍2.2.1Java2.2.2SpringBoot2.2.3Mybatis2.2.4Vue2.2.5MySQL2.2.6Redis2.2.7E......
  • javascript-obfuscator混淆
    安装npminstalljavascript-obfuscator-g配置重度混淆,性能低性能下降50-100%{"compact":true,"controlFlowFlattening":true,"controlFlowFlatteningThreshold":0.75,//设置为0到1之间的值"deadCodeInjection":tr......
  • linux 配置java环境变量
    1.下载与安装查看操作系统位数uname-m如果输出是x86_64,那么你的系统是64位的;如果输出是i686或i386,那么你的系统是32位的。openJDK下载地址:清华大学开源软件镜像站以jdk11为例,下载地址为:https://mirror.tuna.tsinghua.edu.cn/Adoptium/11/jdk/x64/linux/OpenJDK11U-jdk_x......
  • JavaScript ES6 新特性探索:Proxy 解锁编程新境界
    个人主页:学习前端的小z个人专栏:JavaScript精粹本专栏旨在分享记录每日学习的前端知识和学习笔记的归纳总结,欢迎大家在评论区交流讨论!ES5、ES6介绍文章目录......
  • 【JavaWeb】基于Filter和Interceptor实现登录认证
    前言HTTP协议是无状态协议,指的是每一次请求都是独立的,下一次请求并不会携带上一次请求的数据。因为HTTP协议是无状态的,两次请求之间是独立的,所以是无法判断这个员工到底登陆了没有。登录校验的具体的实现思路可以分为两部分:在员工登录成功后,需要将用户登录成功的信息存起来,记......
  • javaScript获取dom元素的常见方法
    前端开发都知道在react、vue等框架没问世之前,开发人员要实现用户对网页元素进行操作时,其中就包括dom元素的选择,不可避免的就是要获取到目标元素再接着编写功能代码。废话少说让我们来看看javaScript获取dom元素的常见方法元素js获取dom元素的方法常有以下几种:1.两个......
  • JavaSE: 基础
    定义:java是sun公司推出的跨平台,面向对象,的一种高级语言面向对象:是一种编程方式,它将现实中的事务抽象为对象,通过对象之间的交互模拟现实世界的情景,面向对象的编程语言中,一切都被视为对象,都有自己的属性和方法。其中对象是由一组数据(属性)和行为(方法)组成,数据包括静态信息,状态,行......
  • java 使用Log4j进行日志记录
    要在Java项目中使用Log4j进行日志记录,需要经过以下步骤:添加Log4j依赖:在项目的pom.xml文件中,添加Log4j依赖。例如:<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency>创建Log4j配置文件:......
  • 又跳槽!3年Java经验收割成都大厂的面试心得(干货满满&文末有福利)
    中厂->阿里->字节,成都->杭州->成都系列文章目录和关于我0.前言笔者在不足两年经验的时候从成都一家金融科技中厂跳槽到杭州阿里淘天集团,又于今年5月份从杭州淘天跳槽到成都字节。自认为自己在面试这方面有一点心得,处于记录和分享的目的便有了此文,此文纯主观,也许对3年社招的同学......