数据库留言板代码
简单的PHP留言板制作(一)
简单的PHP留⾔板制作(⼀)⾸先是确定⾃⼰的留⾔板需求.例如:名字,邮件及留⾔内容.⼀. 建⽴⼀个数据库guestbook。
CREATE TABLE IF NOT EXISTS `content` (`id` int(11) NOT NULL auto_increment,`name` varchar(20) NOT NULL,`email` varchar(50) NOT NULL,`content` varchar(200) NOT NULL,PRIMARY KEY (`id`))ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=3;⼆. 新建config.php<?php$q = mysql_connect("服务器","数据库⽤户","数据库密码");if(!$q){die('Could not connect: ' . mysql_error());}mysql_query("set names utf8"); //以utf8读取数据mysql_select_db("guestbook",$q); //数据库>三.新建index.php<?phpinclude("config.php"); //引⼊数据库连接⽂件$sql = "select * from content"; //搜索数据表content$resule = mysql_query($sql,$q);><html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><body><table width="678" align="center"><tr><td colspan="2"><h1>留⾔本</h1></td></tr><tr><td width="586"><a href="index.php">⾸页</a> | <a href="liuyan.php">留⾔</a></td></tr></table><p>while($row=mysql_fetch_array($resule)){></p><table width="678" border="1" align="center" cellpadding="1" cellspacing="1"><tr><td width="178">Name:<? echo $row[1] ?></td><td width="223">Email:<? echo $row[2] ?></td></tr><tr><td colspan="4"><? echo $row[3] ?></td></tr><tr></table><?}></body></html>四.新建liuyan.php<html><body><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><table width="678" align="center"><tr><td colspan="2"><h1>留⾔本</h1></td></tr><tr><td width="586"><a href="index.php">⾸页</a> | <a href="liuyan.php">留⾔</a></td> </tr></table><table align="center" width="678"><tr><td><form name="form1" method="post" action="post.php"><p>Name:<input name="name" type="text" id="name"><p>Email:<input type="test" name="email" id="email"></p><p>留⾔:</p><p><textarea name="content" id="content" cols="45" rows="5"></textarea></p><p><input type="submit" name="button" id="button" value="提交"><input type="reset" name="button2" id="button2" value="重置"></p></form></td></tr></table></body></html>五. 新建post.php<?phpheader("content-Type: text/html; charset=utf-8");include("config.php");$name= $_POST['name'];$email= $_POST['email'];$patch = $_POST['content'];$content = str_replace("","<br />",$patch);$sql = "insert into content (name,email,content) values ('$name','$email','$content')"; mysql_query($sql);echo "<script>alert('提交成功!返回⾸页。
php+mysql留言板系统「完整代码及详解」
php+mysql留言板系统「完整代码及详解」php+mysql留言板系统【完整代码及详解】主要页面input.html为初始页insert.php为把输入内容送入数据库show.php显示留言板内容change.php修改留言板内容的界面del.php删除留言板内容change_ok.php修改留言板内容并送入数据库数据库的创建CREATE DATABASE GBOOK;CREATE TABLE `gbook` (`id` INT( 255 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,`name` VARCHAR( 10 ) NOT NULL ,`sex` TINYINT( 1 ) UNSIGNED NOT NULL ,`email` VARCHAR( 255 ) NOT NULL ,`info` TEXT NOT NULL ,`ip` VARCHAR( 15 ) NOT NULL ,`time_at` DATETIME NOT NULL)input.html 页面留言版insert.php 页面$mysql_server_name = "localhost";$mysql_username = "root";$mysql_password = "123456";$mysql_database = "gbook";$ip = getenv('REMOTE_ADDR');$conn = mysql_connect("localhost","root","123456");mysql_select_db("gbook");$sql = "INSERT INTO `gbook` ( `id` , `name` , `sex` , `email` , `info` , `ip` , `time_at` )VALUES (NULL , '$name', '$sex', '$email', '$info', '$ip', NOW( ))";$result = mysql_query($sql,$conn);$id = mysql_insert_id();mysql_close($conn);?>留言成功去留言页show.php 页面$mysql_server_name = "localhost";$mysql_username = "root";$mysql_password = "123456";$mysql_database = "gbook";$sql = "SELECT * FROM gbook ORDER BY 'id' DESC"; //排序后留言的在前面显示$conn = mysql_connect($mysql_server_name,$mysql_username,$m ysql_password);mysql_select_db($mysql_database,$conn);$result = mysql_query($sql);while($row = mysql_fetch_row($result)) { // ----if语句判断男女------if($row[2]==1){ $gender = '男';}else{ $gender = '女'; }?>()">[修改] ">[删除]。
PHP编写留言本
PHP+MySQL写留言本留言本最基本的功能就是:1:用户写留言2:把数据写入数据库3:显示所有留言下面就开始制作我的留言本首先在PHPMYADMIN下建立一guest_book数据库然后在该数据库下建立一个contents的表该表下建立两个字段分别为name 和contentSQL语句如下:CREATE TABLE `contents` (`id` int(11) NOT NULL auto_increment,`name` varchar(20) NOT NULL default '"no name"',`content` mediumtext NOT NULL,PRIMARY KEY (`id`)) TYPE=MyISAM AUTO_INCREMENT=6好了数据库建好了~~`下面开始写程序了该程序包含三个页面post.htm(留言提交页面) index.php(留言显示页面) updata.php(把数据写入数据库的页面)post.htm代码如下:<html><head><meta http-equiv="Content-Type" c><title>留言本</title></head><body><form action="updata.php" method="post" name="name1">姓名:<input type="text" name="user_name"><br>留言:<textarea name="post_contents" rows="10" cols="50"></textarea><input type="submit"></form></body></html>updata.php页面代码如下:<?$name=$_POST['user_name'];$content=$_POST['post_contents'];$conn=mysql_connect("localhost:6033", "root", "");mysql_query("set names utf-8"); //解决中文乱码问题mysql_select_db("guest_book");$exec="insert into contents (name,content) values('".$_POST['user_name']."','".$_POST['post_contents']."')";$result=mysql_query($exec);?>index.php页面代码如下:<?$conn=mysql_connect ("localhost:6033", "root", ""); //打开mysql 服务器连接mysql_select_db("guest_book"); //链接数据库mysql_query("set names utf-8"); //解决中文乱码问题$exec="select * from contents"; //sql语句$result=mysql_query($exec); //执行sql语句,返回结果while($rs=mysql_fetch_object($result)){echo "<table><tr><td>姓名:".$rs->name."</td></tr>";echo "<tr><td>留言:".$rs->content."</td></tr></table><br/>";}?>至于分页,页面转向等功能暂时不用上去.为得就是使程序尽量精简.麻雀虽小.但是留言本的核心功能全在这里了.其中还需要再多说几句$conn=mysql_connect ("localhost:6033", "root", "");这一句很重要一开始我用的是$conn=mysql_connect ("127.0.0.1", "", "");怎么弄都不见数据进数据库去~~~~但是又没报错~~后来看了半天才知道原来哪个127的地方应该在PHPMYADMIN里看服务器名一击数据库端口是什么~~~还有ROOT那里就是mysql用户名了,后面的是密码还有个问题就是汉字乱码问题在$result=mysql_query($exec); 语句前面加上mysql_query("set names gb2312");或者mysql_query("set names utf-8");可疑防止提交进数据库的汉字以乱码形式存放在数据库中以及防止从数据库中查询出来的包含汉字的数据以乱码显示有时候尽管这样设置了后还是无法正常显示汉字~~~~我就遇见了这样的情况,由于我是在本地调试的,每次都要把浏览器上的那个字符编码调到utf-8才能正常显示汉字默认的编码总是ISO-8859-1 于是google了一下`~原来是apache设置不对.于是找到httpd.conf 设置文件把default-character-set=ISO-8859-1 改为default-character-set=utf-8然后再service httpd restart 重启appache 清除所有cookies与历史记录~~~然后问题就解决了------------------------------------------------------------------------------------今天再稍微改善下加一个管理员管理留言的功能~~~这里最主要要用到$_SESSION['item'] 这个东东~~` 好了`~`先把昨天的稍微改一下再把这个功能加进去~~~首先我们在首页同时显示留言,以及留言添加框~~这样使留言者方便使用`~`不说多了`~把代码贴出来再说:index.php<html><head><meta http-equiv="Content-Type" c><title>留言本</title></head><body><a href="admin_login.htm" tagert="_blank">留言管理</a><?$conn=mysql_connect ("localhost:6033", "root", ""); //打开MySQL服务器连接mysql_select_db("guest_book"); //链接数据库mysql_query("set names GB2312"); //解决中文乱码问题$exec="select * from contents"; //sql语句$result=mysql_query($exec); //执行sql语句,返回结果while($rs=mysql_fetch_object($result)){echo "<table><tr><td>姓名:".$rs->name."</td></tr>";echo "<tr><td>留言:".$rs->content."</td></tr></table><br/>";echo ".............................................................................................................................";}mysql_close();?><br><br><br><form action="updata.php" method="post" name="name1">姓名:<input type="text" name="user_name"><br>留言:<textarea name="post_contents" rows="10" cols="50"></textarea><input type="submit" value="提交留言"></form></body></html>updata.php页再加个header("location:index.php");语句重定向到主页面`~~ updata.php<?$name=$_POST['user_name'];$content=$_POST['post_contents'];$conn=mysql_connect("localhost:6033", "root", "");mysql_query("set names GB2312"); //解决中文乱码问题mysql_select_db("guest_book");$exec="insert into contents (name,content) values('".$_POST['user_name']."','".$_POST['post_contents']."')";$result=mysql_query($exec);mysql_close();header("location:index.php");?>HOHO~~~是不是用起来有那么回事了`~~好的`~下面再加个管理功能~~那么这个留言本就更加强大了`~留言管理模块分为管理员登录页admin_login.htm ,管理员验证页admin_check.php 后台管理首页admin_index.php先农这个登录页面admin_login.htm<form action="admin_check.php" method="post" name="form2">用户名:<input type="text" name="admin_name">密码:<input type="password" name="admin_password"><input type="submit" value="进入后台管理"></form>这个简单得再简单不过了,我就不说什么了`~~admin_check.php管理员验证<?session_start();$admin_name=$_POST['admin_name'];$admin_password=$_POST['admin_password'];$conn=mysql_connect ("localhost:6033", "root", "");mysql_select_db("guest_book");$exec="select * from admin where admin_name='".$admin_name."'";$result=mysql_query($exec);if ($rs=mysql_fetch_object($result)){ if ($rs->admin_password==$admin_password){$_SESSION['admin']="OK";header("location:admin_index.php");}else echo"密码不正确";}else echo"用户名不正确";mysql_close();?>这里最主要的就是session~~~凡事要用到session的地方.在页面最开始处要加上这一句session_start();否则就无法使用~~那么session究竟是什么东东呢?由于网页的传输方式(也就是http这个东西) 不是永久连接的~~`所以服务器无法在两个不同页面之间传送变量`~~唉.我一下子也说不清楚`~~还是看看这里/read.php?wid=87上面有很详细的介绍.反正就是用这个东西来验证管理员的身分了`~~好了下面说后台管理主页面admin_index.php<?session_start();if($_SESSION['admin']=="OK"){$conn=mysql_connect ("localhost:6033", "root", "");mysql_select_db("guest_book");$exec="select * from contents";$result=mysql_query($exec);while($rs=mysql_fetch_object($result)){echo "<table><tr><td>姓名:".$rs->name."</td></tr>";echo "<tr><td>留言:".$rs->content."</td></tr></table><br/>";echo "<a href=modify.php?id=".$rs->id." >修改</a> <ahref=delete.php?id=".$rs->id." >删除</a>";}echo "<br><br><br><br><br><a href=index.php >回首页</a>";}mysql_close();?>这里最主要是这一句echo "<a href=modify.php?id=".$rs->id." >修改</a> <a href=delete.php?id=".$rs->id." >删除</a>";用来向所连接到的地址传递参数~~看看下面的就知道有什么用了modify.php<?session_start();if($_SESSION['admin']=="OK"){$conn=mysql_connect ("localhost:6033", "root", "");mysql_select_db("guest_book");$exec="select * from contents where id=".$_GET['id']; /*这里这个$_GET['id']就是取得从那个连接传递过来的参数拉*/$result=mysql_query($exec);$rs=mysql_fetch_object($result);$name=$rs->name;$content=$rs->content;$id=$rs->id;?><form action="modify2.php" method="post" name="name1">ID :<?=$id?><input type=hidden name=id value=<?=$id?> >姓名:<?=$name?><br>留言:<textarea name="post_contents" rows="10"cols="50"><?=$content?></textarea><input type="submit" value="提交修改"></form><?}mysql_close();?>这里这个<?=$id> 其实就等于echo $id再看看最终的数据修改实现页面modify2.php<?session_start();if($_SESSION['admin']=="OK"){$conn=mysql_connect ("localhost:6033", "root", "");mysql_select_db("guest_book");$exec="select * from contents where id=".$_GET['id'];$exec="update contents set content='".$_POST['post_contents']."' whereid=".$_POST['id'];$result=mysql_query($exec);}mysql_close();header("location:admin_index.php");?>最后就是删除功能的实现了delete.php<?session_start();if($_SESSION['admin']=="OK"){$conn=mysql_connect ("localhost:6033", "root", "");mysql_select_db("guest_book");$exec="delete from contents where id=".$_GET['id'];mysql_query($exec);mysql_close();header("location:admin_index.php");}?>/////////////////////////////////////////////////////////////////////////////////////////////////////////////今天用到的知识如下:1: session_start(); $_SESSION['变量名']=$变量名或者某一特定值2: <a href="#####.php?var=##">aaa</a>用这个方法来传递参数同时用$_GET['var']来接收传递过来的值3: 数据修改:$exec="update tablename set item1='".$_POST['item1']."' where ...";4: 数据删除:$exec="delete from tablename where...";。
一个简单的留言板代码
一个简单的留言板代码<!DOCTYPE html><html><head><meta charset='utf-8'></head><body><h1>留言板</h1><!--以下为读取留言要用的 PHP 代码 --><?php// 连接数据库$conn = mysqli_connect('ip地址', '用户名', '密码', '数据库名')or die('连接数据库失败:' . mysqli_error());// 设置数据库字符集mysqli_query($conn, 'SET NAMES UTF8');// 执行查询$sql = 'SELECT * FROM message ORDER BY created_at ASC'; // 查询语句$result = mysqli_query($conn, $sql) or die('查询数据失败:' . mysqli_error($conn));// 输出数据if (mysqli_num_rows($result) > 0) {// 输出每行数据while ($row = mysqli_fetch_assoc($result)) {echo '<div>';echo '<h3>' . $row['name'] . ' 发表于 ' . $row['created_at'] . '</h3>';echo '<p>' . $row['content'] . '</p >';echo '</div>';}} else {echo '暂无留言!';}// 关闭数据库mysqli_close($conn);><!-- 以上为读取留言结束 --><!-- 以下为发表留言 --><form action="index.php" method="POST"><div><label for="name">昵称:</label><input type="text" name="name"></div><div><label for="content">内容:</label> <textarea name="content"></textarea> </div><input type="submit" value="提交"></form><!-- 以上为发表留言结束 --></body></html>。
留言板代码大全
留言板代码大全简介留言板是一个常见的网站组件,允许用户在网站上发表自己的评论、建议或者问题。
在本文档中,我们将介绍留言板的实现方法,并提供一些常见的代码示例。
环境准备在进行留言板开发之前,我们需要准备一些必要的环境和工具:1.服务器环境:我们需要一个能够运行服务器脚本的环境,比如搭建本地的开发服务器或者使用云服务器。
2.编程语言:留言板的开发可以使用多种编程语言实现,比如 PHP、Python 等。
3.数据库:留言板需要使用数据库来存储用户的留言信息,所以我们需要安装并配置一个适合的数据库。
实现步骤下面是一个通用的留言板的实现步骤:1.创建数据库表:留言板需要使用数据库来存储用户留言的信息,我们需要创建一个适合的数据表来存储这些信息。
表的字段可以包括用户ID、留言内容、留言时间等。
2.创建前端界面:我们需要创建一个前端界面,该界面用于展示留言板以及接收用户的留言输入。
可以使用HTML、CSS 和 JavaScript 来构建这个前端界面。
3.处理用户留言:当用户在前端界面中提交留言后,我们需要编写后端代码来处理这些留言。
后端代码通常使用服务器脚本或者后端框架来实现。
具体操作包括接收留言,将留言信息存储到数据库中,然后返回给用户留言保存成功的提示。
4.显示留言列表:留言板需要将存储在数据库中的留言信息展示给用户,我们需要编写后端代码来从数据库检索留言信息,然后返回给前端界面进行展示。
以下是一个使用 PHP 和 MySQL 数据库实现的留言板的示例代码:```php <?php// 连接数据库 $conn = mysqli_connect(。
留言板代码
1.Left.jsp<li><a class="head">留言评论管理</a><ul><li><a href="../leave/leaves.action"target="rightFrame">查看/删除留言</a></li></ul></li>2.LeaveActionpackage com.um.action;import java.util.List;import org.apache.struts2.ServletActionContext;import org.apache.struts2.interceptor.validation.SkipValidation;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Order;import org.hibernate.criterion.Restrictions;import com.opensymphony.xwork2.ActionSupport;import com.um.pojo.Leave;import com.um.service.LeaveService;import com.um.util.Paginate;public class LeaveAction extends ActionSupport {private static final long serialVersionUID = 6654280697600536538L;Leave leave=null;List<Leave> leaveList=null;public Leave getLeave() {return leave;}public void setLeave(Leave leave) {this.leave = leave;}public List<Leave> getLeaveList() {return leaveList;}public void setLeaveList(List<Leave> leaveList) {this.leaveList = leaveList;}@SkipValidationpublic String list() throws Exception{LeaveService us=new LeaveService();try {DetachedCriteria criteria=DetachedCriteria.forClass(Leave.class);criteria.addOrder(Order.desc("regtime"));//实例化paginate类,同时传递符合查询条件的记录总数Paginate paginate=new Paginate(us.countByCriteria(criteria));//method 作用是告诉action,用户的操作时什么String method="";if(ServletActionContext.getRequest().getParameter("method")!=null)method=ServletActionContext.getRequest().getParameter("method");int currentPage=1;if ("last".equals(method))st();if("frist".equals(method))paginate.first();if("next".equals(method)){currentPage=Integer.parseInt(ServletActionContext.getRequest().getParameter("currentPage" ));paginate.setCurrentPage(currentPage);paginate.next();}if("previous".equals(method)){currentPage=Integer.parseInt(ServletActionContext.getRequest().getParameter("currentPage"paginate.setCurrentPage(currentPage);paginate.previous();}//将paginate对象放到请求中ServletActionContext.getRequest().setAttribute("paginate", paginate);// 根据离线criteria和paginate进行分页查询leaveList = us.findByCriteria(criteria,paginate);return SUCCESS;} catch (Exception e) {e.printStackTrace();return ERROR;}}public String leaves() throws Exception{LeaveService us=new LeaveService();try {DetachedCriteria criteria=DetachedCriteria.forClass(Leave.class);criteria.addOrder(Order.desc("regtime"));//实例化paginate类,同时传递符合查询条件的记录总数Paginate paginate=new Paginate(us.countByCriteria(criteria));//method 作用是告诉action,用户的操作时什么String method="";if(ServletActionContext.getRequest().getParameter("method")!=null)method=ServletActionContext.getRequest().getParameter("method");int currentPage=1;if ("last".equals(method))st();if("frist".equals(method))paginate.first();if("next".equals(method)){currentPage=Integer.parseInt(ServletActionContext.getRequest().getParameter("currentPage" ));paginate.setCurrentPage(currentPage);paginate.next();}if("previous".equals(method)){currentPage=Integer.parseInt(ServletActionContext.getRequest().getParameter("currentPage" ));paginate.setCurrentPage(currentPage);paginate.previous();}//将paginate对象放到请求中ServletActionContext.getRequest().setAttribute("paginate", paginate);// 根据离线criteria和paginate进行分页查询leaveList = us.findByCriteria(criteria,paginate);return SUCCESS;} catch (Exception e) {e.printStackTrace();return ERROR;}}public String show() throws Exception{LeaveService us=new LeaveService();leave=us.findById(leave.getId());return SUCCESS;}public String delete() throws Exception{LeaveService us=new LeaveService();try {us.delete(leave);return SUCCESS;} catch (Exception e) {e.printStackTrace();return ERROR;}}public String register() throws Exception{LeaveService us=new LeaveService();try {leave.setRegtime(new java.sql.Timestamp(new java.util.Date().getTime()));us.save(leave);return SUCCESS;} catch (Exception e) {e.printStackTrace();return ERROR;}}}3. ILeaveDAO package com.um.dao;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import com.um.pojo.Leave;import com.um.util.Paginate;public interface ILeaveDAO {/*** 方法说明:根据ID查询UserInfo * @param id 用户编号* @return 返回UserInfo对象实例* @throws Exception*/public Leave findById(int id) throws Exception;/*** 方法说明:删除一条UserInfo记录* @param id 用户编号* @throws Exception*/public void delete(Leave leave) throws Exception;/*** 方法说明:添加一条UserInfo记录* @param userInfo UserInfo对象实例* @throws Exception*/public void save(Leave leave) throws Exception;/*** 方法说明:使用离线criteria查询* @param criteria 离线查询条件* @param pageNo 页码* @return 返回查询结果列表* @throws Exception*/public List<Leave> findByCriteria(DetachedCriteria criteria,Paginate paginate) throws Exception;/*** 方法说明:使用离线criteria查询* @param criteria* @return 返回查询数量* @throws Exception*/public int countByCriteria(DetachedCriteria criteria) throws Exception;}4. LeaveDAOImplpackage com.um.dao.impl;import java.util.List;import org.hibernate.Criteria;import org.hibernate.Session;import org.hibernate.criterion.DetachedCriteria;import com.um.dao.BaseHibernateDAO;import com.um.dao.ILeaveDAO;import com.um.pojo.Leave;import com.um.util.Paginate;public class LeaveDAOImpl extends BaseHibernateDAO implements ILeaveDAO{@SuppressWarnings("unchecked")public List<Leave> findByCriteria(DetachedCriteria criteria,Paginate paginate) throws Exception{try {//得到session离线criteriaCriteria c=criteria.getExecutableCriteria(getSession());//设置分页条件c.setMaxResults(paginate.getPageSize());c.setFirstResult(paginate.getStartRow());return criteria.getExecutableCriteria(getSession()).list();} catch (RuntimeException re) {throw re;}}public void save(Leave leave) throws Exception {try {getSession().save(leave);} catch (RuntimeException re) {throw re;}}public Leave findById(int id) throws Exception {try {Leave instance = (Leave) getSession().get("com.um.pojo.Leave", id);return instance;} catch (RuntimeException re) {throw re;}}public int countByCriteria(DetachedCriteria criteria) throws Exception{try {return criteria.getExecutableCriteria(getSession()).list().size();} catch (RuntimeException re) {throw re;}}public void delete(Leave leave) throws Exception {try {getSession().delete(leave);} catch (RuntimeException re) {throw re;}}}5. LeaveService package com.um.service;import java.util.List;import org.hibernate.Transaction;import org.hibernate.criterion.DetachedCriteria;import com.um.dao.impl.LeaveDAOImpl;import com.um.pojo.Leave;import com.um.util.Paginate;public class LeaveService {Leave leaveDAO=new Leave();LeaveDAOImpl leaveDAOImpl=new LeaveDAOImpl();public Leave findById(int id) throws Exception {try{return leaveDAOImpl.findById(id);}catch(Exception e){e.printStackTrace();throw e;}}public void save(Leave leave) throws Exception {try{Transaction tx=null;tx=leaveDAOImpl.getSession().beginTransaction();leaveDAOImpl.save(leave);mit();}catch(Exception e){e.printStackTrace();throw e;}}public void delete(Leave leave) throws Exception {try {leaveDAOImpl.getSession().clear();Transaction tx=null;tx=leaveDAOImpl.getSession().beginTransaction();leaveDAOImpl.delete(leave);mit();} catch (RuntimeException re) {throw re;}}public List<Leave> findByCriteria(DetachedCriteria criteria,Paginate paginate) throws Exception{try{return leaveDAOImpl.findByCriteria(criteria,paginate);}catch(Exception e){e.printStackTrace();throw e;}}public int countByCriteria(DetachedCriteria criteria) throws Exception{try{return leaveDAOImpl.countByCriteria(criteria);}catch(Exception e){e.printStackTrace();throw e;}}}6. struts.xml<!-- 用户留言 --><package name="leave"extends="struts-default"namespace="/leave"><action name="register"method="register"class="com.um.action.LeaveAction"><result name="input">/leave/leave.jsp</result><result type="redirect">list.action</result><result name="error"type="redirect">/leave/error.jsp</result></action><action name="list"method="list"class="com.um.action.LeaveAction"><result>/leave/leave.jsp</result><result name="error"type="redirect">/error.jsp</result> </action><action name="delete"method="delete"class="com.um.action.LeaveAction"><result type="redirect">/leave/leaves.action</result><result name="error"type="redirect">/error.jsp</result> </action><action name="leaves"method="leaves"class="com.um.action.LeaveAction"><result>/leave/leaveList.jsp</result><result name="error"type="redirect">/error.jsp</result> </action><action name="show"method="show"class="com.um.action.LeaveAction"><result>/leave/leaveShow.jsp</result></action></package>。
数据库留言板代码
alter("请填写留言时间");
form1.time.focus();
return false; }
if(form1.title.value==""){
alter("请填写主题");
form1.title.focus();
return false; }
留言主题:<input name="title" type="text"><br>
留言内容:<textarea name="connect" rows="12" cols="30" wrap="on"></textarea><br>
<input name="submit" type="submit" value="发表留言">
留 言:<textarea name="content" rows="10" cols="50" wrap="on"></textarea><br>
<input type="submit" name="submit" value="发表">
基于ASP.NET的网络留言板的制作
基于的网络留言板的制作网络留言板是为用户提供的发表留言、查看留言回复的便捷功能,已成为普通企业网站、政府网站等类型网站的重要组成部分。
本文通过设计制作一个网络留言板,使读者掌握进行数据库操作的相关技术和代码实现方法。
开发环境:Visual Studio 2010开发语言:C#1. 网络留言板整体设计网络留言板的主要功能包括:普通用户发表、查看留言功能,管理员查看留言功能,管理员后台登录功能,管理员回复留言功能,管理员删除留言功能。
下面我们看一下本项目各个功能的界面,了解本项目的整体设计结构。
显示留言页面,如图1所示。
图1显示留言页发表留言界面,如图2所示。
图2 发表留言页管理员登录界面,如图3所示。
图3 管理员登录留言删除提示界面,如图4所示。
图4 留言删除提示回复留言页面,如图5所示。
图5 回复留言页2. 站点的创建了解了本项目的整体结构,下面开始制作网络留言板。
首先我们要创建一个站点,给站点起一个名称,本项目的站点名称为“网络留言板”。
创建好站点后,打开开发环境Visual Studio 2010,如图6 所示。
图6开发环境在图6所示界面中选择“文件”菜单中“新建”选项中的“网站”命令,选择后打开如图7所示的新建网站对话框。
图7 新建网站对话框在图7中点击“浏览”按钮,在弹出的“选择位置”对话框中选择刚刚创建的站点,选择后点击“打开”按钮,回到图7所示界面。
然后点击图7中的“确定”按钮,完成网站的创建,如图8所示。
图8 新建网站3. 网络留言板数据库设计根据网络留言板的功能,在使用留言板时会产生需要存储的数据,所以我们要对数据库进行设计,本项目使用的数据库为Visual Studio 2010自带的SQL Server 2008数据库。
3.1数据库的创建在图8中选择“文件”菜单中“新建”选项中的“文件”,选择后打开如图9所示添加新项对话框。
图9 添加新项对话框在图9所示对话框中选择“SQL 数据库”,然后点击“添加”按钮,在弹出的图10所示消息框中选择“是”,数据库就自动创建了,并且创建在站点中的“App_Data”文件夹中。
简单留言板代码
<head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>09计算机</title><style type="text/css"><!--.STYLE1 {font-family: "宋体";font-size: 36px;}.STYLE2 {font-family: "宋体"; font-size: 16px; }--></style></head><body><p class="STYLE1">09计算机留言板</p><form method="post" action="liuyan.asp"><table width="600" border="1"><tr><td><input type="hidden" name="task" value="insert">姓名<input type="text" size="20" name="xm" /></td></tr><tr><td><p>留言</p><p><textarea rows="5" cols="80" name="lyq"></textarea></p></td></tr><tr><td height="24"><input type="submit" value="提交"name="B1" /><input type="reset" value="重置"name="B2" /></td></tr></table><p>历史留言</p></form><table width="600" border="1"><tr><td><%set conn=server.createobject("adodb.connection")conn.Open="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("wang.mdb") if request("task")="insert" thenxm=request("xm")sj=date()sj=sj&" "&hour(time())& ":"&minute(time())if request("lyq")=" "thenresponse.write("留言不能为空!")response.endelsely=request("lyq")end ifsqlstr="insert into wang (姓名,时间,留言)values('" & xm &"',# " & sj &"#,'"& ly &"')"conn.execute sqlstrend ifsqlstr="select * from wang order by 时间DESC"set rs=conn.execute(sqlstr)do while not rs.eof%>姓名:<%=rs("姓名")%> </td></tr><tr><td> 留言时间:<%=rs("时间")%></td></tr><tr><td height="22">留言内容:<%=rs("留言")%></td></tr><tr><td><br><%rs.movenextlooprs.closeconn.closeset conn=nothing%></td></tr></table></body></html>数据库设计图:。
留言板代码65282
留言板代码:1.[M][fts=6][ftc=#9933FF]*[/ft][/ft][fts=2][ftc=#FFFF33]●[/ft][/ft][fts=3][ftc=#FF66FF]●●[/ft][/ft][fts=5][ftc=#FF9933]●●●[/ft][/ft][ftc=#FF66FF]━━━━●●●[ftc=#FFFFFF][fts=5]*[/ft][/ft]●●●━━━━[/ft][ftc=#FF66FF]打开的是吉祥,看到的是鸿运,[/ft][ftc=#FFFF00]愿所有期望和祝福涌向你,祈望你心情舒畅万事顺意,愿这美好心愿化作真挚的祝福送给你:[/ft][ftc=#FF66FF]开心百分百生活更精彩![/ft][ftc=#FF66FF]━━━━●●●[ftc=#FFFFFF][fts=5]*[/ft][/ft]●●●━━━━[/ft][fts=5][ftc=#FF9933]●●●[/ft][/ft][fts=3][ftc=#FF66FF]●●[/ft][/ft][fts=2][ftc=#FFFF33]●[/ft][/ft][fts=6][ftc=#9933FF]*[/ft][/ft]2.[M] [fts=6][ftc=#ED008C][ftf=Webdings]Y[/ft][/ft][fts=5][ftc=#EF6EA8][ftf=Webdings]Y[/ft][/ft][/ft][fts=4] [ftc=#F49BC1][ftf=Webdings]Y[/ft][/ft][/ft][fts=3][ftc=#FCE1EC][ftf=Webdings]Y[/ft][/ft][/ft][fts=3][ftc=#FCE1EC][ftf=Webdings]Y[/ft][/ft] [/ft][/ft][fts=4] [ftc=#F49BC1][ftf=Webdings]Y[/ft][/ft][/ft][ftc=#F49BC1] ━━━━━━━━━━━━[/ft][ftf=Webdings]=[/ft][/ft][ftc=#EF6EA8][ftf=Webdings]=[/ft][/ft][ftc=#F49BC1]━━━━[/ft] [fts=4][ftc=#F49BC1][ftf=Webdings]Y[/ft][/ft][/ft]3.[ftc=#6CCFF7] ┏┓┏━━┓┏┳┓┏━━┓[ftc=#EE1000][/ft][ftc=#81CA9D] ┃┃┃┏┓┃┃┃┃┃━┫[/ft] [ftc=#F16D7E][/ft][ftc=#0054A5] ┃┗┓┃┗┛┃┃┃┃┃━┫[/ft] [ftc=#F5999D][/ft]┗━┛┗━━┛┗━┛┗━━┛[/ft][ftc=#FCE0E2][/ft]_____________[ftc=#EF6EA8]♥♥[/ft] _____________[ftc=#F0000F]自己[/ft][ftc=#E1001E][/ft][ftc=#D2002D]的[/ft][ftc=#C3003C]世[/ft][ftc=#B4004B]界[/ft][ftc=#A5005A]因[/ft][ftc=#960069]自[/ft][ftc=#870078]己[/ft][ftc=#780087][/ft][ftc=#690096]而[/ft][ftc=#5A00A5]精[/ft][ftc=#4B00B4]彩[/ft]_____________[ftc=#EF6EA8]♥♥[/ft] _____________[M][fts=6][ftf=wingdings][ftc=F49BC1]@[/ft][/ft][/ft]某人、親筆[fts=6][ftc=#EE1000][ftf=Webdings]Y[/ft][/ft][/ft]4..*""*.*""*. .*""*.*""*.* 维 * .*""*.*""*. * 卡 *..*. .* * 爱 * *. .*." * " *. .* " * ".[M][ftc=#EE1000][fts=6][ftf=Webdings]Z[/ft][/ft][/ft][ftc=#ED008C][/f t][ftc=#EE1000][fts=6][ftf=Webdings]Z[/ft][/ft][/ft][ftc=#F16D7E][/ft ][ftc=#EE1000][fts=6][ftf=Webdings]Z[/ft][/ft][/ft][ftc=#F79700][/ft] [/M][M] "--┈--┈┈----┈┈---[ftc=#F49BC1]わ、[/ft][/M][/M][M][ftc=#00BFF3]人生在世无朋友,犹如生活无太阳。
php留言板
PHP+MYSQL新手学习实例代码(留言板)数据库结构:(库名:lyb)表一: admin字段: id(int11) name(varchvr) password(varchvr)表二: lo字段: id(int11) username(varchvr) sex(varchvr) qq(varchvr) email(varchvr) info(text) ip(varchvr) submit_time(datetime)1、conn.php(连接数据库文件)<?phpmysql_connect("localhost","root","");//连接数据库mysql_select_db("lyb");//选择数据库?><li><a href="admin.php">偶要管理</a></li><?}?></ul></div><div id="head_r">银子留言板Version 1.0</div></div>3、footer.php(公用底部文件)<?php$counterFile="conter.xml";function displayCounter($counterFile){$fp = fopen($counterFile,"rw");$num = fgets($fp,5);$num += 1;print "<div id=\"footer\">银子留言板Version 1.0 您是第 "."$num"." 位无聊的银</div>";exec("rm -rf $counterFile");exec("echo $num > $counterFile");}if(!file_exists($counterFile)){exec("echo 0 > $counterFile");}displayCounter($counterFile);?></body></html>4、index.php(首页)<?phprequire_once("conn.php");require_once("header.php");session_start();//分页代码开始$pagesize = 10;//设置每页显示条数$rs = mysql_query("select count(*) from lo");//取得记录总数,计算总页数用$myrow = mysql_fetch_array($rs);$numrows = $myrow[0];//计算总记录$pages = intval($numrows/$pagesize);if($numrows%$pagesize)$pages++;//设置页数if(isset($_GET['page'])){$page = intval($_GET['page']);}else{$page = 1;//设为第一页}$offset = $pagesize*($page-1);//计算记录偏移量//分页代码结束$sql = "select id,username,sex,qq,email,info,ip,DA TE_FORMA T(submit_time, '%Y年%m月%d 日%T' ) from lo order by id desc limit $offset,$pagesize";//用到了DA TE-FORMAT格式化日期格式$result = mysql_query($sql);$num = mysql_num_rows($result);if($num>0){while($row = mysql_fetch_array($result)){//echo print_r($row);if($row[2]=="男")//这个使性别改成你想要的名称^_^{$sex = "帅锅";}else{$sex = "美女";}?><div id="show"><p class="num">第[<?= $row[0] ?>] 条留言<p><p class="unline">留言人:<span class="blue"><?= $row[1]?></span> 性别:<?= $sex ?> 留言时间:<?= $row[7] ?> <? if($row[3]) {?> <a href="/msgrd?V=1&Uin=<?=$row[3] ?>&Site=&Menu=yes"><img src="img/qq.gif" alt="<?= $row[3]?>" /></a><? } ?><? if($row[4]){ ?> <a href="mailto:<?= $row[4] ?>"><img src="img/email.gif" alt="<?= $row[4]?>" /></a> <? }?><? if($_SESSION["key"]==1){ ?> IP:<?= $row[6] ?> <a href="update.php?wuleying&id=<?= $row[0]?>">更改</a> <a href="delete.php?wuleying&id=<?= $row[0]?>">删除</a><?}?></a></p><p class="blue">留言内容:</p><div id="show_info"><?= nl2br(htmlspecialchars($row[5])) ?></div></div><?php}}else{echo "<div id=\"show\">无数据......</div>";}?><div id="show_page"><p><?php$first=1;$prev=$page-1;$next=$page+1;$last=$pages;if($page==1&&$pages>1){echo "首页 | ";echo "上一页 | ";echo "<a href=\"index.php?page=".$next."\">下一页</a> | ";echo "<a href=\"index.php?page=".$last."\">尾页</a> | ";}elseif($page>=1&&$page!=$pages&&$num>0){echo "<a href=\"index.php?page=".$first."\">首页</a> | ";echo "<a href=\"index.php?page=".$prev."\">上一页</a> | ";echo "<a href=\"index.php?page=".$next."\">下一页</a> | ";echo "<a href=\"index.php?page=".$last."\">尾页</a> | ";}elseif($page==$pages&&$page!=1){echo "<a href=\"index.php?page=".$first."\">首页</a> | ";echo "<a href=\"index.php?page=".$prev."\">上一页</a> | ";echo "下一页 | ";echo "尾页 | ";}elseif($page==$pages){echo "首页 | ";echo "上一页 | ";echo "下一页 | ";echo "尾页 | ";}else{echo "首页 | ";echo "上一页 | ";echo "下一页 | ";echo "尾页 | ";}?>共 <span><?= $pages ?></span> 页 | 当前第 <span><?= $page ?></span> 页 | 共 <span><?=$numrows ?></span> 条留言</p></div><?phpmysql_close();?><?phprequire_once("footer.php");5、post.php(提交留言页面)<?require_once("header.php");?><div id="input"><form method="post" action="input.php" name="form1"><h1>提交留言</h1><p>姓名:<input type="text" name="name" size="20" class="y" /> </p><p>性别:<input name="sex" type="radio" value="男" checked/> 帅锅 <input type="radio" name="sex" value="女"/> 美女</p><p>Q Q:<input type="text" name="qq" class="y" /> (可选填)</p><p>Email:<input type="text" name="email" class="y" /> (可选填)</p><p>留言内容:</p><p><textarea name="info" rows="5" cols="40"></textarea></p><p class="cen"><input type="submit" value="偶填好了" /><input type="reset" value="偶要重写"></p><p class="cen1">银子留言板Version 1.0</p></form></div></body></html>6、input.php(插入留言)<?phprequire_once("conn.php");$username = $_POST['name'];$sex = $_POST['sex'];$qq = $_POST['qq'];$email = $_POST['email'];$info = $_POST['info'];if (strrpos($username,"<")!==false || strrpos($username,">")!==false||strrpos($username,"@")!==false||strrpos($username,"\"")!==false ||strrpos($username,"'")!==false||strrpos($username,"_")!==false)echo "<script>alert('名称不能有特殊字符!');location.href='post.php';</script>";exit();}if (!ereg("^[0-9]{0,}$",$qq))//用正则检查QQ格式{echo "<script>alert('OICQ信息有错误!必须是数字!');location.href='post.php';</script>";exit();}if($email){//如果填写了邮箱就用正则检查邮箱格式if (!ereg("^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$",$email)){echo "<script>alert('email格式不正确!');location.href='post.php';</script>";exit();}}if(!$username){echo "<script>alert('名称不能为空哦!');location.href='post.php';</script>";exit();}elseif(!$info){echo "<script>alert('留言不能为空哦!');location.href='post.php';</script>";exit();}else{$ip = getenv('REMOTE_ADDR');//获取客户端IP地址$sql = "insert into lo (username,sex,qq,email,info,ip,submit_time) values ('$username','$sex','$qq','$email','$info','$ip',NOW())";$result = mysql_query($sql);mysql_close();echo "<script>alert('提交成功!返回首页');location.href='index.php';</script>";}?>7、update.php(修改留言页)<?phpsession_start();require_once('conn.php');require_once('header.php');if($_SESSION["key"]==1){$id = $_GET['id'];$sql = "select * from lo where id= ".$id;$result = mysql_query($sql);$row = mysql_fetch_array($result);?><div id="update"><form action="updatepost.php?wuleying&id=<?= $row[0] ?>" method="post"> <h1>修改留言</h1><p>姓名:<input type="text" value="<?= $row[1]?>" name="name" class="y"></input></p><p>留言:</p><p><textarea name="info" rows="5" cols="35"><?= $row[5] ?></textarea></p><p class="cen"><input type="submit" value="偶要修改" /></p><p class="cen1">银子留言板Version 1.0</p></form><div><?php}else{header('location:index.php');}?>8、updatepost(修改提交页)<?phprequire_once('conn.php');$username = $_POST['name'];$info = $_POST['info'];$id = $_GET['id'];//echo $id;$sql = "update lo set username= '".$username."',info='".$info."' where id=".$id; mysql_query($sql);echo "<script>alert('修改成功!');location.href='index.php';</script>";?>9、delete.php(删除留言页)<?phpsession_start();require_once('conn.php');$id=$_GET['id'];if($_SESSION["key"]==1){$sql = "delete from lo where id=".$id;mysql_query($sql);echo "<script>location.href='index.php'</script>";}else{header('location:index.php');}?>10、admin.php(管理登录页)<?phprequire_once('conn.php');require_once('header.php');?><div id="admin"><form method="post" action="adminpost.php"><h1>管理员登录</h1><p>姓名: <input type="text" name="name" size="20" class="y" /> </p><p>密码: <input type="password" name="password" size="20" class="y" /> </p><p class="cen"><input type="submit" value="管理员登录" /></p><p class="cen1">银子留言板Version 1.0</p></form></div>11、adminpost.php(管理验证页)<?phpsession_start();require_once('conn.php');$name = $_POST['name'];$password = $_POST['password'];$sql = "select * from admin where name='".$name."'";$result = mysql_query($sql);$num = mysql_num_rows($result);if (strrpos($name,"<")!==false || strrpos($name,">")!==false||strrpos($name,"@")!==false||strrpos($name,"\"")!==false||strrpos($na me,"'")!==false||strrpos($name,"_")!==false){echo "<script>alert('不能有特殊字符!');location.href='admin.php';</script>";}if($num){//如果用户存在,就检查密码是否正确$rs = mysql_fetch_array($result);if($rs[2]!=$password){echo "<script>alert('密码不正确,请确认后输入!');location.href='admin.php';</script>";}else{//用户名,密码都正确,注册SESSION变量,然后跳转到首页$_SESSION["key"]=1;echo "<script>alert('登录成功!');location.href='index.php';</script>";}}else{//如果没有这个用户echo "<script>alert('没有这个用户,请确认后输入!');location.href='admin.php';</script>"; }?>12、adminexit.php(退出管理页)<?phpsession_start();$_SESSION["key"] = 0;//使SESSION不为1,0为游客,1为管理员header('location:index.php');?>只是些基本的东东,像MD5加密,UBB,表情图片,添加管理员账号,回复留言(-_!!)等我文章来源:UU网络()。
留言板开发源代码
package com.litiancms.bean;public class Word {//留言idprivate int id;//留言内容private String word_content;//留言作者private String word_zuozhe;//留言时间private String word_shijian;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getWord_content() {return word_content;}public void setWord_content(String wordContent) { word_content = wordContent;}public String getWord_zuozhe() {return word_zuozhe;}public void setWord_zuozhe(String wordZuozhe) { word_zuozhe = wordZuozhe;}public String getWord_shijian() {return word_shijian;}public void setWord_shijian(String wordShijian) { word_shijian = wordShijian;}}package com.litiancms.dao;import java.util.List;import com.litiancms.bean.Word;public interface WordDao {//留言添加public void addword(Word w)throws Exception;//删除public void delword(int id)throws Exception;// 总共有几条记录public int count() throws Exception;// 总页数public int countpage() throws Exception;// 设置每页显示几条记录public void pagesize(int pagesize) throws Exception;// 分页显示public List<Word> querypage(int page) throws Exception;}package com.litiancms.db;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class DataBase {//用户名这里的用户名指:数据库的用户名public final String UNAME="root";//用户密码这里的密码指:数据库的密码public final String UPWD="admin";//驱动程序public final String DRIVER="com.mysql.jdbc.Driver";//链接地址public final String URL="jdbc:mysql://localhost:3306/ltcms";//链接public Connection conn;//构造方法public DataBase(){try {//加载驱动程序Class.forName(DRIVER);//链接数据库conn=DriverManager.getConnection(URL, UNAME, UPWD);} catch (Exception e) {// TODO: handle exception}}//链接方法public Connection conn(){return this.conn;}//关闭public void close(){try {this.conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}package com.litiancms.factory;import com.litiancms.dao.WordDao;import com.litiancms.impl.Wordimpl;public class WordFactory {public static WordDao getword(){return new Wordimpl();}}package com.litiancms.impl;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;import com.litiancms.bean.Word;import com.litiancms.dao.WordDao;import com.litiancms.db.DataBase;public class Wordimpl implements WordDao {//分页显示int pagesize=5;// 定义连接数据库DataBase db = null;// 操作数据库PreparedStatement pstm;//集合ResultSet rs;//sql语句String sql=null;@Override//留言添加public void addword(Word w) throws Exception {// TODO Auto-generated method stub//数据库db=new DataBase();sql="insert into ltcms_word(word_content,word_zuozhe,word_shijian)values(?,?,?)";pstm=db.conn.prepareStatement(sql);pstm.setString(1,w.getWord_content());pstm.setString(2,w.getWord_zuozhe());pstm.setString(3, w.getWord_shijian());pstm.executeUpdate();pstm.close();db.close();}@Override//删除public void delword(int id) throws Exception {// TODO Auto-generated method stub//数据库db=new DataBase();sql="deldet from ltcms_word where id=?";pstm=db.conn.prepareStatement(sql);pstm.setInt(1, id);pstm.executeUpdate();pstm.close();db.close();}@Overridepublic int count() throws Exception {// TODO Auto-generated method stubint count = 0;// 连接数据库db = new DataBase();// sql语句sql = "select count(*)from ltcms_word";pstm = db.conn.prepareStatement(sql);rs = pstm.executeQuery();if (rs.next()) {count = rs.getInt(1);}rs.close();pstm.close();db.close();return count;}@Override// 总共有几页public int countpage() throws Exception { int countpage=0;//拿到总记录数int count=this .count();if (count%pagesize==0){countpage=count/pagesize;}else {countpage=count/pagesize+1;}return countpage;}@Override// 每页显示几条记录public void pagesize(int pagesize) throws Exception {this.pagesize=pagesize;}@Overridepublic List<Word> querypage(int page) throws Exception {// TODO Auto-generated method stubList<Word> lst=new ArrayList<Word>();db=new DataBase();sql="select * from ltcms_word order by word_shijian desc limit ?,?";int start = (page - 1) * pagesize;pstm = db.conn.prepareStatement(sql);pstm.setInt(1, start);pstm.setInt(2, pagesize);rs = pstm.executeQuery();Word w=null;while (rs.next()) {w=new Word();w.setId(rs.getInt(1));w.setWord_content(rs.getString(2));w.setWord_zuozhe(rs.getString(3));w.setWord_shijian(rs.getString(4));lst.add(w);}rs.close();pstm.close();db.close();return lst;}}package com.litiancms.servlet;import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.xml.crypto.Data;import org.omg.CORBA.Request;import com.litiancms.bean.Word;import com.litiancms.factory.WordFactory;import com.litiancms.impl.Wordimpl;public class WordServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {PrintWriter out = response.getWriter();String start = request.getParameter("start");String content = request.getParameter("content");String zuozhe = request.getParameter("zuozhe");SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒");String ctime = sdf.format(new Date());Word w = new Word();w.setWord_content(content);w.setWord_zuozhe(zuozhe);w.setWord_shijian(ctime);if ("addword".equals(start)) {try {WordFactory.getword().addword(w);out.println("<script>alert('留言成功');location.href='../servlet/QueyallServlet'</script>");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}// int id = Integer.parseInt(request.getParameter("id"));if ("delword".equals(start)) {try {// WordFactory.getword().delword(id);// 跳转页面// out.println("<script>alert('删除成功');location.href='../servlet/QueryallServlet';</script>");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}package com.litiancms.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.litiancms.bean.Word;import com.litiancms.factory.WordFactory;public class QueyallServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PrintWriter out = response.getWriter();int pagestart=1;try {Integer count=WordFactory.getword().count();Integer countpage=WordFactory.getword().countpage();String start = request.getParameter("start");if (start != null) {try {pagestart = Integer.parseInt(start);if (pagestart > countpage) {pagestart = countpage;}} catch (Exception e) {// TODO: handle exceptionpagestart = 1;}}// 分页List<Word> lst=new ArrayList<Word>();lst=WordFactory.getword().querypage(pagestart);// 当前页数request.setAttribute("pagestart", pagestart);// 记录数request.setAttribute("count", count);// 总页数request.setAttribute("countpage", countpage);request.setAttribute("lst",WordFactory.getword().querypage(pagestart));request.getRequestDispatcher("../index.jsp").forward(request, response);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}添加页面<%@ page contentType="text/html;charset=gb2312"%><script type="text/javascript" src="js/edit.js"></script><br><img src="images/addtitle.jpg"><hr color="#ACCE69" width="90%" style="border-style:solid;margin-top:-10"><a name="addword"></a><form action="servlet/WordServlet" name="editform" method="post"><input type="hidden" name="start" value="addword"><input type="hidden" name="zuozhe" value="游客"><table width="90%" border="0" cellpadding="0" cellspacing="0"><tr><td width="67%"><font color="#7F7F7F">最多:<b><span id="ContentAll" style="width:40;text-align:center">500</span></b>已用:<b><span id="ContentUse" style="width:40;text-align:center">0</span></b>剩余:<b><span id="ContentRem" style="width:40;text-align:center">500</span></b></font> <b><span id="checkmessage" style="color:red"></span></b></td><td align="right"></td></tr><tr><td colspan="2"><textarea rows="12" cols="99" name="content" onpropertychange="checkLen()"></textarea></tr><tr height="30"><td colspan="2" align="center"><input type="button" name="submitb" onclick="editformsubmit()" style="background:url('images/submit.jpg');width:97;height:26;border:0"><input type="reset" value="" style="background:url('images/reset.jpg');width:97;height:26;border:0"></td></tr></table></form><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@page import="java.text.SimpleDateFormat"%><%@ taglib prefix="c" uri="/jsp/jstl/core" %><%@ taglib prefix="fmt" uri="/jsp/jstl/fmt" %><%@ taglib prefix="pg" uri="/tags/navigation/pager" %><%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 'index.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">--><style type="text/css">body{padding: 0px;margin: 0px;}</style></head><body><center><jsp:include page="top.jsp"></jsp:include><jsp:include page="menu.jsp"></jsp:include><table border="0" width="80%" align="left"><tr><td align="right" width="20%"><img src="images/ad.jpg"><br><br><img src="images/ad.jpg"><br><br><img src="images/ad.jpg"><br><br></td><td valign="top" width="80%"><table border="0" width="90%" cellpadding="0" cellspacing="0"><tr height="50" valign="bottom"><td><img src="images/newtitle.jpg" height="28"></td></tr></table><c:forEach items="${requestScope.lst}" var="w"><table bgcolor="#ACCE69" border="0" width="80%" style="word-break:break-all;margin-top:3" cellpadding="8" cellspacing="1"><tr bgcolor="#F5FFE8"><td><%SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");String ctime=sdf.format(new Date());request.getParameter(ctime);request.setAttribute(ctime,new Date());%><div style="margin-top:0">☆<b><u>${w.word_zuozhe }</u></b></div><div style="margin-top:-20;color:gray" align="right"><%//<fmt:formatDate value="${ctime}" var="dd"/>//<fmt:setLocale value="zh_CN"/>//${dd}%>${w.word_shijian }<br></div><input type="hidden" name="start"><hr color="black">${w.word_content }<br><br></td></tr></table></c:forEach>总计录数:<font color="red">${requestScope.count}</font> 当前页数:<font color="red">${requestScope.pagestart}/${requestScope.countpage}</font> <c:choose><c:whentest="${requestScope.pagestart==1&&requestScope.pagestart<requestScope.countpage}"> 首页 上一页 <a href="servlet/QueyallServlet?start=${requestScope.pagestart+1 }">下一页</a> <a href="servlet/QueyallServlet?start=${requestScope.countpage}">末页</a> </c:when><c:whentest="${1<requestScope.pagestart&&requestScope.pagestart==requestScope.countpage}"><a href="servlet/QueyallServlet?start=${requestScope.pagesize}">首页</a> <a href="servlet/QueyallServlet?start=${requestScope.pagestart-1}">上一页</a> 下一页 末页</c:when><c:otherwise><a href="servlet/QueyallServlet?start=1">首页</a> <a href="servlet/QueyallServlet?start=${requestScope.pagestart-1}">上一页</a> <a href="servlet/QueyallServlet?start=${requestScope.pagestart+1 }">下一页</a> <a href="servlet/QueyallServlet?start=${requestScope.countpage}">末页</a> </c:otherwise></c:choose><%--<a href="servlet/QueyallServlet?start=${pagesize}">首页</a> <a href="servlet/QueyallServlet?start=${pagestart-1}">上一页</a> <a href="servlet/QueyallServlet?start=${pagestart+1 }">下一页</a> <a href="servlet/QueyallServlet?start=${countpage}">末页</a> --%><jsp:include page="addword.jsp"></jsp:include></td></tr><tr><td colspan="2"><jsp:include page="end.jsp"></jsp:include></td></tr></table></center></body></html>。
C#留言板制作(报告+源码)
一、业务流程与功能设计1、管理员(权限为1):管理员在前台页面通过验证后,可以直接登录到后台管理页面,对留言进行增删查改等操作。
2、普通用户(权限为0):普通用户可以对自己留言进行查看,发表3、业务流程图注册用户普通用户管理员是发表留言查看留言回复留言登录否管理留言二、数据库设计1、综述:本系统采用了SQL Server2005数据库,建立了三个数据表,用户信息表tb_User、留言表tb_LeaveWord、回复表tb_Reply2、三个数据表如下:用户信息表tb_User留言表tb_LeaveWord回复表tb_Reply3、数据库连接操作类SqlData.cs代码:public class SqlData{private SqlConnection sqlcon;private SqlCommand sqlcom;private SqlDataAdapter sqldata;public SqlData(){sqlcon = new SqlConnection("Data Source=.\\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|db_22.mdf;User Instance=true");sqlcon.Open();}public bool ExceSQL(string strSqlCom){sqlcom = new SqlCommand(strSqlCom, sqlcon);try{sqlcom.ExecuteNonQuery();return true;}catch{return false;}{sqlcon.Close();}}public DataSet ExceDS(string SqlCom){try{sqlcom = new SqlCommand(SqlCom, sqlcon);sqldata = new SqlDataAdapter();sqldata.SelectCommand = sqlcom;DataSet ds = new DataSet();sqldata.Fill(ds);return ds;}finally{sqlcon.Close();}}public SqlDataReader ExceRead(string SqlCom){sqlcom = new SqlCommand(SqlCom, sqlcon);SqlDataReader read = sqlcom.ExecuteReader();return read;}#endregion}三、各模块设计1、母版设计界面:public partial class MasterPage : System.Web.UI.MasterPage{protected void Page_Load(object sender, EventArgs e){}protected void Button1_Click(object sender, EventArgs e){SqlConnection con = new SqlConnection("Data Source=.\\SQLExpress;IntegratedSecurity=True;AttachDBFilename=|DataDirectory|db_22.mdf;User Instance=true");con.Open();if (TextBox1.Text == ""){Response.Write("<script language=javascript>alert('输º?入¨?不?能¨¹为a空?!ê?');location='query.aspx'</script>");}else{string str = "select * from tb_LeaveWord where Subject like'%" + TextBox1.Text + "%'";SqlCommand cmd = new SqlCommand(str, con);SqlDataReader reader = cmd.ExecuteReader();reader.Read();if (reader.HasRows){reader.Close();PagedDataSource pgds = new PagedDataSource();string sqlStr1 = "select ID,Uid,Subject,Content,DateTime from tb_LeaveWord where Subject like'%" + TextBox1.Text + "%'";SqlDataAdapter Adapter = new SqlDataAdapter(sqlStr1, con);DataSet ds = new DataSet();Adapter.Fill(ds, "tb_LeaveWord");pgds.DataSource= ds.Tables["tb_LeaveWord"].DefaultView;this.GridView1.DataSource = pgds;this.GridView1.DataBind();}else{Response.Write("<script language=javascript>alert('没?有®D相¨¤关?内¨²容¨Y!ê?');location='query.aspx'</script>");}}}}2、留言板主页(查看主题)设计界面:后台代码:public partial class UserControls_ShowWord : erControl{protected void Page_Load(object sender, EventArgs e){}public string GetList(){SqlData da = new SqlData();SqlDataReader dr = da.ExceRead("select * from tb_LeaveWord ");string strBody = "<table width=150>";while (dr.Read()){strBody += "<tr><td class=tableBottom>·¡è<a href=ShowWord.aspx?ID=" + d r["ID"] + " >" + dr["Subject"].ToString() + "</a></td></tr>\n";}dr.Close();strBody += "</table>";return strBody;}}4、发表留言模块设计界面:后台代码:(先检测是否已登录)public partial class Default2 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (Session["UserName"] == null){Response.Redirect("Login.aspx");}}protected void btnOK_Click(object sender, EventArgs e){SqlData da = new SqlData();string cmdtxt = "INSERT INTO tb_LeaveWord(Uid,Subject,Content,DateTime,IP)";cmdtxt += " VALUES('" + Session["UserName"].ToString()+ "','" + this.TextBox1.Text + "'"; cmdtxt += ",'"+this.FreeTextBox1.Text+"','" + DateTime.Now+ "'";cmdtxt += ",'" + erHostAddress + "')";bool add = da.ExceSQL(cmdtxt);if (add == true){Response.Write("<script language=javascript>alert('添¬¨ª加¨®成¨¦功|!');location='Default.aspx'</script>");}{Response.Write("<script language=javascript>alert('添¬¨ª加¨®失º¡ì败㨹!ê?');location='javascript:history.go(-1)'</script>");}}protected void Button1_Click(object sender, EventArgs e){this.TextBox1.Text = "";this.FreeTextBox1.Text = "";}}5、用户信息注册模块设计界面:后台代码:public partial class UserControls_Register : erControl{protected void Page_Load(object sender, EventArgs e){}protected void btnOK_Click(object sender, EventArgs e){this.MultiView1.ActiveViewIndex = 1;}protected void btnOK1_Click(object sender, EventArgs e){SqlData da = new SqlData();SqlDataReader read = da.ExceRead("select * from tb_User where Uid='" + this.txtUid.Text + "'"); read.Read();if (read.HasRows){if (this.txtUid.Text == read["Uid"].ToString())Response.Write("<script language=javascript>alert('对?不?起e,ê?该?用®?户¡ì已°?经-注Á¡é册¨¢!ê?');location='Register.aspx'</script>");return;}}read.Close();string cmdtxt = "INSERT INTO tb_User(Uid,Pwd,Sex,WebSite,Email,QQ,IP)";cmdtxt += " VALUES('" + this.txtUid.Text + "','" + this.txtPwd.Text + "','" +this.radSex.SelectedValue+ "'";cmdtxt += ",'" + this.txtWebSite.Text + "','" + this.txtEmail.Text + "','" + this.txtQQ.Text + "'"; cmdtxt += ",'" + erHostAddress + "')";bool add = da.ExceSQL(cmdtxt);if (add == true){Response.Write("<script language=javascript>alert('注Á¡é册¨¢成¨¦功|!');location='Default.aspx'</script>");}else{Response.Write("<script language=javascript>alert('注Á¡é册¨¢失º¡ì败㨹!ê?');location='javascript:history.go(-1)'</script>");}}protected void btnNoOK_Click(object sender, EventArgs e){Response.Redirect("Default.aspx");}}6、个人留言信息查看模块设计界面:后台代码:(先检测是否登录)public partial class Default2 : System.Web.UI.Page{public string ShowSubject, ShowTime, ShowContent;protected void Page_Load(object sender, EventArgs e){if (Session["UserName"] == null){Response.Redirect("Login2.aspx");}this.dlBind();}public string[] ReplyName = null;public string[] ReplyTime = null;public string[] ReplyContent = null;public string strName=null;public void dlBind(){string id = null;SqlData da = new SqlData();int curpage = Convert.ToInt32(labNowPage.Text);PagedDataSource ps = new PagedDataSource();SqlConnection mycon = new SqlConnection("Data Source=.\\SQLExpress;IntegratedSecurity=True;AttachDBFilename=|DataDirectory|db_22.mdf;User Instance=true");mycon.Open();string cmdtxt1 = "SELECT * FROM tb_LeaveWord WHERE Uid='" + Session["UserName"].ToString() + "'"; SqlDataAdapter MyAdapter = new SqlDataAdapter(cmdtxt1, mycon);DataSet ds = new DataSet();MyAdapter.Fill(ds, "tb_LeaveWord");ps.DataSource = ds.Tables["tb_LeaveWord"].DefaultView;ps.AllowPaging = true; //是º?否¤?可¨¦以°?分¤?页°3ps.PageSize = 3; //显?示º?的Ì?数ºy量¢?ps.CurrentPageIndex = curpage - 1; //取¨?得Ì?当Ì¡À前¡ã页°3的Ì?页°3码?lnkbtnPrve.Enabled = true;lnkbtnTop.Enabled = true;lnkbtnNext.Enabled = true;lnkbtnLast.Enabled = true;if (curpage == 1){lnkbtnTop.Enabled = false;//不?显?示º?第̨²一°?页°3按ã¡ä钮£¤lnkbtnPrve.Enabled = false;//不?显?示º?上¦?一°?页°3按ã¡ä钮£¤}if (curpage == ps.PageCount){lnkbtnNext.Enabled = false;//不?显?示º?下?一°?页°3}bCount.Text = Convert.ToString(ps.PageCount);this.DataList1.DataSource = ps;this.DataList1.DataKeyField = "ID";this.DataList1.DataBind();}protected void lnkbtnTop_Click(object sender, EventArgs e){bNowPage.Text = "1";this.dlBind();}protected void lnkbtnPrve_Click(object sender, EventArgs e){bNowPage.Text = Convert.ToString(Convert.ToInt32(bNowPage.Text) - 1);this.dlBind();}protected void lnkbtnNext_Click(object sender, EventArgs e){bNowPage.Text = Convert.ToString(Convert.ToInt32(bNowPage.Text) + 1);this.dlBind();}protected void lnkbtnLast_Click(object sender, EventArgs e){bNowPage.Text = bCount.Text;this.dlBind();}protected void lnkbtnFeedBack_Click(object sender, EventArgs e){Response.Redirect("LeaveWordBack.aspx?ID="+Request["ID"].ToString()+"");}protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e){string strid = this.DataList1.DataKeys[e.Item.ItemIndex].ToString(); //获?取¨?当Ì¡À前¡ãDataList 控?件t列¢Dstring com = "Delete from tb_LeaveWord where ID='" + Convert.ToInt32(strid) + "'";SqlData da = new SqlData();da.ExceSQL(com);Page.Response.Redirect("MyWord.aspx");}}7、留言信息管理模块设计界面后台代码:public partial class Default2 : System.Web.UI.Page{public string ShowSubject, ShowTime, ShowContent; //声¦¨´明¡Â的Ì?变À?量¢?protected void Page_Load(object sender, EventArgs e){if (Session["UserName"] == null){Response.Redirect("Login.aspx");}this.dlBind();}public void dlBind(){string id = null;SqlData da = new SqlData();int curpage = Convert.ToInt32(labNowPage.Text);PagedDataSource ps = new PagedDataSource();SqlConnection mycon = new SqlConnection("Data Source=.\\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|db_22.mdf;User Instance=true");mycon.Open();string cmdtxt1 = "SELECT * FROM tb_LeaveWord";SqlDataAdapter MyAdapter = new SqlDataAdapter(cmdtxt1, mycon);DataSet ds = new DataSet();MyAdapter.Fill(ds, "tb_LeaveWord");ps.DataSource = ds.Tables["tb_LeaveWord"].DefaultView;ps.AllowPaging = true;ps.PageSize = 3;ps.CurrentPageIndex = curpage - 1;lnkbtnPrve.Enabled = true;lnkbtnTop.Enabled = true;lnkbtnNext.Enabled = true;lnkbtnLast.Enabled = true;if (curpage == 1){lnkbtnTop.Enabled = false;lnkbtnPrve.Enabled = false; }if (curpage == ps.PageCount){lnkbtnNext.Enabled = false;lnkbtnLast.Enabled = false;}bCount.Text = Convert.ToString(ps.PageCount);this.DataList1.DataSource = ps;this.DataList1.DataKeyField = "ID";this.DataList1.DataBind();}protected void lnkbtnTop_Click(object sender, EventArgs e){bNowPage.Text = "1";this.dlBind();}protected void lnkbtnPrve_Click(object sender, EventArgs e){bNowPage.Text = Convert.ToString(Convert.ToInt32(bNowPage.Text) - 1);this.dlBind();}protected void lnkbtnNext_Click(object sender, EventArgs e){bNowPage.Text = Convert.ToString(Convert.ToInt32(bNowPage.Text) + 1);this.dlBind();}protected void lnkbtnLast_Click(object sender, EventArgs e){bNowPage.Text = bCount.Text;this.dlBind();}protected void lnkbtnFeedBack_Click(object sender, EventArgs e){Response.Redirect("LeaveWordBack.aspx?ID="+Request["ID"].ToString()+"");}protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e){string strid = this.DataList1.DataKeys[e.Item.ItemIndex].ToString(); //获?取¨?当Ì¡À前¡ãDataList 控?件t列¢Dstring com = "Delete from tb_LeaveWord where ID='" + Convert.ToInt32(strid) + "'";SqlData da = new SqlData();da.ExceSQL(com);Page.Response.Redirect("LeaveWordManage.aspx");}protected void lnkbtnDelete_Click(object sender, EventArgs e){}}7、回复留言设计模块界面:后台代码:public partial class Default2 : System.Web.UI.Page{public string ShowSubject, ShowTime, ShowContent; //声¦¨´明¡Â的Ì?变À?量¢?protected void Page_Load(object sender, EventArgs e){if (Session["UserName"] == null){Response.Redirect("Login.aspx");}this.dlBind();}public void dlBind(){string id = null;SqlData da = new SqlData();int curpage = Convert.ToInt32(labNowPage.Text);PagedDataSource ps = new PagedDataSource();SqlConnection mycon = new SqlConnection("Data Source=.\\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|db_22.mdf;User Instance=true");mycon.Open();string cmdtxt1 = "SELECT * FROM tb_LeaveWord";SqlDataAdapter MyAdapter = new SqlDataAdapter(cmdtxt1, mycon);DataSet ds = new DataSet();MyAdapter.Fill(ds, "tb_LeaveWord");ps.DataSource = ds.Tables["tb_LeaveWord"].DefaultView;ps.AllowPaging = true; //是º?否¤?可¨¦以°?分¤?页°3ps.PageSize = 3; //显?示º?的Ì?数ºy量¢?ps.CurrentPageIndex = curpage - 1; //取¨?得Ì?当Ì¡À前¡ã页°3的Ì?页°3码?lnkbtnPrve.Enabled = true;lnkbtnTop.Enabled = true;lnkbtnNext.Enabled = true;lnkbtnLast.Enabled = true;if (curpage == 1){lnkbtnTop.Enabled = false;//不?显?示º?第̨²一°?页°3按ã¡ä钮£¤lnkbtnPrve.Enabled = false;//不?显?示º?上¦?一°?页°3按ã¡ä钮£¤}if (curpage == ps.PageCount){lnkbtnNext.Enabled = false;//不?显?示º?下?一°?页°3lnkbtnLast.Enabled = false;//不?显?示º?最Á?后¨®一°?页°3}bCount.Text = Convert.ToString(ps.PageCount);this.DataList1.DataSource = ps;this.DataList1.DataKeyField = "ID";this.DataList1.DataBind();}protected void lnkbtnTop_Click(object sender, EventArgs e){bNowPage.Text = "1";this.dlBind();}protected void lnkbtnPrve_Click(object sender, EventArgs e){bNowPage.Text = Convert.ToString(Convert.ToInt32(bNowPage.Text) - 1); this.dlBind();}protected void lnkbtnNext_Click(object sender, EventArgs e){bNowPage.Text = Convert.ToString(Convert.ToInt32(bNowPage.Text) + 1); this.dlBind();}protected void lnkbtnLast_Click(object sender, EventArgs e){bNowPage.Text = bCount.Text;this.dlBind();}protected void lnkbtnFeedBack_Click(object sender, EventArgs e){Response.Redirect("LeaveWordBack.aspx?ID="+Request["ID"].ToString()+"");}protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e){string strid = this.DataList1.DataKeys[e.Item.ItemIndex].ToString(); //获?取¨?当Ì¡À前¡ãDataList 控?件t列¢Dstring com = "Delete from tb_LeaveWord where ID='" + Convert.ToInt32(strid) + "'";SqlData da = new SqlData();da.ExceSQL(com);Page.Response.Redirect("LeaveWordManage.aspx");}protected void lnkbtnDelete_Click(object sender, EventArgs e){}}回复编辑界面后台代码:public partial class Default3 : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){SqlConnection Con = new SqlConnection("Data Source=.\\SQLExpress;IntegratedSecurity=True;AttachDBFilename=|DataDirectory|db_22.mdf;User Instance=true");Con.Open();string id = Request["ID"].ToString();string cmdtxt = "SELECT * FROM tb_LeaveWord WHERE ID=" + id + "";SqlData da = new SqlData();SqlCommand Com = new SqlCommand(cmdtxt, Con);SqlDataReader dr = Com.ExecuteReader();dr.Read();if (dr.HasRows){this.txtSubject.Text = dr["Subject"].ToString();}dr.Close();}}protected void btnOK_Click(object sender, EventArgs e){SqlData da = new SqlData();string cmdtxt = "INSERT INTO tb_Reply(UName,Content,DateTime,ReplyID,IP)";cmdtxt += "VALUES('" + this.txtUid.Text + "','" + this.FreeTextBox1.Text + "','" + DateTime.Now + "'";cmdtxt += "," + Request["ID"].ToString() + ",'" + erHostAddress + "')";if (da.ExceSQL(cmdtxt)){Response.Write("<script language=javascript>alert('操¨´作Á¡Â成¨¦功|!ê?');location='LeaveWordView.aspx?ID="+Request["ID"]+"'</script>");}else{Response.Write("<script language=javascript>alert('操¨´作Á¡Â失º¡ì败㨹!ê?')</script>");}}}8、添加功能(1)、分页,其代码示例如下:MyAdapter.Fill(ds, "tb_LeaveWord");ps.DataSource = ds.Tables["tb_LeaveWord"].DefaultView;ps.AllowPaging = true; //是º?否¤?可¨¦以°?分¤?页°3ps.PageSize = 3; //显?示º?的Ì?数ºy量¢?ps.CurrentPageIndex = curpage - 1; //取¨?得Ì?当Ì¡À前¡ã页°3的Ì?页°3码?lnkbtnPrve.Enabled = true;lnkbtnTop.Enabled = true;lnkbtnNext.Enabled = true;lnkbtnLast.Enabled = true;if (curpage == 1){lnkbtnTop.Enabled = false;//不?显?示º?第̨²一°?页°3按ã¡ä钮£¤lnkbtnPrve.Enabled = false;//不?显?示º?上¦?一°?页°3按ã¡ä钮£¤}if (curpage == ps.PageCount){lnkbtnNext.Enabled = false;//不?显?示º?下?一°?页°3lnkbtnLast.Enabled = false;//不?显?示º?最Á?后¨®一°?页°3}bCount.Text = Convert.ToString(ps.PageCount);this.DataList1.DataSource = ps;this.DataList1.DataKeyField = "ID";this.DataList1.DataBind();(2)、搜索模块,详见母版设计四、总结这个设计是在参考老师给出的例子的基础上做出来的,在设计的过程中我遇到了很多问题。
简单留言板代码
简单留言板代码篇一:留言版代码ASP留言板源代码:有主页,回复和删除三个版面主程序htmlheadtitle业牧粞员?lt;/titlemeta http-equiv=Content-Type content=text/html; charset=gb2312 /headscript language=VBScriptsub check()if erid.value=empty thenmsgbox 请输入您的昵称!focusto(0)exit subend ifif form.email.value=empty thenmsgbox 请输入您的E-mail地址!focusto(1)exit subend ifif instr(form.email.value, @)=0 thenmsgbox 您的E-mail地址不正确,是不是记错了?再想想!focusto(1)exit subend ifif form.content.value=empty thenmsgbox 请输入您的留言内容!focusto(5)exit subend ifform.submitend subsub focusto(x)document.form.elements(x).focus()end sub/scriptbody bgcolor=#CCFFCC text=#333333table width=90% border=0 bordercolorlight=#E2F3F2 height=77 align=centertrtd height=47 colspan=2 bgcolor=#00FFFFdiv align=center font face=华文行楷size=+6font color=#FF0000 face=行楷strong留言本/strong/font/font/div /td/trtrtd colspan=2 height=2p align=centerfont face=隶书size=+2font face=楷体_GB2312ba href=show.aspfont size=+1查看留言/font/a/b/font /font/p/td/tr/tabletable width=90% border=0 align=centertr bgcolor=#E2F3F2 align=center valign=middletd height=385form action=show.asp method=post name=form id=formtable align=center bgcolor=#E2F3F2 border=1cellpadding=0 cellspacing=0 width=100%tbodytr bgcolor=#CCFFCCtd width=96 height=34div align=centerfont color=#0000FF昵称:/font/div/tdtd width=441 height=34input maxlength=30 name=useridfont color=#FF0000* /font/td/trtr bgcolor=#CCFFCCtd width=96 height=35div align=centerfont color=#0000FF伊妹儿:/font/div/tdtd width=441 height=35 colspan=3input type=text name=emailfont color=#FF0000* /font/td/trtr bgcolor=#CCFFCCtd width=96 height=36div align=centerfont color=#0000FF主题:/font/div/tdtd width=441 height=36 colspan=3input maxlength=200 name=subject size=40/td/trtr bgcolor=#CCFFCCtd width=96 height=36div align=centerfont color=#0000FF你的QQ:/font/div/tdtd width=441 height=36 colspan=3input name=qq type=text id=qq maxlength=10/td/trtr bgcolor=#CCFFCCtd width=96 height=37div align=centerfont color=#0000FF 你的主页:/font/div/tdtd width=441 height=37 colspan=3input name=site type=text id=site value=/td/trtr bgcolor=#CCFFCCtd width=96 height=147div align=centerfont color=#0000FF留言内容:/font/div/tdtd width=441 height=147 colspan=3textarea cols=50 name=content rows=12/textarea/td/trtr align=middle bgcolor=#CCFFCCtd height=56 colspan=4div align=centerinput name=button1 type=button value= 发表onclick=check() input name=button2 type=reset value= 重写/div/td/tr/tbody/table/form/td/tr/table/body/html保存程序%@ language=VBScript%htmlheadtitle保存留言/titlemeta http-equiv=Content-Type content=text/html; charset=gb2312 /headbody bgcolor=#CCFFCC text=#0000FFp align=centerstrongfont color=#FF0000 size=+6 face=行楷我的留言本/font/strong/p%'获得表单内的信息userid = Request.Form (userid)title= Request.Form(subject)site=Request.Form(site)content= Request.Form(content)email=Request.Form(email)wtime=now()from=Request.ServerVariables(REMOTE_ADDR)email=a href=mailto: & email & & email & /aif title= thentitle=无标题end ifOn Error Resume NextApplication.Lock'以ForAppending模式开启留言文件set fso = CreateObject(Scripting.FileSystemObject)'取得save和oldsave两个文件的完整路径filepath=server.MapPath(save.txt)oldfilepath=server.MapPath(oldsave.txt)'将save改名为oldsavefso.CopyFile filepath ,oldfilepath'打开oldsave文件set readf=fso.OpenTextFile(oldfilepath,1,true)t=readf.ReadAll'打开save文件set showf=fso.CreateTextFile(filepath,true)'将新的留言内容添加(append)到留言文件中showf.WriteLine arrow & b留言者/b:& userid & brshowf.WriteLine arrow & b伊妹儿/b>:& email & brshowf.WriteLine arrow & b来自于/b:& from & br showf.WriteLine arrow & b发表日期/b:& wtime & brshowf.WriteLine arrow & b留言者主页/b:& site & brshowf.WriteLine arrow & b留言标题/b:& title & brshowf.WriteLine arrow & b留言内容/b:& content & pshowf.WriteLineshowf.WriteLine hr' 读出oldsave的内容,写入save中showf.WriteLine t'关闭oldsave文件readf.Close'删除oldsave文件fso.DeleteFile oldfilepath,trueApplication.UnLock'顺便将留言内容输出到浏览器中Response.Write h3Response.Write 以下是i & userid & /i 的留言内容:Response.Write /h3hrResponse.Write arrow & b来自于/b:& from & br Response.Write arrow & b伊妹儿/b :& email & brResponse.Write arrow & b发表日期/b:& wtime & br Response.Write arrow & b留言者主页/b:& site & br Response.Write arrow & b留言标题/b:& title & brResponse.Write arrow & b留言内容/b:& content & p Response.Write hr%p align=center点击 A href=show.aspfont color=#FF00FF这里/font/A,font color=#0000FF查看所有留言!/font/p /body/html显示程序@ language=VBScript%htmlheadtitle所有留言/titlemeta http-equiv=Content-Type content=text/html; charset=gb2312 /headbody bgcolor=#CCFFCC text=#0000FFp align=centerfont face=华文行楷size=+6font color=#FF0000 face=行楷strong留言本/strong/font/font /phrp align=center /p%on error resume nextset fso = CreateObject(Scripting.FileSystemObject)filepath=server.MapPath(save.txt)set showall=fso.OpenTextFile(filepath,1,true)t=showall.ReadAll篇二:网上留言簿jsp实现(附所有代码)计算机与信息学院《计算机网络系统实践》报告设计题目:网上留言簿的设计与实现学生姓名:学号:专业班级:计算机科学与技术X班2014年1 月二、选做部分题目:网上留言簿的设计与实现1设计要求1.进行网上留言簿的需求分析和功能设计;2.在数据库中构建数据库、表或视图,熟悉数据库开发流程; 3.根据网上留言簿的功能,设计各页面和脚本,掌握动态网页的制作技术;2开发环境操作系统:Windows7数据库:SQL Server 2005开发平台:MyEclipse 8.63基本原理1、Web编程Web编程简单地说是基于WWW的Internet上的应用程序开发,随着Internet的普及与传播,越来越多的人通过WWW走进网络世界的大门。
留言板主人寄语代码
留言板主人寄语代码第一款:伤感离别彩色留言代码:树叶的离开是风的追求。
[M][B][ftf=comic sans ms][ftc=E4F2E2][ftf=Wingdings][fts=6]| [/ft][fts=5]|[/ft][/ft][/ft][ftc=EE1000][ftf=Wingdings][fts=4]{{[/ft][ /ft][/ft][ftc=E4F2E2][ftf=Wingdings][fts=5 ]|[/ft][fts=6]|[/ft][/ft][/ft][ftc=666666])))[fts=5][ftc=91278F]*[/ft][/ft])))[fts=6][ftc=37B400]*[/ft][/ft])))[fts=6][ftc=37B400]*[/ft][/ft])))[fts=5][ftc=91278F]*[/ft][/ft])))[/ft] [ftc=FCE1EC][ftc=8FC63D]树叶[/ft][ftc=0072BC]的[/ft]离开,是[ftc=FFF100]风的[/ft][ftc=ED008C]追求[/ft][ftc=652C91]还[/ft]。
[ftc=F7941D][/ft]是[ftc=EE1000]树[/ft]的[ftc=EE1000]不[/ft]挽[ftc=00A99E]留[/ft]![/ft][ftc=666666]))[fts=5][ftc=91278F]*[/ft][/ft]))[fts=6][ftc=37B400]*[/ft][/ft]))[fts=6][ftc=37B400]*[/ft][/ft]))[fts=5][ftc=91278F]*[/ft][/ft]))[/ft][ftc=E4F2E2][ftf=Wingdings][fts=5]| [/ft][/ft][/ft][ftc=FCE0E2][ftf=Wingdings][fts=5]|[/ft][/ ft][/ft][ftc=E4F2E2][ftf=Wingdings][fts=5]|[/ft][/ ft][/ft][ftc=E4F2E2][ftf=Wingdings][fts=5]| [/ft][/ft][/ft][ftc=E4F2E2][ftf=Wingdings][fts=5]|[/ft][/ ft][/ft]第二款:彩色爱情留言板代码:一辈子在一起,必须的。
学习制作PHP+MYSQL留言板步简单步骤
建立数据库bbs,在数据库bbs中建立表message,如下:CREA TE TABLE `message` (`id` tinyint(1) NOT NULL auto_increment,`user` varchar(25) NOT NULL,`title` varchar(50) NOT NULL,`content` tinytext NOT NULL,`lastdate` date NOT NULL,PRIMARY KEY(`id`)) ENGINE=InnoDB DEFAULT CHARSET=gbk AUTO_INCREMENT=1 ;1、(保存为conn.PHP)<?php$conn = @ mysql_connect("127.0.0.1","root","") or die("数据库链接错误");mysql_select_db("bbs",$conn);mysql_query("set names 'GBK'"); //使用GBK中文编码;function htmtocode($content) {$content = str_replace("\n", "<br>", str_replace(" ", " ", $content));return$content;}//$content=str_replace("'","‘",$content);//htmlspecialchars();?>注释:替换输入内容中输入的回车和空格,写入这个函数后,在list.php中的内容输出语句写为:Echo <?php echo htmtocode($row[content]);?>function htmtocode($content) {$content = str_replace("\n", "<br>", str_replace(" ", " ", $content));return$content;2、(保存为add.php)<?phpinclude("conn.php");include("head.php");if($_POST[submit]){$sql="insert into messagevalues('','$_POST[user]','$_POST[title]','$_POST[content]',now())";if(mysql_query($sql)) {echo"<center>发布成功<center/>";}}?><SCRIPT language=javascript>function CheckPost(){ if (er.value==""){ alert("请填写用户名");er.focus();return false;}if (myform.title.value.length<5)//这里的5个字符是5个汉字或者是5个字母。
使用数据库实现web留言板
使⽤数据库实现web留⾔板⽕狐和ie是不⽀持的html5本地数据库(web sql Darabase)核⼼⽅法 openDatabase transaction executeSql⼩解:1 openDatabase 能使⽤现有数据库或创建新数据库创建数据库对象。
2 transaction 能访问数据库3 executeSql 执⾏SQl查询(例如获取数据,将传进来的数据保存在数据库中)<body onload="init();"><table><tr><td>姓名</td><td><input type="text" id="name"/></td></tr><tr><td>留⾔</td><td><input type="text" id="memo"/></td></tr><tr><td><input type="button" value="保存" onclick="saveData();"/></td></tr></table><hr/><table id="datatable" border="1"></table><p id="msg"></p><script>var datatable =null;var db=openDatabase('MyData' , '','My Database',102400);if (!db) {console.log("数据库创建失败!");} else {console.log("数据库创建成功!");}function init(){datatable = document.getElementById("datatable");showAllData();}/*//removeChild() ⽅法指定元素的某个指定的⼦节点。
java留言本,实现对数据库的多种操作
说明:本java留言本程序由本人一人所创,功能是提供留言,在MyEclipse下运行成功,分享给大家做java建立操作数据库程序的参考。
本程序中采用java纯驱动方式连接MICROSOFT SQL SERVER,jdbc驱动可以从微软官网下载到,所有涉及数据库的连接时的代码请自行修改。
留言本登陆界面代码import java.awt.Dimension;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import .URL;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextField;import javax.swing.JRadioButton;import javax.swing.ButtonGroup;import javax.swing.KeyStroke;class Load extends JPanel{JButton button1,button2,button3;JLabel label1,label2;JTextField text1;JPasswordField text2;JRadioButton user,admin;ButtonGroup bg;final String userName,passwrod;Font f=new Font("TimesRoman",Font.BOLD,18);URL path=Load.class.getResource("a1.jpg"); //读取图片资源public Load(){userName = "abc";passwrod = "123";setLayout(null);label1 = new JLabel("用户名:");label1.setBounds(100, 50, 90, 30); label1.setFont(f);label2 = new JLabel("密码:");label2.setBounds(100,100, 80, 30); label2.setFont(f);text1 = new JTextField();text1.setBounds(190, 50, 130, 30); text1.setFont(f);text2 = new JPasswordField();text2.setBounds(190, 100, 130, 30); text2.setFont(f);button1 = new JButton("登陆");button1.setBounds(100, 200, 80, 30); button1.setFont(f);button2= new JButton("注册");button2.setBounds(100, 250, 80, 30); button2.setFont(f);button3 = new JButton("退出");button3.setBounds(320,250,80, 30); button3.setFont(f);user=new JRadioButton("用户",true);//选中user.setBounds(250,200,66,30); user.setFont(f); user.setActionCommand("用户");admin=new JRadioButton("管理员",false);admin.setBounds(316, 200,85,30); admin.setFont(f); admin.setActionCommand("管理员");bg=new ButtonGroup();bg.add(user);//单选按钮加入按钮组实现单选功能bg.add(admin);add(label1);add(label2);add(text1);add(text2);add(button1);add(button2);add(button3);add(user);add(admin);}Toolkit tk=Toolkit.getDefaultToolkit();Image a=tk.createImage(path);public void paint(Graphics g){g.drawImage(a, 0, 0, getWidth(), getHeight(), this);paintComponents(g);}}public class LoadTest{final JFrame jFrame = new JFrame("登陆界面");Load ld=new Load();String[] Aid=new String[4];//三个管理员String[] Aname=new String[4];String[] Apassword=new String[4];String[] Uid=new String[1000];//最多一千个用户String[] Uname=new String[1000];String[] Upassword=new String[1000];public static String Aname1=null;public static String Aid1=null;public static String Uname1=null;public static String Uid1=null;int AidCount=0,UidCount=0;Connection con=null;Statement stmt=null;ResultSet rs1=null,rs2=null;public LoadTest(){jFrame.setContentPane(ld);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();con=DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Guestb ook","wanghuidong","12345678");stmt=con.createStatement();rs1=stmt.executeQuery("select * from Admin");for(int i=1;i<=3&&rs1.next();i++)//管理员{Aid[i]=rs1.getString(1);Aname[i]=rs1.getString(2);Apassword[i]=rs1.getString(3);System.out.println("管理员ID:"+Aid[i]+"\t管理员姓名:"+Aname[i]+"\t密码:"+Apassword[i]);AidCount++;}rs2=stmt.executeQuery("select * from User1");for(int i=1;rs2.next();i++){Uid[i]=rs2.getString(1);Uname[i]=rs2.getString(2);Upassword[i]=rs2.getString(3);System.out.println("用户ID:"+Uid[i]+"\t用户姓名:"+Uname[i]+"\t密码:"+Upassword[i]);UidCount++;}}catch(Exception e){e.printStackTrace();}finally{try {if (rs1 != null)rs1.close();if (rs2 != null)rs2.close();if (stmt != null)stmt.close();if (con != null)con.close();} catch (Exception e) {e.printStackTrace();}}System.out.println("行数:"+UidCount);for(int i=1;i<=AidCount;i++)System.out.println("管理员ID:"+Aid[i]+"\t用户姓名:"+Aname[i]+"\t密码:"+Apassword[i]);for(int i=1;i<=UidCount;i++)System.out.println("用户ID:"+Uid[i]+"\t用户姓名:"+Uname[i]+"\t密码:"+Upassword[i]);ld.button1.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {char []pwd=ld.text2.getPassword();String str=ld.bg.getSelection().getActionCommand();//获取选中的单选按钮的标签if(str=="管理员"){int flag=0;for(int i=1;i<=AidCount;i++) //三次循环找到{if(Aname[i].trim().equals(ld.text1.getText()) && Apassword[i].trim().equals(String.valueOf(pwd))){ flag=1;JOptionPane.showMessageDialog(ld.button1, "登陆成功."+Aname[i]+",欢迎您!", "提示", RMATION_MESSAGE);LoadTest.Aid1=Aid[i]; LoadTest.Aname1=Aname[i];new adminInterfaceTest().frame.setVisible(true);jFrame.dispose(); break;}}if(flag==0){JOptionPane.showMessageDialog(ld.button1, "错误", "提示", JOptionPane.ERROR_MESSAGE);ld.text1.setText("");ld.text2.setText("");}}if(str=="用户"){ int flag=0;for(int i=1;i<=UidCount;i++)//循环找到{if(Uname[i].trim().equals(ld.text1.getT ext())&&Upassword[i].trim().equals(String.valueOf(pwd))){ flag=1;String way="initial"; int id=1;userInterface ui=new userInterface(way,id);JOptionPane.showMessageDialog(ld.button1, "登陆成功."+Uname[i]+",欢迎您!", "提示", RMATION_MESSAGE);LoadTest.Uid1=Uid[i].trim(); LoadTest.Uname1=Uname[i].trim();new userInterfaceTest().frame.setVisible(true);jFrame.dispose(); break;}}//没有找到if(flag==0){JOptionPane.showMessageDialog(ld.button1, "错误", "提示", JOptionPane.ERROR_MESSAGE);ld.text1.setText("");ld.text2.setText("");}}}});ld.button1.setMnemonic(KeyEvent.VK_ENTER);//设置快捷键alt+回车ld.button2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){new registerTest();jFrame.dispose();}});ld.button3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){System.exit(-1);}});Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();jFrame.setBounds(((int)dimension.getWidth()/ 2 - 250) , ((int)dimension.getHeight()/ 2 -175) ,500, 350);jFrame.setResizable(false);jFrame.setVisible(true);jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public static void main(String[] args){new LoadTest();}}用户界面import java.awt.BorderLayout;import java.awt.Color;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import .URL;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.Date;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JComboBox;//下拉列表框import javax.swing.JScrollPane;import javax.swing.JTable;import javax.swing.table.DefaultTableModel;class userInterface extends JPanel {JPanel jp=new JPanel();JButton new1,refresh,change;JScrollPane scrollpane;public static JTable table;JComboBox combox1,combox2;JLabel label1,label2,label3,label4,label5;URL path=userInterface.class.getResource("a7.jpg");Connection con=null;Statement stmt=null;ResultSet rs1=null,rs2=null,rs3=null,rs4=null;int UidCount=0;String way,id;//传参给构造器,执行不同的sql语句public static String aid;String[] columnNames={"用户ID","用户名","年龄","性别","留言","留言时间","回复","回复时间"};String[] Uid=new String[1001]; String[] Uname=new String[1001]; String[] Upassword=new String[1001];String[] Uage=new String[1001]; String[] Usex=new String[1001];String[]Umessage=new String[1001];String[] Utime=new String[1001]; String[] Amessage=new String[1001]; String[] Atime=new String[1001];//SQL获得数据public userInterface(String way,int id){System.out.println("way="+way+"\tid="+id);// BorderLayout bl=new BorderLayout();//setLayout(bl);setLayout(null);new1=new JButton("新留言"); new1.setBounds(390,550,90,30);refresh=new JButton("刷新"); refresh.setBounds(530,550,90,30);change=new JButton("修改个人信息"); change.setBounds(200,550,130,30);label5=new JLabel("用户ID:"+LoadTest.Uid1+" 姓名:"+LoadTest.Uname1); label5.setBounds(570,0,250,30);label1=new JLabel("查看留言,请选择方式"); label1.setBounds(50,0,250,30);label2=new JLabel("年龄"); label2.setBounds(250,0,60,30);label3=new JLabel("性别"); label3.setBounds(390,0,60,30);label4=new JLabel(""+new Date()); label4.setBounds(820,0,300,30);combox1=new JComboBox(); combox1.setBounds(300,0,50,30);combox1.addItem("");for(int i=10;i<40;i++){combox1.addItem(i);}combox2=new JComboBox(); combox2.setBounds(450,0,45,30);combox2.addItem(""); combox2.addItem("男"); combox2.addItem("女");add(refresh);add(new1); add(label5); add(change);add(label1); add(label2); add(label3); add(label4); add(combox1); add(combox2);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();con=DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Guestb ook","wanghuidong","12345678");stmt=con.createStatement();if(way=="initial" ){ rs1=stmt.executeQuery("select * from Uview1 order by Utime DESC");}if(way=="boy"){ rs1=stmt.executeQuery("select * from Uview1 where Usex='男' order by Utime DESC");}if(way=="girl"){ rs1=stmt.executeQuery("select * from Uview1 where Usex='女' order by Utime DESC");}if(way=="age"){ rs1=stmt.executeQuery("select * from Uview1 where Uage='"+id+"' order by Utime DESC");}for(int i=0;rs1.next();i++)//游标一定要移动{Uid[i]=rs1.getString(1);Uname[i]=rs1.getString(2);Uage[i]=rs1.getString(3);Usex[i]=rs1.getString(4);Umessage[i]=rs1.getString(5);Utime[i]=rs1.getDate(6)+" "+rs1.getTime(6);Amessage[i]=rs1.getString(7);Atime[i]=rs1.getDate(8)+" "+rs1.getTime(8);UidCount++;} System.out.println("UidCount="+UidCount);for(int i=0;i<10;i++)System.out.println(Uid[i]+"\t"+Uname[i]+"\t"+Uage[i]+"\t"+Umessage[i]);}catch(Exception e){e.printStackTrace();}finally{try {if (rs1 != null)rs1.close();if (rs2 != null)rs2.close();if (stmt != null)stmt.close();if (con != null)con.close();} catch (Exception e) {e.printStackTrace();}}for(int i=0;i<5;i++)System.out.println(Uid[i]+"\t"+Uname[i]+"\t"+Uage[i]+"\t"+Umessage[i]);//DefaultTableModel dtm=new DefaultTableModel();// table.setModel(dtm);// dtm.addRow(data);Object[][] data=new Object[UidCount][8];//对象二维数组for(int i=0;i<UidCount;i++)//行数{data[i][0]=Uid[i]; data[i][1]=Uname[i]; data[i][2]=Uage[i];data[i][3]=Usex[i]; data[i][4]=Umessage[i]; data[i][5]=Utime[i];data[i][6]=Amessage[i]; data[i][7]=Atime[i];};table=new JTable(data,columnNames);//构建表table.setRowHeight(45);table.setGridColor(Color.green);table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);//table.setEnabled(false);//table.updateUI();//表格更新scrollpane=new JScrollPane(table);if(UidCount>=10)scrollpane.setBounds(0, 30, 1010, 470);elsescrollpane.setBounds(0, 30, 1010, (UidCount*45)+20);add(scrollpane);}Image image=Toolkit.getDefaultToolkit().createImage(path);public void paint(Graphics g){g.drawImage(image,0,0,getWidth(),getHeight(),this);paintComponents(g);}}public class userInterfaceTest {JFrame frame=new JFrame("留言本");JMenuBar menubar=new JMenuBar();JMenu file=new JMenu("文件");JMenuItem exit=new JMenuItem("退出");JMenu help=new JMenu("帮助");JMenuItem about=new JMenuItem("关于");public static String way="initial";//静态变量,初始化后不再恢复原值public static int id=1;userInterface ui=new userInterface(way,id);public userInterfaceTest(){frame.setContentPane(ui);frame.setJMenuBar(menubar);menubar.add(file); menubar.add(help);file.add(exit); help.add(about);exit.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){System.exit(-1);}});about.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubnew AboutDialog(frame);}});ui.new1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubuserInterface.aid=JOptionPane.showInputDialog(ui.new1, userInterface.aid,"请输入入管理员ID号(1、2或3):",JOptionPane.QUESTION_MESSAGE);if(userInterface.aid!=""&&userInterface.aid!=null)//内容不为空new Newmessage();}});ui.refresh.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){way="initial";//静态变量,初始化后不再恢复原值id=1;//new userInterface(way,id);new userInterfaceTest();//新产生一个实例frame.dispose();//释放当前窗口,相当于刷新}});ui.change.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){new userChangeTest();}});box1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String age=((JComboBox)e.getSource()).getSelectedItem().toString();if(age!=""){way="age";id=Integer.parseInt(age);new userInterfaceTest();//新产生一个实例frame.dispose();}else{way="initial";//静态变量,初始化后不再恢复原值id=1;//new userInterface(way,id);new userInterfaceTest();//新产生一个实例frame.dispose();//释放当前窗口,相当于刷新}}});box2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String sex=((JComboBox)e.getSource()).getSelectedItem().toString();//等价于String sex=box2.getSelectedItem().toString();if(sex=="男"){way="boy";//静态变量,初始化后不再恢复原值id=1;//new userInterface(way,id);new userInterfaceTest();//新产生一个实例frame.dispose();//释放当前窗口,相当于刷新}else if(sex=="女"){way="girl";//静态变量,初始化后不再恢复原值id=1;//new userInterface(way,id);new userInterfaceTest();//新产生一个实例frame.dispose();//释放当前窗口,相当于刷新}else{way="initial";//静态变量,初始化后不再恢复原值id=1;//new userInterface(way,id);new userInterfaceTest();//新产生一个实例frame.dispose();//释放当前窗口,相当于刷新}}});frame.setSize(1024, 700);frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);frame.setLocationRelativeTo(null);//frame.setResizable(false);frame.setVisible(true);}public static void main(String[] args){new userInterfaceTest();}}用户留言框import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.sql.Connection;import java.util.Date;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import javax.swing.JButton;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPopupMenu;import javax.swing.JTextArea;import javax.swing.JFrame;public class Newmessage{JFrame jf=new JFrame("留言");JPopupMenu menu=new JPopupMenu();JMenuItem all=new JMenuItem("全选");JMenuItem copy=new JMenuItem("复制"); JMenuItem cut=new JMenuItem("剪切");JMenuItem paste=new JMenuItem("粘贴");final JTextArea text=new JTextArea(30,30);JButton submit=new JButton("提交");JButton cancel=new JButton("取消");int AidCount=0,UidCount1=0,UidCount2=0;Connection con=null;Statement stmt=null;ResultSet rs1=null,rs2=null;String Umessage,Umessage1,Utime;BorderLayout bl=new BorderLayout();public Newmessage(){jf.getContentPane().setLayout(bl);jf.getContentPane().add(submit,BorderLayout.WEST);jf.getContentPane().add(cancel,BorderLayout.EAST);jf.getContentPane().add(text,BorderLayout.CENTER);menu.add(all);menu.add(copy);menu.add(cut);menu.add(paste);text.setComponentPopupMenu(menu);text.setLineWrap(true);all.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){text.selectAll();}});cut.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){text.cut();}});copy.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){text.copy();}});paste.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){text.paste();}});submit.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){Umessage=new String(text.getText());System.out.println("Umessage="+Umessage);try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();con=DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Guestb ook","wanghuidong","12345678");Date time=new Date();//util Datejava.sql.Date sqltime=new java.sql.Date(time.getTime());//sql DateString Aid=userInterface.aid.trim();String sql = "insert into UA values(?,?,?,?)";//UAid由数据库自动增加PreparedStatement pstmt = con.prepareStatement(sql);//预执行语句// pstmt.setInt(1,UidCount1);pstmt.setString(1,Aid);pstmt.setString(2, LoadTest.Uid1);pstmt.setString(3, Umessage);pstmt.setDate(4, sqltime);int count=pstmt.executeUpdate();//不带参数System.out.println(count);if(count==1){JOptionPane.showMessageDialog(submit, "留言成功", "提示", RMATION_MESSAGE);userInterface.table.updateUI();//新产生一个实例jf.dispose();}else{JOptionPane.showMessageDialog(submit, "留言失败", "提示", JOptionPane.ERROR_MESSAGE);}}catch(Exception e1){e1.printStackTrace();}finally{try {if (rs2 != null)rs2.close();if (stmt != null)stmt.close();if (con != null)con.close();} catch (Exception e1) {e1.printStackTrace();}}jf.dispose();}});cancel.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){jf.dispose();}});jf.setVisible(true);jf.setSize(500,300);jf.setLocationRelativeTo(null);}}用户注册表import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import .URL;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import java.text.DateFormat;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.JRadioButton;import javax.swing.ButtonGroup;import javax.swing.WindowConstants;@SuppressWarnings("serial")class register extends JPanel{JLabel label1,label2,label3,label4,label5,label6,label7,label8;public static JTextField Uname,Upassword,age,sex,qq,phone,email;static JTextArea adress;JRadioButton male,female;ButtonGroup bg;public static JButton submit,cancel;Font f=new Font("黑体",Font.BOLD,16);URL path=register.class.getResource("a3.jpg");public register(){setLayout(null);label1=new JLabel("用户名"); label1.setBounds(120,30,60,25); label1.setFont(f); label1.setForeground(Color.WHITE);label2=new JLabel("密码"); label2.setBounds(120,70,60,25); label2.setFont(f); label2.setForeground(Color.WHITE);label3=new JLabel("年龄"); label3.setBounds(120,110,60,25); label3.setFont(f); label3.setForeground(Color.WHITE);label4=new JLabel("性别"); label4.setBounds(120,150,60,25); label4.setFont(f); label4.setForeground(Color.WHITE);label5=new JLabel("qq号码"); label5.setBounds(120,230,90,25); label5.setFont(f); label5.setForeground(Color.WHITE);label6=new JLabel("手机号"); label6.setBounds(120,190,120,25); label6.setFont(f); label6.setForeground(Color.WHITE);label7=new JLabel("邮箱"); label7.setBounds(120,270,60,25); label7.setFont(f); label7.setForeground(Color.WHITE);label8=new JLabel("地址"); label8.setBounds(120,310,60,50); label8.setFont(f); label8.setForeground(Color.WHITE);Uname=new JTextField(); Uname.setBounds(200,30,150,25);age=new JTextField(); age.setBounds(200,110,60,25);Upassword=new JTextField(); Upassword.setBounds(200,70,150,25);sex=new JTextField("男"); sex.setBounds(200,150,60,25);male=new JRadioButton("男",true); male.setBounds(280,150,40,25);male.setActionCommand("男");female=new JRadioButton("女",false); female.setBounds(330,150,40,25);female.setActionCommand("女");bg=new ButtonGroup();bg.add(male); bg.add(female);qq=new JTextField(); qq.setBounds(200, 190, 150, 25);phone=new JTextField(); phone.setBounds(200,230,150,25);email=new JTextField(); email.setBounds(200,270,250,25);adress=new JTextArea(); adress.setBounds(200,310,400,50);submit=new JButton("提交"); submit.setBounds(150,400,60,30);cancel=new JButton("取消"); cancel.setBounds(250,400,60,30);add(label1);add(Uname); add(label2);add(age); add(Upassword);add(label3);add(sex);add(male);add(female); add(label8);add(label4);add(qq); add(label5);add(phone);add(label6);add(email); add(label7);add(adress);add(submit); add(cancel);male.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String str=bg.getSelection().getActionCommand();sex.setText(str);}});female.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String str=bg.getSelection().getActionCommand();sex.setText(str);}});}Toolkit tk=Toolkit.getDefaultToolkit();Image image=tk.createImage(path);public void paint(Graphics g){g.drawImage(image, 0, 0,getWidth(), getHeight(), this);paintComponents(g);}}public class registerTest {JFrame frame=new JFrame("用户信息登记表");register rg=new register();registerTest(){frame.setContentPane(rg);register.cancel.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){frame.dispose();new LoadTest();}});register.submit.addActionListener(new Submit_ActionListener(this));frame.setSize(750,500);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);frame.setVisible(true);}public static void main(String[] args){new registerTest();}}class Submit_ActionListener implements ActionListener{private registerT est adaptee;Connection con;PreparedStatement pstmt;Statement stmt;ResultSet rs=null;int UidCount=0;public Submit_ActionListener(registerTest adaptee){this.adaptee=adaptee;}public void actionPerformed(ActionEvent e){//提交动作try{Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();con=DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Guestbook", "wanghuidong", "12345678");stmt=con.createStatement();rs=stmt.executeQuery("select Uid from User1");while(rs.next()){UidCount++;}String count=String.valueOf(UidCount+1);//等价于String count=UidCount+"";java.util.Date date=new java.util.Date();//产生时间// DateFormat df=DateFormat.getDateTimeInstance();//格式转换工具// String sdate=df.format(date);//时间转换为字符串// System.out.println(sdate);java.sql.Date sqldate=new java.sql.Date(date.getTime());String sql="insert into User1 values(?,?,?,?,?,?,?,?,?,?)";pstmt=con.prepareStatement(sql);//预编译pstmt.setString(1, count);pstmt.setString(2, register.Uname.getT ext());pstmt.setString(3, register.Upassword.getText());pstmt.setString(4, register.sex.getText());pstmt.setInt(5, Integer.parseInt(register.age.getText()));pstmt.setString(6, register.phone.getText());pstmt.setString(7, register.qq.getText());pstmt.setString(8, register.email.getText());pstmt.setString(9, register.adress.getText());pstmt.setDate(10, sqldate);int rc=pstmt.executeUpdate();if(rc==1){JOptionPane.showMessageDialog(register.submit, "注册成功,请记住你的用户名和密码!用户名:"+register.Uname.getText()+"密码:"+register.Upassword.getT ext(), "提示", RMATION_MESSAGE);//userInterface.table.updateUI();//新产生一个实例adaptee.frame.dispose();new LoadTest();}else{JOptionPane.showMessageDialog(register.submit, "注册失败", "提示", JOptionPane.ERROR_MESSAGE);adaptee.frame.dispose();new LoadTest();}}catch(Exception e1){e1.printStackTrace();}finally{try {if (rs!= null)rs.close();if (stmt != null)stmt.close();if (con != null)con.close();}catch (Exception e2) {e2.printStackTrace();}}}}用户信息修改表import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import .URL;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import java.text.DateFormat;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.JRadioButton;import javax.swing.ButtonGroup;import javax.swing.WindowConstants;@SuppressWarnings("serial")class userChange extends JPanel{JLabel label1,label2,label3,label4,label5,label6,label7,label8;public static JTextField Uname,Upassword,age,sex,qq,phone,email;static JTextArea adress;JRadioButton male,female;ButtonGroup bg;public static JButton commit,cancel;Font f=new Font("黑体",Font.BOLD,16);URL path=userInterface.class.getResource("a7.jpg");public userChange(){setLayout(null);label1=new JLabel("用户名"); label1.setBounds(120,30,60,25); label1.setFont(f); label1.setForeground(Color.WHITE);label2=new JLabel("密码"); label2.setBounds(120,70,60,25); label2.setFont(f); label2.setForeground(Color.WHITE);。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
</form>
</body>
</html>
<?php
include(&uot;lianjie.php&uot;);
$sl=&uot;insert into message(id,user,e-mail,phone,address,title,content)
if(form1.sname.value==&uot;&uot;){
alert(&uot;请填写用户名,不能为空!&uot;);
form1.sname.focus();
return false;
}
if(form1.title.value==&uot;&填写用户名,不能为空!&uot;);
form1.title.focus();
return false;
}
if(form1.content.value==&uot;&uot;){
alert(&uot;请填写用户名,不能为空!&uot;);
form1.content.focus();
return false;
标&nbsp;&nbsp;题:<input type=&uot;text&uot; name=&uot;title&uot;><br>
留&nbsp;&nbsp;言:<textarea name=&uot;content&uot; rows=&uot;10&uot; cols=&uot;50&uot; wrap=&uot;on&uot;></textarea><br> <input type=&uot;submit&uot; name=&uot;submit&uot; value=&uot;发表&uot;>
}
}
</SCRIPT>
<html>
<body>
<form name=&uot;form1&uot; action=&uot;add.php&uot; method=&uot;post&uot; onsubmit=&uot;return CheckPost()&uot;> 用户名:<input type=&uot;text&uot; name=&uot;sname&uot;><br>
nt)values('','$_POST[sname]','$_POST[title]','$_POST[content]')&uot;; mysl_uery($sl,$conn);
?>
<SCRIPT language=javascript>
function CheckPost(){
values('',&uot;$_POST[&uot;user&uot;],&uot;$_POST[&uot;phone&uot;],&uot;$_POST[&uot;address&uot;],&uot;$_PO