BBS论坛留言板servlet+jsp+jdbc+mysql

由于代码较多,这里只给出几个模块的代码,想看全部代码请点击链接:
http://download.csdn.net/detail/broccoli2/9874505

DBUtils.java

package dbUtils;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;

import entity.Message;

public class DBUtils {

    public static Connection getConn() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/bbs";
        String username = "root";
        String password = "123456";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }



    public static int insert(String username,String password) {
        Connection conn = getConn();
        int i = 0;
        String sql = "insert into user (username,password) values(?,?)";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
           // pstmt.setInt(1, 2);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            i = pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    public static Integer getAUser(String username,String password) {
        Connection conn = getConn();
        String sql = "select * from user where username=? and password=?";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = (ResultSet) pstmt.executeQuery();




            /*System.out.println("============================"); while (rs.next()) { System.out.print(rs.getInt("id") + "\t"); System.out.print(rs.getString("username") + "\t"); System.out.println(rs.getString("password") + "\t"); } System.out.println("============================");*/
            System.out.println("查询数据成功!");

            if(rs.next()){
                return 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean insertMessage(String username,String subject,String content,String notetime,String ntime){

        Connection conn = getConn();
        String sql = "insert into message (noteuser,subject,content,notetime,ntime) values(?,?,?,?,?)";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, subject);
            pstmt.setString(3, content);
            pstmt.setString(4, notetime);
            pstmt.setString(5, ntime);
            int i = pstmt.executeUpdate();
        if(i != 0){
            System.out.println("留言成功!");
            return true;
        }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return false;
    }


    public static List<Message> getAllMessage(){
        Connection conn = getConn();
        String sql = "select * from message";
        PreparedStatement pstmt;
        List<Message> list = new ArrayList<Message>();
        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);

            ResultSet rs = (ResultSet) pstmt.executeQuery();
            while(rs.next()){
                Message message = new Message();
                message.setNoteuser(rs.getString("noteuser"));
                message.setSubject(rs.getString("subject"));
                message.setContent(rs.getString("content"));
                message.setNotetime(rs.getDate("notetime"));
                message.setNtime(rs.getTime("ntime"));
                list.add(message);
            }

            return list;
           /* while (rs.next()) { System.out.print(rs.getString("noteuser") + "\t"); System.out.print(rs.getString("subject") + "\t"); System.out.println(rs.getString("content") + "\t"); }*/
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //返回记录数目
    public static int  count(){
        Connection conn = getConn();
        String sql = "select count(*) from message";
        PreparedStatement pstmt;
        int i = 0;
        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);
            i = pstmt.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return i;
    }



    public static boolean deleteMessage(String notetime){
        Connection conn = getConn();
        String sql = "delete from message where ntime=?";
        PreparedStatement pstmt;

        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);
            pstmt.setString(1, notetime);
            int re = pstmt.executeUpdate();
            if(re>0){
                return true;
            }


        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }


}

后太使用的是servlet。
LoginAction.java

package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dbUtils.DBUtils;
import entity.Message;

public class LoginAction extends HttpServlet {

    /** * Constructor of the object. */
    public LoginAction() {
        super();
    }

    /** * Destruction of the servlet. <br> */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //System.out.println(username+":"+password);

        HttpSession session = request.getSession(); 
        //request.setAttribute("username", username);




        session.setAttribute("username", username);
        System.out.println(session.getAttribute("username"));


