首页 > 其他分享 >起个名字想半天小组的博客

起个名字想半天小组的博客

时间:2024-06-17 16:57:49浏览次数:20  
标签:username 小组 request 起个 博客 stmt import null public

关于Javaweb实现简易记事簿这一项目的博客

1,项目的功能架构图:

2,项目的功能简述:

用户进入网址,便可看见当前的时间。

除此之外他可以选择注册并登录,以便进入可以添加,修改,删除事件的页面。

可以添加用户认为重要的事件,以便提醒自己及时做完需要做的事情。


3,项目的分工:
详见考核表

4,具体代码:
详见文件夹

5,还是展示一下每个成员的核心代码:
//1号成员:
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 Login;

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

//登录界面
//同SignUpUI,投递html页面
@WebServlet("/Login.LoginUI")
public class LoginUI 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");

    RequestDispatcher dispatcher = request.getRequestDispatcher("/Login/Login.html");
    dispatcher.forward(request, response);
}

@Override
public String getServletInfo(){
    return "Login.LoginUI";
}

@Override
public void destroy(){

}

}
package SignUp;

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

//注册处理
@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(correctInfo(username, password, confirmPassword, stmt, dispatcher, request)){
            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){
                Date date = java.sql.Date.valueOf(LocalDate.now());
                System.out.println(date);

                //添加注册成功的用户,并添加一张表,用来记录该用户的事件
                stmt.executeUpdate("insert into users(username, password, eventCnt, signupDate) values('%s', '%s', 0, '%s')".formatted(username, password, date));
                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 correctInfo(String username, String password, String confirmPassword, Statement stmt, RequestDispatcher dispatcher, ServletRequest request){
    boolean flag = false;

    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
        flag = true;

    return flag;
}

//检查用户名的合法性
public static boolean nameIsValid(String name, Statement stmt){
    if(name.charAt(0) >= '0' && name.charAt(0) <= '9') return false;
    for(char i : name.toCharArray())
        if(((i >= 32 && i <= 47) || (i >= 58 && i <= 64) || (i >= 91 && i <= 96) || (i >= 123 && i <= 126)) && i != '&' && 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;
}

}
package SignUp;

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

//注册界面
//同LoginUI,投递html页面
@WebServlet("/SignUp.SignUpUI")
public class SignUpUI 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");

    RequestDispatcher dispatcher = request.getRequestDispatcher("/SignUp/SignUp.html");
    dispatcher.forward(request, response);
}

@Override
public String getServletInfo(){
    return "SignUp.SignUpUI";
}

@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);
        if(session == null || session.getAttribute("username") == null){
            RequestDispatcher dispatcher = request.getRequestDispatcher("/NullSession.html");
            dispatcher.forward(request, response);
        }
        else{
            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.
;

//登出
@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){
        RequestDispatcher dispatcher = request.getRequestDispatcher("/NullSession.html");
        dispatcher.forward(request, response);
        return;
    }
    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.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);
        if(session == null || session.getAttribute("username") == null){
            RequestDispatcher dispatcher = request.getRequestDispatcher("/NullSession.html");
            dispatcher.forward(request, response);
        }
        else{
            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;
import java.util.ArrayList;
import java.util.List;

//登出
@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);
        if(session == null || session.getAttribute("username") == null){
            RequestDispatcher dispatcher = request.getRequestDispatcher("/NullSession.html");
            dispatcher.forward(request, response);
        }
        else{
            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;
            List<Date> datesToDelete = new ArrayList<>();

            while(rsEvent.next()){
                boolean flag = true;
                Date eventDate = rsEvent.getDate("date");
                if(eventDate.compareTo(now) < 0){
                    datesToDelete.add(eventDate);
                    flag = false;
                }else if(!eventDate.equals(lastDate)){
                    lastDate = eventDate;
                    if (eventDate.equals(now))
                        result += "<h2>今日</h2>";
                    else result += "<h2>" + eventDate + "</h2>";
                }

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

            for(Date date : datesToDelete){
                int cnt = stmt.executeUpdate("delete from e" + userid + " where date = '" + date + "'");
                stmt.executeUpdate("update users set eventCnt = eventCnt - " + cnt + " where username = '" + username + "'");
            }

            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 jakarta.servlet.http.
;
import java.io.*;

//登出
@WebServlet("/UserAct.LogOut")
public class LogOut 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){
        RequestDispatcher dispatcher = request.getRequestDispatcher("/NullSession.html");
        dispatcher.forward(request, response);
    }
    else{
        session.invalidate();
        ((HttpServletResponse)response).sendRedirect("/crm/Main");
    }
}

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

@Override
public void destroy(){

}

}
package UserAct;

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

//用户信息
@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);
    if(session == null || session.getAttribute("username") == null){
        RequestDispatcher dispatcher = request.getRequestDispatcher("/NullSession.html");
        dispatcher.forward(request, response);
        return;
    }

    String username = (String)session.getAttribute("username");
    int userid = 0, eventCnt = 0;
    LocalDate date = null;

    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, signupDate from users where username = '" + username + "'");
        rs.next();
        userid = rs.getInt(1);
        eventCnt = rs.getInt(2);
        date = rs.getDate(3).toLocalDate();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        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>
                        <h2>用户注册日期</h2>""" + date.format(dtf) + """
                        <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(){

}

}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

