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

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

时间:2024-06-17 15:53:55浏览次数:27  
标签:username jdbc Java rs request 记事簿 stmt null public

//相关代码
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.
;

//登出
@WebServlet("/UserAct.Close")
public class Close 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);
    if(session == null || session.getAttribute("username") == null){
        System.out.println("NullSession");
        return;
    }
    else System.out.println("YES");
    String username = (String)session.getAttribute("username");

    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();

        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.AddEvent")
public class AddEvent 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 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 Login;

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

//登录处理
@WebServlet("/Login.Login")
public class Login 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{
    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();

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        RequestDispatcher dispatcher = null;
        if(username == null || username.isEmpty())
            dispatcher = request.getRequestDispatcher("/Login/NullUsername.html");
        else if(password == null || password.isEmpty())
            dispatcher = request.getRequestDispatcher("/Login/NullPassword.html");
        else{
            rs = stmt.executeQuery("select password from users where username = '" + username + "' and password = '" + password + "'");
            if(rs.next()){
                HttpSession session = ((HttpServletRequest)request).getSession();
                session.setAttribute("username", username);

                ((HttpServletResponse)response).sendRedirect("/crm/Main");
            }
            else{
                dispatcher = request.getRequestDispatcher("/Login/Incorrect.html");
                dispatcher.forward(request, response);
            }
        }

        if(dispatcher != null) dispatcher.forward(request, response);

    }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 "Login.Login handling form submissions";
}

@Override
public void destroy(){

}

}
package SignUp;

import jaka rta.servlet.;
import jakarta.servlet.annotation.WebServlet;
import java.io.
;
import java.sql.*;

//注册处理
@WebServlet("/SignUp.SignUp")
public class SignUp 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{
    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();

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        System.out.println(password + " " + confirmPassword);

        RequestDispatcher dispatcher = null;
        if(username == null || username.isEmpty())
            dispatcher = request.getRequestDispatcher("/SignUp/NullUsername.html");
        else if(!nameIsValid(username, stmt))
            dispatcher = request.getRequestDispatcher("/SignUp/InvalidUsername.html");
        else if(password == null || password.isEmpty())
            dispatcher = request.getRequestDispatcher("/SignUp/NullPassword.html");
        else if(!passwordIsValid(password))
            dispatcher = request.getRequestDispatcher("/SignUp/InvalidPassword.html");
        else if(confirmPassword == null || confirmPassword.isEmpty())
            dispatcher = request.getRequestDispatcher("/SignUp/NullConfirmPassword.html");
        else if(!confirmPassword.equals(password))
            dispatcher = request.getRequestDispatcher("/SignUp/UnequalPassword.html");
        else{
            boolean flag = true;
            rs = stmt.executeQuery("select username from users where username = '" + username + "'");
            while(rs.next())
                if(username.equals(rs.getString(1))){
                    dispatcher = request.getRequestDispatcher("/SignUp/UserNameExists.html");
                    flag = false;
                    break;
                }

            if(flag){
                //添加注册成功的用户,并添加一张表,用来记录该用户的事件
                stmt.executeUpdate("insert into users(username, password, eventCnt) values('" + username + "', '" + password + "', 0)");
                rs = stmt.executeQuery("select userid from users where username = '" + username + "' order by userid desc");
                rs.next();
                int userid = rs.getInt(1);
                stmt.execute("drop table if exists e" + userid);
                stmt.execute(
                        "create table e" + userid + "(" +
                                "date date not null," +
                                "info varchar(1000))"
                );

                dispatcher = request.getRequestDispatcher("/SignUp/Successfully.html");
            }
        }
        if(dispatcher != null) dispatcher.forward(request, response);

    }catch(SQLException e){
        throw new RuntimeException(e);
    }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 "SignUp.SignUp handling form submissions";
}

@Override
public void destroy(){

}


//检查用户名的合法性
public static boolean nameIsValid(String name, Statement stmt){
    for(char i : name.toCharArray())
        if(i == '\\') return false;

    ResultSet rs =  null;
    try{
        rs = stmt.executeQuery("select length('" + name + "')");
        rs.next();
        if(rs.getInt(1) > 30) return false;
    }catch(SQLException e){
        e.printStackTrace();
    }finally{
        if(rs != null)
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
    }

    return true;
}
//检查密码的合法性
public static boolean passwordIsValid(String password){
    if(password.length() < 7 || password.length() > 16) return false;

    for(int i : password.toCharArray())
        if(i == '\\' || (i < 33 || i > 126)) return false;

    return true;
}

}