        DBUtils.getConn();
        Integer temp = DBUtils.getAUser(username, password);
        if(temp!=null){
            List<Message> list = DBUtils.getAllMessage();
            session.setAttribute("messageList", list);
            //System.out.println(list.listIterator());
            /*Message m = list.get(0); System.out.println(m.getContent()+"*************");*/
            response.sendRedirect("home.jsp");
        }




        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println(" <BODY>");
        out.println("请输入正确的用户名和密码! ");
        out.println(" </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println(" <BODY>");
        out.print(" This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println(" </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */
    public void init() throws ServletException {
        // Put your code here
    }

}

ManagerAction.java

package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dbUtils.DBUtils;
import entity.Message;

public class MessageAction extends HttpServlet {

    /** * */
    private static final long serialVersionUID = 1L;

    /** * Constructor of the object. */
    public MessageAction() {
        super();
    }

    /** * Destruction of the servlet. <br> */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String method = request.getParameter("method");
        String ntime2 = request.getParameter("ntime");
        /*System.out.println(method+":method"); System.out.println(ntime2+":notetime");*/
        HttpSession session = request.getSession(); 

        if(method.equals("deleteNote")){
            DBUtils.deleteMessage(ntime2);
            List<Message> list = DBUtils.getAllMessage();
            session.setAttribute("messageList", list);
            response.sendRedirect("home.jsp");
        }

        String subject = request.getParameter("subject");
        String content = request.getParameter("content");

        if(method.equals("addMessage")){

          SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          Date beginDate = new Date();
          Calendar date = Calendar.getInstance();
          date.setTime(beginDate);
          date.set(Calendar.DATE,date.get(Calendar.DATE));
          String today = dft.format(date.getTime());  
    //System.out.println(today+"&&&&&&&&&&&&&&&&&&&");

        Date ctime = new Date();
        /*DateFormat df3 = DateFormat.getTimeInstance();//只显示出时分秒 Calendar cal = Calendar.getInstance(); int hour=cal.get(Calendar.HOUR);//小时 int minute=cal.get(Calendar.MINUTE);//分 int second=cal.get(Calendar.SECOND);//秒 */     
       long ms = ctime.getTime();



        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        String ntime = formatter.format(ms);
        //System.out.println(ntime+"**************");


        String username = (String) session.getAttribute("username");

        if(DBUtils.insertMessage(username,subject, content,today,ntime)){
            List<Message> list = DBUtils.getAllMessage();
            session.setAttribute("messageList", list);
            response.sendRedirect("home.jsp");
        }

        }




    }

    /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println(" <BODY>");
        out.print(" This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println(" </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */
    public void init() throws ServletException {
        // Put your code here
    }

}

home.jsp

<%@ page language="java" import="java.util.*,entity.Message" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'home.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->

  </head>

  <body>
  <div align="center">
  <h1>留言板</h1>
  <table border="1px" width="50%" cellspacing="0" cellpadding="0" bordercolor="#F0F0F0" bordercolorlight="#F0F0F0" bordercolordark="white">
    <tr>
    <td>留言人</td>
    <td>留言主题</td>
    <td>留言内容</td>
    <td>留言时间</td>
    <td>操作</td>
    </tr>
    <c:if test="${not empty messageList}">
    <c:forEach var="message" items="${messageList}" varStatus="status">
    <tr>
    <td>${message.noteuser}</td>
    <td>${message.subject}</td>
    <td>${message.content}</td>
    <td>${message.notetime}&nbsp${message.ntime}</td>
    <td><a href="messageAction?ntime=${message.ntime}&method=deleteNote">删除</a></td>
    </tr>
    </c:forEach>
  </c:if>
  </table>
  <a href="addMessage.jsp">添加留言</a>

  </div>
  </body>
</html>

实体类:
Mssage.java

package entity;

import java.io.Serializable;
import java.sql.Time;
import java.util.Date;

public class Message implements Serializable{

    private String noteuser;
    private String subject;
    private String content;
    private Date notetime;
    private Time ntime;
    public String getNoteuser() {
        return noteuser;
    }
    public void setNoteuser(String string) {
        this.noteuser = string;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Date getNotetime() {
        return notetime;
    }
    public void setNotetime(Date notetime) {
        this.notetime = notetime;
    }
    public Time getNtime() {
        return ntime;
    }
    public void setNtime(Time ntime) {
        this.ntime = ntime;
    }   
}
全部评论

相关推荐

11-07 03:09
深圳大学 C++
实习秋招做的很差,也想总结一下自己的大学生涯吧。不算太摆,但是很迷。0.大学前高考发挥超常,才来到深大计软。大学前暑期基本上都是玩游戏了。接触了python(李笑来)但是没接触到online&nbsp;judge,也没去多了解编程生态、计算机行业。背了背单词,但是没去规划指标如六级,没制定计划不了了之。1.大一军训时去了校ACM培训,当时dev编译器都不会下载。军训期间积极看B站大学c语言课程。力扣,牛客都是知道的,但是没有成为很好的跳板。第二次培训,看不懂cpp的&nbsp;cin&amp;gt;&amp;gt;,网上搜了也没搞懂,再加上周末跟训得三个多小时,感觉跟不上放弃了。自费报了蓝桥杯,混了省二跟着一些机构课程学习,走的cpp路线。暑假在linux上熟悉vim操作。2.大二朝花夕拾,又去参加ACM训练,跟了一年,寒假都在码&nbsp;带懒标记的线段树。codeforce和力扣赛都在打打(竞赛还是有趣的)。集训队入队周赛打四场,校赛拿金,面试时表现差,说自己想就业,遂挂。当时四月多,2024华为软件精英挑战赛也在打,拿了80名(前64才有三等奖)。蓝桥杯国二。很多晚上跑步来消磨时间。3.大三上修了深大最强的计算机图形学,408找实习,投简历了说自己只有周末有空,遂没在找。也没看牛客真实行情。寒假随便做了个日志器,属于混过去了。当时接到字节的面试(人生处女面),前一天觉都睡不好,很紧张,手撕做的不好,话都说不利索了。面评脏。大三下找实习,cpp选手,没有很好经历、项目,运气好去了学校附近中厂实习。4.大四现在,貌似对开发不上心?没有好的offer(甚至hot100不会做)其实同届好多同学都拿的不错。还有保研C9的。嗯,考研吧。————对自己行为的分析:a.应试教育+应试家庭教育,我的个性是固执、遵规守矩的。b.还有莫名的孤独,明明有很多朋友,但还是没有很好的内驱力,没有坚定的理想。c.自己没有很好的调研、探索和规划能力。大家也可以锐评一下😊
_Matrice_:差不多的性格,不然不会本科时硬杠cpp(那个时候还没有大模型,啃完一整本primer和习题,还是做不出来什么东西),还找不到方向,相比之下学习一些应用层的同学已经能够参考别人的方法做出实用的应用了。学东西,找实习,感觉更多地是出于和别人比较,而不是自我内驱。不过...正如deft所说,人生不需要他人的建议,所以也没有标准化的路径,在能够自食其力的背景下慢慢找到自己的生活方式吧...。另外面试很多时候看运气、眼缘
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务