利用JSP+JDBC实现网站的留言功能

每一次相遇都是一定的缘分,先赞后看,养成习惯,期待你点赞与关注

创建用户留言模块,页面有登陆,注册,查看留言列表,查看详细留言,发布留言,安全退出等功能。先创建数据库,数据库中至少要有users和words两个表,其他可以自行设计。
CREATE TABLE users (
UserID bigint(20) NOT NULL auto_increment,
UserName varchar(20) default NULL,
UserPassword varchar(20) default NULL,
PRIMARY KEY (UserID)
) ;
CREATE TABLE words (
WordsID bigint(20) NOT NULL auto_increment,
WordsTitle varchar(100) default NULL,
WordsContent text,
WordsTime datetime default ‘0000-00-00 00:00:00’,
UserID bigint(20) NOT NULL default ‘0’,
PRIMARY KEY (WordsID)
) ;
界面可以自行设计

由于代码较多,这里仅列出主要代码,完整代码可以在GitHub上下载GIthub完整代码

实现效果:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

db.sql

drop database ch11;
create database ch11;
use ch11;
CREATE TABLE users (
  UserID bigint(20) NOT NULL auto_increment,
  UserName varchar(20) default NULL,
  UserPassword varchar(20) default NULL,
  PRIMARY KEY (UserID)
) ;
CREATE TABLE words (
  WordsID bigint(20) NOT NULL auto_increment,
  WordsTitle varchar(100) default NULL,
  WordsContent text,
  WordsTime datetime default '0000-00-00 00:00:00',
  UserID bigint(20) NOT NULL default '0',
  PRIMARY KEY  (WordsID)
 ) ;

login.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
		<title>用户登录</title>
		<script language="javascript">
		//判断输入的用户名和密码是否合法
		function check()
		{
			if(login_form.UserName.value == "")
			{//判断用户名是否为空
				alert("用户名不能为空!");
				login_form.UserName.focus();
			}
			else if(login_form.UserPassword.value == "")
			{//判断密码是否为空
				alert("用户密码不能为空!");
				login_form.UserPassword.focus();
			}
			else
			{
				//设置跳转目的页面
				login_form.action="login_check.jsp";
				login_form.target="_top"
			}
		}
		</script>
	</head>
	<body>
		<p align="center"><font size="5">用户登录</font></p>
		<div align="center">
		<form name="login_form" method="post" onSubmit="check()" >
		<table width="60%" border="0">
			<tr>
			<td width="50%" align="right">请输入用户名:</td>
			<td width="50%" align="left"><input type="text" name="UserName"></td>
			</tr>
			<tr>
			<td width="50%" align="right">请输入密码:</td>
			<td width="50%" align="left"><input type="password" name="UserPassword"></td>
			</tr>	
			 
			<tr>
			<td width="50%" align="center" colspan="2">
			<br>
			<input type="submit" name="sub" value="登录">&nbsp;&nbsp;
			<input type="reset" name="res" value="重填">
			<br><br>
			<a href=register.jsp>注册用户</a>
			</td>			
			</tr>
		</table>
		</form>
		</div>
	</body>
</html>

register.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
		<title>新用户注册</title>
		<script language="javascript">
		//判断输入的用户名和密码是否合法
		function check()
		{
			if(reg_form.UserName.value == "")
			{//判断用户名是否为空
				alert("用户名不能为空!");
				reg_form.UserName.focus();
			}
			else if(reg_form.UserPassword.value == "")
			{//判断密码是否为空
				alert("用户密码不能为空!");
				reg_form.UserPassword.focus();
			}
			else if(reg_form.UserPassword.value != reg_form.confirm_UserPassword.value)
			{//判断两次输入的密码是否一致
				alert("两次输入的密码不一致!");
				reg_form.UserPassword.focus();				
			}
			else
			{
				//设置跳转目的页面
				reg_form.action="user_reg_save.jsp";
			}
		}
		</script>
	</head>
	<body>
		<p align="center"><font size="5">新用户注册</font></p>
		<div align="center">
		<form name="reg_form" method="post" onSubmit="check()">
		<table width="60%" border="0">
			<tr>
			<td width="50%" align="right">请输入用户名:</td>
			<td width="50%" align="left"><input type="text" name="UserName"></td>
			</tr>
			<tr>
			<td width="50%" align="right">请输入密码:</td>
			<td width="50%" align="left"><input type="password" name="UserPassword"></td>
			</tr>
			<tr>
			<td width="50%" align="right">请输入确认密码:</td>
			<td width="50%" align="left"><input type="password" name="confirm_UserPassword"></td>
			</tr>
			<tr>
			<td width="50%" align="center" colspan="2">
			<br>
			<input type="submit" name="sub" value="注册">&nbsp;&nbsp;
			<input type="reset" name="res" value="重填">
			</td>			
			</tr>
		</table>
		</form>
		</div>
	</body>
