求JSP+javabean+mvc格式写的留言板 20
2个回答
展开全部
这个是用纳碧数据源连接洞判举数据库的!
package beans;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBBean {
public void addMessageBoard(MessageBoard messageBoard){
try {
// 连接数据冲春库
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/book_store");
Connection con = ds.getConnection();
String sql = "insert into guestbook(user,title,content,time,ip) values(?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, messageBoard.getUsername());
ps.setString(2, messageBoard.getTitle());
ps.setString(3, messageBoard.getContent());
// 获取当前时间
java.util.Date nowTime = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
ps.setString(4, sdf.format(nowTime));
ps.setString(5, messageBoard.getIp());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package beans;
import java.io.Serializable;
public class MessageBoard implements Serializable {
private Integer id;
private String username;
private String title;
private String content;
private String writeDate;
private String ip;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getWriteDate() {
return writeDate;
}
public void setWriteDate(String writeDate) {
this.writeDate = writeDate;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
上面是两个Bean
数据库文件
-- ----------------------------
-- Create Database for `bookstore`
-- ----------------------------
DROP DATABASE IF EXISTS `bookstore`;
CREATE DATABASE `bookstore`;
USE `bookstore`;
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `guestbook`
-- ----------------------------
DROP TABLE IF EXISTS `guestbook`;
CREATE TABLE `guestbook` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`user` varchar(10) DEFAULT NULL,
`title` varchar(100) DEFAULT NULL,
`content` longtext,
`time` varchar(19) DEFAULT NULL,
`ip` varchar(15) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of guestbook
-- ----------------------------
-- ----------------------------
-- Table structure for `admin`
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`adminName` varchar(10) DEFAULT NULL,
`password` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of admin
-- ----------------------------
INSERT INTO `admin` VALUES ('1', 'zhangsan', '111');
INSERT INTO `admin` VALUES ('2', '李四', '222');
Servlet:
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.DBBean;
import beans.MessageBoard;
public class ProcessServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String title = request.getParameter("title");
if(username == null || title == null || "".equals(username.trim()) || "".equals(title.trim())){
response.sendRedirect("say.jsp");
return;
}
String content = request.getParameter("content");
String fromIp = request.getRemoteAddr();
MessageBoard messageBoard = new MessageBoard();
messageBoard.setUsername(username);
messageBoard.setTitle(title);
messageBoard.setContent(content);
messageBoard.setIp(fromIp);
new DBBean().addMessageBoard(messageBoard);
response.sendRedirect("list.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
这个XML文件 放到META-INF 文件下
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>
<Resource name="book_store"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="111"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/bookstore" />
</Context>
Servlet xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>process servlet</servlet-name>
<servlet-class>servlets.ProcessServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>process servlet</servlet-name>
<url-pattern>/process</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>list.jsp</welcome-file>
</welcome-file-list>
</web-app>
JSP :
<%@ page import="java.util.*,javax.naming.*" pageEncoding="UTF-8"%>
<%@ page import="javax.sql.*,java.sql.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>留言板列表</title>
</head>
<body>
<a href="say.jsp">我要留言</a>
<hr/>
<%
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/book_store");
Connection con = ds.getConnection();
// 创建可滚动、不可更新结果集
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE , ResultSet.CONCUR_READ_ONLY);
String sql = "select * from guestbook order by time desc";
// 获取查询结果集
ResultSet rs = stmt.executeQuery(sql);
// 将游标移到结果集的最后一行
rs.last();
// 获取结果集中记录的总行数,也就是留言的总条数
int rowCount = rs.getRow();
if(rowCount == 0){
%>
当前没有任何留言!
<%
return;
} else {
%>
共有<%=rowCount %>条留言
<%
}
// 表示当前的页码,即当前是第几页
int curPage;
// 读取用户输入的要显示的页数,即第几页
String strCurPage = request.getParameter("page");
if(strCurPage == null){
curPage = 1;
} else {
curPage = Integer.parseInt(strCurPage);
}
// 定义每页显示的留言数
int countPerPage = 3;
// 计算显示所有留言需要的总页数
int pageCount = (rowCount + countPerPage - 1) / countPerPage;
out.println("当前是第" + curPage + "/" + pageCount + "页 ");
// 若为第一页,则显示不带超链接的导航文字;若不为第一页,则显示带超链接的导航文字
if(curPage == 1){
%>
首页 上页
<%
} else {
%>
<a href="list.jsp?page=<%=1 %>">首页</a>
<a href="list.jsp?page=<%=curPage - 1 %>">上页</a>
<%
}
// 若为最后一页,则显示不带超链接的导航文字;若不为最后一页,则显示带超链接的导航文字
if(curPage == pageCount){
%>
下页 尾页<br/>
<%
} else {
%>
<a href="list.jsp?page=<%=curPage + 1 %>">下页</a>
<a href="list.jsp?page=<%=pageCount %>">尾页</a><br/>
<%
}
%>
<form action="list.jsp">
跳转到第<input type="text" name="page"/>页
<input type="submit" value="跳转"/>
</form>
<br/>
<hr/>
<%
// 显示每页中的数据
// 将游标移动到当前页的首条记录
rs.absolute(countPerPage * (curPage - 1) + 1);
int i = 0;
while(i < countPerPage && !rs.isAfterLast()){
out.println((i + 1) + "、用户名:" + rs.getString("user") + " ");
out.println("留言时间:" + rs.getString("time") + "  ");
out.println("用户IP:" + rs.getString("ip") + "<br/>");
out.println("主题:" + rs.getString("title") + "<br/>");
out.println("内容:" + rs.getString("content") + "<hr/>");
i++;
// 游标下移一行
rs.next();
}
rs.close();
stmt.close();
con.close();
%>
</body>
</html>
<%@ page pageEncoding="UTF-8"%>
<html>
<head>
<title>留言板</title>
</head>
<body>
<form action="process" method="post">
<table align="center" bgcolor="#eeeeee" border="1">
<caption>欢迎访问留言板</caption>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>标题:</td>
<td><input type="text" name="title"/></td>
</tr>
<tr>
<td>内容:</td>
<td>
<textarea name="content" rows="10" cols="40"></textarea>
</td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
<td><input type="reset" value="重填"/></td>
</tr>
</table>
</form>
</body>
</html>
package beans;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBBean {
public void addMessageBoard(MessageBoard messageBoard){
try {
// 连接数据冲春库
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/book_store");
Connection con = ds.getConnection();
String sql = "insert into guestbook(user,title,content,time,ip) values(?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, messageBoard.getUsername());
ps.setString(2, messageBoard.getTitle());
ps.setString(3, messageBoard.getContent());
// 获取当前时间
java.util.Date nowTime = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
ps.setString(4, sdf.format(nowTime));
ps.setString(5, messageBoard.getIp());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package beans;
import java.io.Serializable;
public class MessageBoard implements Serializable {
private Integer id;
private String username;
private String title;
private String content;
private String writeDate;
private String ip;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getWriteDate() {
return writeDate;
}
public void setWriteDate(String writeDate) {
this.writeDate = writeDate;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
上面是两个Bean
数据库文件
-- ----------------------------
-- Create Database for `bookstore`
-- ----------------------------
DROP DATABASE IF EXISTS `bookstore`;
CREATE DATABASE `bookstore`;
USE `bookstore`;
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `guestbook`
-- ----------------------------
DROP TABLE IF EXISTS `guestbook`;
CREATE TABLE `guestbook` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`user` varchar(10) DEFAULT NULL,
`title` varchar(100) DEFAULT NULL,
`content` longtext,
`time` varchar(19) DEFAULT NULL,
`ip` varchar(15) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of guestbook
-- ----------------------------
-- ----------------------------
-- Table structure for `admin`
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`adminName` varchar(10) DEFAULT NULL,
`password` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of admin
-- ----------------------------
INSERT INTO `admin` VALUES ('1', 'zhangsan', '111');
INSERT INTO `admin` VALUES ('2', '李四', '222');
Servlet:
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.DBBean;
import beans.MessageBoard;
public class ProcessServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String title = request.getParameter("title");
if(username == null || title == null || "".equals(username.trim()) || "".equals(title.trim())){
response.sendRedirect("say.jsp");
return;
}
String content = request.getParameter("content");
String fromIp = request.getRemoteAddr();
MessageBoard messageBoard = new MessageBoard();
messageBoard.setUsername(username);
messageBoard.setTitle(title);
messageBoard.setContent(content);
messageBoard.setIp(fromIp);
new DBBean().addMessageBoard(messageBoard);
response.sendRedirect("list.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
这个XML文件 放到META-INF 文件下
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>
<Resource name="book_store"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="111"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/bookstore" />
</Context>
Servlet xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>process servlet</servlet-name>
<servlet-class>servlets.ProcessServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>process servlet</servlet-name>
<url-pattern>/process</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>list.jsp</welcome-file>
</welcome-file-list>
</web-app>
JSP :
<%@ page import="java.util.*,javax.naming.*" pageEncoding="UTF-8"%>
<%@ page import="javax.sql.*,java.sql.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>留言板列表</title>
</head>
<body>
<a href="say.jsp">我要留言</a>
<hr/>
<%
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/book_store");
Connection con = ds.getConnection();
// 创建可滚动、不可更新结果集
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE , ResultSet.CONCUR_READ_ONLY);
String sql = "select * from guestbook order by time desc";
// 获取查询结果集
ResultSet rs = stmt.executeQuery(sql);
// 将游标移到结果集的最后一行
rs.last();
// 获取结果集中记录的总行数,也就是留言的总条数
int rowCount = rs.getRow();
if(rowCount == 0){
%>
当前没有任何留言!
<%
return;
} else {
%>
共有<%=rowCount %>条留言
<%
}
// 表示当前的页码,即当前是第几页
int curPage;
// 读取用户输入的要显示的页数,即第几页
String strCurPage = request.getParameter("page");
if(strCurPage == null){
curPage = 1;
} else {
curPage = Integer.parseInt(strCurPage);
}
// 定义每页显示的留言数
int countPerPage = 3;
// 计算显示所有留言需要的总页数
int pageCount = (rowCount + countPerPage - 1) / countPerPage;
out.println("当前是第" + curPage + "/" + pageCount + "页 ");
// 若为第一页,则显示不带超链接的导航文字;若不为第一页,则显示带超链接的导航文字
if(curPage == 1){
%>
首页 上页
<%
} else {
%>
<a href="list.jsp?page=<%=1 %>">首页</a>
<a href="list.jsp?page=<%=curPage - 1 %>">上页</a>
<%
}
// 若为最后一页,则显示不带超链接的导航文字;若不为最后一页,则显示带超链接的导航文字
if(curPage == pageCount){
%>
下页 尾页<br/>
<%
} else {
%>
<a href="list.jsp?page=<%=curPage + 1 %>">下页</a>
<a href="list.jsp?page=<%=pageCount %>">尾页</a><br/>
<%
}
%>
<form action="list.jsp">
跳转到第<input type="text" name="page"/>页
<input type="submit" value="跳转"/>
</form>
<br/>
<hr/>
<%
// 显示每页中的数据
// 将游标移动到当前页的首条记录
rs.absolute(countPerPage * (curPage - 1) + 1);
int i = 0;
while(i < countPerPage && !rs.isAfterLast()){
out.println((i + 1) + "、用户名:" + rs.getString("user") + " ");
out.println("留言时间:" + rs.getString("time") + "  ");
out.println("用户IP:" + rs.getString("ip") + "<br/>");
out.println("主题:" + rs.getString("title") + "<br/>");
out.println("内容:" + rs.getString("content") + "<hr/>");
i++;
// 游标下移一行
rs.next();
}
rs.close();
stmt.close();
con.close();
%>
</body>
</html>
<%@ page pageEncoding="UTF-8"%>
<html>
<head>
<title>留言板</title>
</head>
<body>
<form action="process" method="post">
<table align="center" bgcolor="#eeeeee" border="1">
<caption>欢迎访问留言板</caption>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>标题:</td>
<td><input type="text" name="title"/></td>
</tr>
<tr>
<td>内容:</td>
<td>
<textarea name="content" rows="10" cols="40"></textarea>
</td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
<td><input type="reset" value="重填"/></td>
</tr>
</table>
</form>
</body>
</html>
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询