//初始化数据库/重构数据库
public class DataBaseInit{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try{
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "lcy333668");
stmt = conn.createStatement();

        //重构数据库
        stmt.execute("drop database if exists HTTPServer");
        stmt.execute("create database HTTPServer");
        stmt.execute("use HTTPServer");

        //创建用户表:
        //用户名长度不超过30长度(一个汉字为3个长度),不得含有'\'符号
        //密码7-16位,只允许含有数字、字母和除'\'以外的特殊符号
        stmt.execute("drop table if exists users");
        stmt.execute(
                "create table users(" +
                        "username varchar(30) not null," +
                        "userid int not null auto_increment," +
                        "password varchar(17) not null," +
                        "eventCnt int not null default 0," +
                        "signupDate date not null," +
                        "primary key(userid));"
        );
        stmt.execute("alter table users auto_increment = 10000");

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

}
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.jsp");
            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>
                        
                        <script>
                            function updateTime() {
                                var now = new Date();
                                var dayOfWeek = now.getDay();
                                var arr = ["日", "一", "二", "三", "四", "五", "六"];
                                var formattedTime = now.getFullYear() + '年' +
                                    ('0' + (now.getMonth() + 1)).slice(-2) + '月' +
                                    ('0' + now.getDate()).slice(-2) + '日\\n' +
                                    ('0' + now.getHours()).slice(-2) + ':' +
                                    ('0' + now.getMinutes()).slice(-2) + ':' +
                                    ('0' + now.getSeconds()).slice(-2) + '\\n\\n' +
                                    "星期" + arr[dayOfWeek];
                                document.getElementById("currentTime").innerText = formattedTime;
                            }
                                        
                            setInterval(updateTime, 1000);
                            window.onload = updateTime;
                        </script>
                    </head>
                    
                    <body>
                        <div class="right-align">
                            <strong>你好 <a href="/crm/UserInfo">""" + username + """
                        </a><strong>
                        </div>
                        
                        <br><br><br><br><br><br><br><br>
                            <div style="text-align: center;">
                                <h1><span id="currentTime"><%= request.getAttribute("currentTime") %></span></h1>
                            </div>
                        <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(){

}

}

标签:username,小组,request,起个,博客,stmt,import,null,public
From: https://www.cnblogs.com/lhyy/p/18252633

相关文章

  • 3.16博客
    演示数据库在本教程中,我们将使用RUNOOB样本数据库。下面是选自"Websites"表的数据:+----+--------------+---------------------------+-------+---------+|id|name|url|alexa|country|+----+--------------+-------------------......
  • CogVLM/CogAgent环境搭建&推理测试-CSDN博客
    引子最近在关注多模态大模型,之前4月份的时候关注过CogVLM(https://blog.csdn.net/zzq1989_/article/details/138337071?spm=1001.2014.3001.5501)。模型整体表现还不错,不过不支持中文。智谱AI刚刚开源了GLM-4大模型,套餐里面包含了GLM-4V-9B大模型,模型基于GLM-4-9B的多模态模型GL......
  • 博客园众包平台:50w+驱动开发大单,全园找人接单
    园子的众包平台在小步慢跑、量力而行地向前推进着,一边在召集早期合作开发者,一边在等单来。昨天就等来一单,而是很大很大的单子,报价50w-100w,也是很难很难的单子,发单后合作开发者中没人敢接单,于是才有了今天这篇全园找人接单。客户是一家做WiFi芯片的公司,想找人为自家的WiFi芯......
  • 一键搭建博客系统
    前言如今CSDN,博客园等充斥着大量的重复博客,有些甚至连样式都没有经过调整。为了寻求一个干净,简洁无广告的平台,选择了自己搭建一个博客,该系统使用的Halo2一键部署。 Halo一个强大易用的开源建站框架对比了很多博客系统,因为Halo外观更加简洁,并且使用Springboot开发(笔者Ja......
  • 6.14博客
    周五了太棒了学习内容:安卓packagecom.example.app_02;importorg.junit.Rule;importorg.junit.Test;importstaticorg.junit.Assert.*;importcom.example.app_02.entity.Record;importcom.example.app_02.utils.RecordDao;importjava.util.ArrayList;/** *......
  • 6.5博客
    python和工程数学俩实验真累啊python学习:importrefromcollectionsimportCounterimportrequestsfromlxmlimportetreeimportpandasaspdimportjiebaimportmatplotlib.pyplotaspltfromwordcloudimportWordCloudheaders={"User-Agent":"Mozilla......
  • 6.10博客
    放松也放松完了快考试了进入状态了该学习内容:安卓<?xmlversion="1.0"encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" ......
  • 5.18博客
    上午数据库下午计网要是工程数学老师有数据库老师的松弛感就好了学习内容:安卓<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="50dp"  android:background="#aaa......
  • 5.21博客
    又是周一!课这么多spring-boot就先放一放学习内容:安卓packagecom.example.app_02.database;importandroid.util.Log;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;publicclassMySQLCon......
  • 5.22博客
    还是上午计网下午建民老师的课,晚上又是跑步,今天跑得慢了点但是足足有七公里学习内容:安卓packagecom.example.app_02.entity;publicclassRecord{  privateStringstartTime;  privateStringendTime;  privateStringrecord;  publicRecord(){......