</html>

user_reg_save.jsp

<%@ page contentType="text/html; charset=gb2312" language="java"%>
<%@ page  import="java.sql.*" %>
<jsp:useBean class="com.ch11.users" id="users" scope="page"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
		<title>保存注册用户资料</title>
	</head>
	<body>
	<%
	
		//获取注册的用户名
		String UserName = request.getParameter("UserName");
		//设置users中的UserName变量
		users.setUserName(UserName);
		//判断该用户名是否存在
		if(users.is_exist())
		{
	%>
			<h2 align="center">该用户名已经存在</h2>
			<center><input type="button" name="goback" value="返回" onClick="javascript:window.history.go(-1)"></center>
	<%
		}
		else
		{
			//获取注册的密码
			String UserPassword = request.getParameter("UserPassword");
			//设置users中的UserPassword变量
			users.setUserPassword(UserPassword);
			//判断是否成功保存注册资料
			if(users.add_user())
			{
	%>
				<h2 align="center">注册成功</h2>
				<center>
				<a href="login.jsp" target="_self">现在登录</a>
				</center>
	<%
			}
			else
			{
				out.println("<h1>注册失败,请稍后重试</h1>");
			}		
		}
	%>	
	</body>
</html>

db.java

package com.ch11;
import java.sql.*;

public class db
{ 
	//数据库用户名
	String userName="root";
	//数据库密码
	String userPassword="123";
    //数据库的URL,包括连接数据库所使用的编码格式
	String url="jdbc:mysql://localhost:3306/ch11?useUnicode=true&characterEncoding=gb2312";
   	//定义一个连接对象
	Connection dbcon;   
   	//错误信息串
	Statement stmt;
	ResultSet rs;    	
    /**
	*@初始化操作,包括给变量赋初值和连接数据库
	*/
   	public db()
   	{
   		//初始化参数值
   		stmt = null;
		rs = null;	
		//连接数据库
   	try
		{			
			//声明所用的类包
			Class.forName("org.gjt.mm.mysql.Driver");
			//获得数据库的连接对象
			dbcon= DriverManager.getConnection(url,userName,userPassword);	
		}
		catch(SQLException ex)
		{
			//打印出异常信息
			System.out.println(ex.toString());		
		}
		catch(ClassNotFoundException ex)
		{
			//打印出异常信息
			System.out.println(ex.toString());	
		}
   	}   	
   	/**
	*@对数据库执行sql执行语句,主要是插入和更新操作,返回一个布尔值变量
	*/
	public boolean exeSql(String strSql)
	{
		try
		{
   			stmt=dbcon.createStatement();
			stmt.executeUpdate(strSql);
			return true;            
		}
		catch(Exception ex)
		{
			//打印出异常信息
			System.out.println(ex.toString());
			return false;
		}			
	}	
	/**
	*@对数据库执行sql查询语句,返回一个ResultSet类型的对象
	*/
    public ResultSet exeSqlQuery(String strSql)
	{		
		try
		{
   			stmt=dbcon.createStatement();
			rs =stmt.executeQuery(strSql);			            
		}
		catch(Exception ex)
		{
			//打印出异常信息
			System.out.println(ex.toString());
			rs = null;
		}		
		return rs;
	}  
}


users.java

package com.ch11;
import java.util.*;
import java.sql.*;
import java.text.*;

public class users extends db
{
	//定义成员变量
	private int UserID;
    private String UserName;
    private String UserPassword;       
    //执行各种操作的sql语句
    private String strSql;
   