标签:username,jdbc,Java,rs,request,记事簿,stmt,null,public
From: https://www.cnblogs.com/lhyy/p/18252580

相关文章

  • [javascript]何为变量提升?
    【版权声明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权)https://www.cnblogs.com/cnb-yuchen/p/18252500出自【进步*于辰的博客】关于编译与解释,详述可查阅博文《[Java]知识点》中的【编译与解释】一栏。参考笔记二,P43.3、P46.1、P9.3。目录1、什么是“变量提升?2、va......
  • Java速成笔记 2024.6.17版
    变量:可以变化的容器不同变量可以存储不同类型的值变量声明方法:变量类型变量名=初始值;E.G.inta=1;变量类型:整型:intlong浮点数:floatdouble布尔:boolean字符串:String字符:char变量命名注意事项:不能重名不能以数字开头常量:关键字:final语法:finalfl......
  • 基于Java+Vue的采购管理系统:实现采购业务数字化(全套源码)
    前言:采购管理系统是一个综合性的管理平台,旨在提高采购过程的效率、透明度,并优化供应商管理。以下是对各个模块的详细解释:一、供应商准入供应商注册:供应商通过在线平台进行注册,填写基本信息和资质文件。资质审核:系统对供应商提交的资质文件进行自动或人工审核,确保供应商符......
  • JavaScript妙笔生花:打造沉浸式中国象棋游戏体验
    前言随着信息技术的飞速发展,Web开发领域也出现了翻天覆地的变化。JavaScript作为前端开发中不可或缺的编程语言,其重要性不言而喻。而当我们谈论到利用JavaScript打造一款沉浸式的中国象棋游戏体验时,我们不仅仅是在开发一个游戏,更是在进行一种文化的传承和创新。以下将探讨......
  • PTA 6-3 tjrac - Java集合类之Set的HashSet之常用方法的使用
    importjava.util.HashSet;importjava.util.Scanner;importjava.util.Set;publicclassMain{publicstaticvoidmain(String[]args){ Scannerscan=newScanner(System.in); Stringzi=scan.nextLine();//首先我们定义一个字符串输入; ......
  • PTA JAVA 7-5 sdust-Java-字符串集合求并集
    7-5sdust-Java-字符串集合求并集分数20全屏浏览切换布局作者 张峰单位 山东科技大学从键盘接收N个英文字符串(其中不同的字符串数量大于10),从头开始取5个不同的字符串放入一个集合S1,然后接着取5个不同的字符串放入另一个集合S2,按照字母顺序输出S1和S2的并集中的每个......
  • java从入门到精通
    java从入门到精通1.进制转换1.1二进制和十进制1.2八进制packagecom.itheima.variable;publicclassASCIIDemo1{publicstaticvoidmain(String[]args){//目标:掌握ASCII编码表的编码特点。System.out.println('a'+10);//97+10=10......
  • Java常见面试题分享-用Java实现LIS(最长递增子序列)算法
    问题描述编写一个函数,该函数接受一个整数列表作为参数,计算这个列表的最长递增子序列(LIS)的长度,这个也是动态规划中常见的问题。举一个典型的场景:用来查找股票价格的最大增长,比如股票价格是[12,13,11,14,15,16,10,9,8,7],股票价格的最大增长是[12,13,14,15,......
  • 持续性学习-Day18(JavaWeb)
    JavaWeb1、基本概念web开发:web,表示可以从互联网上拿到一定的资源静态webhtml、css提供给所有人看的数据,始终不会发生变化动态web每个人在不同时间、不同地点,看到的信息各不相同技术栈:servlet/JSP、ASP、PHP在Java中,动态web资源开发的计数统称为Java......
  • JavaScript 面试问题及答案
    什么是JavaScript模块?答: JavaScript模块是可重复使用的代码片段,可以在文件之间导入和导出,从而提高模块化和可维护性。解释原型链的概念。答:原型链是JavaScript中的一项功能,它允许对象通过原型链从其他对象继承属性和方法。什么是高阶函数?答:高阶函数是可以将其他函数作......