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} ${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;
}
}