    //构造函数,初始化成员变量
    public users()
    {       
        UserID=0;
        UserName="";
        UserPassword="";         
   		strSql="";   
   }   
   /**
	*@添加用户记录
	*/
   public boolean add_user()
   {
        
        strSql="insert into users ";
        strSql=strSql + "(";
        strSql=strSql + "UserName,";       
        strSql=strSql + "UserPassword";
        strSql=strSql + ") ";
		strSql=strSql + "values(";
		strSql=strSql + "'" + UserName + "',";
		strSql=strSql + "'" + UserPassword + "'";		
		strSql=strSql + ")";
		boolean isAdd = super.exeSql(strSql);
		return isAdd;
   } 
   /**
    *@判断用户名是否存在 by UserName
    */
   public boolean is_exist()
   {
    	strSql="select * from `users` where UserName = '"+UserName+"'";
        ResultSet rs = null;
        boolean isExist = false;              
        try
		{
   		 	rs = super.exeSqlQuery(strSql);
   		 	while(rs.next())
			{
				isExist = true;	
			}
		}
		catch(Exception ex)
		{
			System.out.println(ex.toString()); 			
		}
		return isExist;
   }   
    /**
    *@判断用户名和密码是否正确
    */
   public boolean user_valid()
   {
    	strSql="select * from `users` where";
    	strSql=strSql + " UserName = '"+UserName+"'";
    	strSql=strSql + " and UserPassword = '"+UserPassword+"'";
        ResultSet rs = null;
        boolean isValid = false;              
        try
		{
   		 	rs = super.exeSqlQuery(strSql);
   		 	while(rs.next())
			{
				this.UserID = rs.getInt("UserID");				
				isValid = true;	
			}
		}
		catch(Exception ex)
		{
			System.out.println(ex.toString()); 			
		}
		return isValid;
   }    
   /**
    *@获取某个用户的信息 by UserID
    */
   public boolean init()
   {
    	strSql="select * from `users` where UserID=";
        strSql=strSql +UserID;        
        try
		{
   			ResultSet rs = super.exeSqlQuery(strSql);
            if (rs.next())
            {
                this.UserID=rs.getInt("UserID");
                this.UserName=rs.getString("UserName");
                this.UserPassword=rs.getString("UserPassword");              
                
                return true;
            }
            else
            {
               return false;
            }
		}
		catch(Exception ex)
		{
			System.out.println(ex.toString());            
            return false;
		}
   }   
   /**
    *@设置成员变量UserID的值
    */
   public void setUserID(int UserID)
   {
   		this.UserID = UserID;	
   }   
   /**
    *@获取成员变量UserID的值
    */
   public int getUserID()
   {
   		return this.UserID;	
   }   
    /**
    *@设置成员变量UserName的值
    */
   public void setUserName(String UserName)
   {
   		this.UserName = UserName;	
   }   
   /**
    *@获取成员变量UserName的值
    */
   public String getUserName()
   {
   		return this.UserName;	
   }   
    /**
    *@设置成员变量UserPassword的值
    */
   public void setUserPassword(String UserPassword)
   {
   		this.UserPassword = UserPassword;	
   }   
   /**
    *@获取成员变量UserPassword的值
    */
   public String getUserPassword()
   {
   		return this.UserPassword;	
   }   
}

words.java

package com.ch11;
import java.util.*;
import java.sql.*;
import java.text.*;
public class words extends db
{
	//定义成员变量
	private int WordsID;
    private String WordsTitle;
    private String WordsContent;    
    private String WordsTime; 
    private int UserID;      
    //执行各种操作的sql语句
    private String strSql;
    //时间格式
    private SimpleDateFormat timeFormatter;
    
