留言板案例
开发环境
java的jdk:jdk1.8.0_66
java的开发工具:eclipse(eclipse-photon)
数据库:MySQL Server 5.1
Web容器:apache-tomcat-8.5.32
jar包:c3p0-0.9.1.2.jar mysql-connector-java-5.1.6-bin.jar
配置文件
c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置 -->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql -->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
</c3p0-config>
注意:将c3p0-config.xml放在src下面
需要的两个表
用户表
用户表(tab_admin)
字段 | 描述 | 数据类型 | 约束 | 备注 |
---|---|---|---|---|
aid | 用户编号 | int | PK | 自动增长 |
aname | 密码 | varchar | Not null | |
password | 用户编号 | varchar | Not null |
留言表
留言表(tab_gestbook)
字段 | 描述 | 数据类型 | 约束 | 备注 |
---|---|---|---|---|
gst_id | 用户编号 | int | PK | 自动增长 |
aid | 用户编号 | int | UK | |
gst_title | 留言标题 | varchar | ||
gst_content | 留言内容 | varchar | ||
gst_time | 留言时间 | timestamp | ||
gst_ip | 用户的IP地址 | Varchar |
流程介绍
a.用户登录成功后,显示留言信息列表。如图:
b.用户点击“我要留言”,显示留言界面。如图:
c.点击“留言”,将数据写入数据库,并将返回到留言列表信息界面。
d.如果用户没有没有登录,则提示用户,需要登录才能查看留言
e.用户登录界面:
项目列表如下图片
控制器包下com.bbs.controller(Servlet)
AdminLoginServlet.java
package com.bbs.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bbs.dao.AdminDao;
import com.bbs.pojo.Admin;
public class AdminLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private AdminDao adminDao;
public AdminLoginServlet() {
super();
this.adminDao = new AdminDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
// 1.获取用户提交的信息
String strname = request.getParameter("aname");
String strpass = request.getParameter("password");
// 2.组织数据信息,调用Dao的业务方法
Admin admin=new Admin(strname,strpass);
Admin result=adminDao.login(admin);
// 3.根据结果返回到对应的页面或者下个Servlet
if(result!=null) {
request.getSession().setAttribute("logined", result);
response.sendRedirect("ListGestBookServlet");
return;
}
response.sendRedirect("login.jsp");
return;
}
}
InsertGestBookServlet.java
package com.bbs.controller;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bbs.dao.GestbookDao;
import com.bbs.pojo.Admin;
import com.bbs.pojo.Gestbook;
public class InsertGestBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private GestbookDao bookDao;
public InsertGestBookServlet() {
super();
this.bookDao = new GestbookDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
// 1.获取提交的留言数据
// gst_id 自动增长 default
// aid 会话中提取
// gst_title 表单提交过来
// gst_content 表单提交过来
// gst_time 当前时间 new Date();
// gst_ip 请求对象中包含有request.getRemoteAddr()
Admin admin=(Admin) request.getSession().getAttribute("logined");
Integer aid=admin.getAid();
String gst_title=request.getParameter("gst_title");
String gst_content=request.getParameter("gst_content");
Date gst_time=new Date();
String gst_ip=request.getRemoteAddr();
// 2.组织数据,通过Dao完成添加留言
Gestbook book=new Gestbook(aid, gst_title, gst_content, gst_ip, gst_time);
bookDao.insertGestbook(book);
// 3.返回到ListGestBookServlet重新提取所有浏览,并在list.jsp中显示新添加的数据内容
response.sendRedirect("ListGestBookServlet");
}
}
ListGestBookServlet.java
package com.bbs.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bbs.dao.AdminDao;
import com.bbs.dao.GestbookDao;
import com.bbs.pojo.Gestbook;
public class ListGestBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private GestbookDao gestBookDao;
private AdminDao adminDao;
public ListGestBookServlet() {
super();
this.gestBookDao = new GestbookDao();
this.adminDao = new AdminDao();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
ArrayList<Gestbook> list=gestBookDao.getAllGestbook();
request.setAttribute("list", list);
// HashMap以 aid<==>aname 的形式组织所有的数据保存进来.
HashMap<Integer,String> map=new HashMap<Integer,String>();
for(Gestbook book:list) {
Integer aid=book.getAid();
String aname=adminDao.getNameById(book.getAid());
map.put(aid, aname);
}
request.setAttribute("map", map);
this.getServletContext().getRequestDispatcher("/list.jsp").forward(request, response);
}
}
访问数据库包下com.bbs.dao
AdminDao.java
package com.bbs.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.bbs.pojo.Admin;
import com.bbs.util.C3P0Utils;
public class AdminDao {
public Admin login(Admin admin) {
Admin result=null;
String sql="select aid,aname,password from tab_admin where aname=? and password=?";
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con = C3P0Utils.getConn();
ps = con.prepareStatement(sql);
ps.setString(1, admin.getAname());
ps.setString(2, admin.getPassword());
rs=ps.executeQuery();
if(rs.next()) {
result=new Admin();
result.setAid(rs.getInt("aid"));
result.setAname(rs.getString("aname"));
result.setPassword(rs.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
C3P0Utils.closeJDBC(con, ps, rs);
}
return result;
}
public String getNameById(Integer id) {
String sql="select aname from tab_admin where aid=?";
String result=null;
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con = C3P0Utils.getConn();
ps = con.prepareStatement(sql);
ps.setInt(1, id);
rs=ps.executeQuery();
if(rs.next()) {
result=rs.getString("aname");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
C3P0Utils.closeJDBC(con, ps, rs);
}
return result;
}
}
GestbookDao.java
package com.bbs.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.bbs.pojo.Gestbook;
import com.bbs.util.C3P0Utils;
import com.bbs.util.DateUtil;
public class GestbookDao {
// 获取所有的数据列表
public ArrayList<Gestbook> getAllGestbook(){
ArrayList<Gestbook> list=new ArrayList<Gestbook>();
String sql="select * from tab_gestbook";
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con = C3P0Utils.getConn();
ps = con.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()) {
Gestbook book=new Gestbook();
book.setGst_id(rs.getInt("gst_id"));
book.setAid(rs.getInt("aid"));
book.setGst_title(rs.getString("gst_title"));
book.setGst_content(rs.getString("gst_content"));
book.setGst_ip(rs.getString("gst_ip"));
Timestamp temp=rs.getTimestamp("gst_time");
book.setGst_time(temp);
list.add(book);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
C3P0Utils.closeJDBC(con, ps, rs);
}
return list;
}
// 添加新的留言信息
public int insertGestbook(Gestbook book) {
int result=0;
String sql="insert into tab_gestbook values(default,?,?,?,?,?)";
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con = C3P0Utils.getConn();
ps = con.prepareStatement(sql);
ps.setInt(1, book.getAid());
ps.setString(2,book.getGst_title());
ps.setString(3, book.getGst_content());
ps.setString(4,DateUtil.getStringByDate(book.getGst_time()));
ps.setString(5, book.getGst_ip());
result=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
C3P0Utils.closeJDBC(con, ps, rs);
}
return result;
}
}
实体类包下com.bbs.pojo(entity)
Admin.java
package com.bbs.pojo;
public class Admin {
private Integer aid;
private String aname;
private String password;
public Admin() {
super();
}
public Admin(String aname, String password) {
super();
this.aname = aname;
this.password = password;
}
public Admin(Integer aid, String aname, String password) {
super();
this.aid = aid;
this.aname = aname;
this.password = password;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Gestbook.java
package com.bbs.pojo;
import java.util.Date;
public class Gestbook {
private Integer gst_id;
private Integer aid;
private String gst_title;
private String gst_content;
private String gst_ip;
private Date gst_time;
public Gestbook() {
super();
}
public Gestbook(Integer aid, String gst_title, String gst_content, String gst_ip, Date gst_time) {
super();
this.aid = aid;
this.gst_title = gst_title;
this.gst_content = gst_content;
this.gst_ip = gst_ip;
this.gst_time = gst_time;
}
public Gestbook(Integer gst_id, Integer aid, String gst_title, String gst_content, String gst_ip, Date gst_time) {
super();
this.gst_id = gst_id;
this.aid = aid;
this.gst_title = gst_title;
this.gst_content = gst_content;
this.gst_ip = gst_ip;
this.gst_time = gst_time;
}
public Integer getGst_id() {
return gst_id;
}
public void setGst_id(Integer gst_id) {
this.gst_id = gst_id;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getGst_title() {
return gst_title;
}
public void setGst_title(String gst_title) {
this.gst_title = gst_title;
}
public String getGst_content() {
return gst_content;
}
public void setGst_content(String gst_content) {
this.gst_content = gst_content;
}
public String getGst_ip() {
return gst_ip;
}
public void setGst_ip(String gst_ip) {
this.gst_ip = gst_ip;
}
public Date getGst_time() {
return gst_time;
}
public void setGst_time(Date gst_time) {
this.gst_time = gst_time;
}
}
工具包下com.bbs.util
C3P0Utils.java
package com.bbs.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
public static Connection getConn() {
try {
Connection conn = dataSource.getConnection();
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void closeJDBC(Connection con,Statement st,ResultSet rs) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
if(con!=null && con.isClosed()==false) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
DateUtil.java
package com.bbs.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static String getStringByDate(Date date) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return sdf.format(date);
}
}
WebContent下如图
WEB-INF下的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3/2001/XMLSchema-instance" xmlns="http://java.sun/xml/ns/javaee" xsi:schemaLocation="http://java.sun/xml/ns/javaee http://java.sun/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>BBS-Demo01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>AdminLoginServlet</display-name>
<servlet-name>AdminLoginServlet</servlet-name>
<servlet-class>com.bbs.controller.AdminLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AdminLoginServlet</servlet-name>
<url-pattern>/AdminLoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ListGestBookServlet</display-name>
<servlet-name>ListGestBookServlet</servlet-name>
<servlet-class>com.bbs.controller.ListGestBookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListGestBookServlet</servlet-name>
<url-pattern>/ListGestBookServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>InsertGestBookServlet</display-name>
<servlet-name>InsertGestBookServlet</servlet-name>
<servlet-class>com.bbs.controller.InsertGestBookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertGestBookServlet</servlet-name>
<url-pattern>/InsertGestBookServlet</url-pattern>
</servlet-mapping>
</web-app>
WebContent下
insert.jsp
<%@ page language="java" import="com.bbs.pojo.Admin" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/InsertGestBookServlet" method="post">
作者:<input type="text" name="aid" value="<%=((Admin)session.getAttribute("logined")).getAname()%>" readonly="readonly"/><br/><br/>
主题:<input type="text" name="gst_title"/><br/><br/>
内容:<input type="text" name="gst_content"/><br/><br/>
<input type="submit" value="留言"/>
<input type="reset" value="取消"/>
</form>
</body>
</html>
list.jsp
<%@ page language="java" import="java.util.*,com.bbs.pojo.Gestbook,com.bbs.util.DateUtil" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<hr/>
<a href="${pageContext.request.contextPath}/insert.jsp">我要留言</a><br/><br/>
共15条留言 当前2/10页 第一页最 上一页 下一页 后一页<br/><br/>
<hr/>
<%
ArrayList<Gestbook> list=(ArrayList<Gestbook>)request.getAttribute("list");
HashMap<Integer,String> map=(HashMap<Integer,String>)request.getAttribute("map");
for(Gestbook book:list){%>
用户名:<%=map.get(book.getAid())%> 留言时间:<%=DateUtil.getStringByDate(book.getGst_time())%> 用户IP:<%=book.getGst_ip()%> <br/>
主题:<%=book.getGst_title()%><br/>
内容:<%=book.getGst_content()%><br/>
<hr/>
<%}%>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/AdminLoginServlet" method="post">
账号:<input type="text" name="aname"/><br/><br/>
密码:<input type="text" name="password"/><br/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
执行效果图如下
login.jsp效果图
跳转到list.jsp
点"我要留言"跳转到insert.jsp
点击留言后跳转到list.jsp
最后欢迎大家留言,谢谢
更多推荐
java的留言板案例
发布评论