    //构造函数,初始化成员变量
    public words()
    {       
        WordsID=0;
        WordsTitle="";
        WordsContent=""; 
        UserID=0;
   		timeFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
   		WordsTime=timeFormatter.format(new java.util.Date());
   		strSql="";   
   }   
   /**
	*@添加留言记录
	*/
   public boolean add_words()
   {
        
        strSql="insert into words ";
        strSql=strSql + "(";
        strSql=strSql + "WordsTitle,";       
        strSql=strSql + "WordsContent,";
        strSql=strSql + "WordsTime,";
        strSql=strSql + "UserID";
        strSql=strSql + ") ";
		strSql=strSql + "values(";
		strSql=strSql + "'" + WordsTitle + "',";
		strSql=strSql + "'" + WordsContent + "',";
		strSql=strSql + "'" + WordsTime + "',";
		strSql=strSql + "'" + UserID + "'";
		strSql=strSql + ")";
		boolean isAdd = super.exeSql(strSql);
		return isAdd;
   }     
   /**
    *@获取某条留言 by WordsID
    */
   public boolean init()
   {
    	strSql="select * from `words` where WordsID=";
        strSql=strSql + WordsID;         
        try
		{
   			ResultSet rs = super.exeSqlQuery(strSql);
            if (rs.next())
            {
                //获取留言内容
                this.WordsID=rs.getInt("WordsID");
                this.WordsTitle=rs.getString("WordsTitle");
                this.WordsContent=rs.getString("WordsContent");
                this.WordsTime=rs.getString("WordsTime");                
                this.UserID=rs.getInt("UserID");                
                return true;
            }
            else
            {
               return false;
            }
		}
		catch(Exception ex)
		{
			System.out.println(ex.toString()); 
            return false;
		}
   }   
   /**
    *@显示所有留言
    */
   public ResultSet show_all_words()
   {
    	strSql="select * from `words`";
        ResultSet rs = null;
              
        try
		{
   		 	rs = super.exeSqlQuery(strSql); 
		}
		catch(Exception ex)
		{
			System.out.println(ex.toString()); 
		}
		return rs;
   }   
   /**
    *@设置成员变量WordsID的值
    */
   public void setWordsID(int WordsID)
   {
   		this.WordsID = WordsID;	
   }   
   /**
    *@获取成员变量WordsID的值
    */
   public int getWordsID()
   {
   		return this.WordsID;	
   }   
    /**
    *@设置成员变量WordsTitle的值
    */
   public void setWordsTitle(String WordsTitle)
   {
   		this.WordsTitle = WordsTitle;	
   }   
   /**
    *@获取成员变量WordsTitle的值
    */
   public String getWordsTitle()
   {
   		return this.WordsTitle;	
   }   
    /**
    *@设置成员变量WordsContent的值
    */
   public void setWordsContent(String WordsContent)
   {
   		this.WordsContent = WordsContent;	
   }   
   /**
    *@获取成员变量WordsContent的值
    */
   public String getWordsContent()
   {
   		return this.WordsContent;	
   }   
   /**
    *@设置成员变量WordsTime的值
    */
   public void setWordsTime(String WordsTime)
   {
   		this.WordsTime = WordsTime;	
   }   
   /**
    *@获取成员变量WordsTime的值
    */
   public String getWordsTime()
   {
   		return this.WordsTime;	
   }   
   /**
    *@设置成员变量UserID的值
    */
   public void setUserID(int UserID)
   {
   		this.UserID = UserID;	
   }   
   /**
    *@获取成员变量UserID的值
    */
   public int getUserID()
   {
   		return this.UserID;	
   }
}


add_words_save.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" %>
<%@ page  import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
		<title>保存留言</title>
		<jsp:useBean class="com.ch11.words" id="words" scope="page"/>
	</head>
	<body>
	<%
		//获取session中UserID变量的值
		String str_UserID = application.getAttribute("UserID").toString();
		//设置words中UserID变量的值
		words.setUserID(Integer.parseInt(str_UserID));
		//获取留言标题
		String WordsTitle = request.getParameter("WordsTitle");
		//编码转换
		WordsTitle=new String(WordsTitle.getBytes("iso-8859-1"));
		//设置words中WordsTitle变量的值
		words.setWordsTitle(WordsTitle);
		//获取留言内容
		String WordsContent = request.getParameter("WordsContent");
		//编码转换
		WordsContent=new String(WordsContent.getBytes("iso-8859-1"));
		//设置words中WordsContent变量的值
		words.setWordsContent(WordsContent);
		//判断保存留言是否成功
		if(words.add_words())
		{
		//out.println("<h2 align=center>留言保存成功</h2>");
		response.sendRedirect("list.jsp");
		}
		else
		{
	%>	
			<h2 align="center">留言保存失败</h2>
			<center>
			<input type="button" name="goback" value="返回" onClick="javascript:window.history.go(-1)">
			</center>
	<%
		}
	%>
	</body>
</html>

只列出部分代码,完整代码请移步GIthub自行下载调试——> 留言模块完整代码链接期待给个小星星哦

©️2020 CSDN 皮肤主题: Age of Ai 设计师:mmellie 返回首页