JspServlet留言板实践源码.docx
- 文档编号:10770165
- 上传时间:2023-02-22
- 格式:DOCX
- 页数:29
- 大小:25.48KB
JspServlet留言板实践源码.docx
《JspServlet留言板实践源码.docx》由会员分享,可在线阅读,更多相关《JspServlet留言板实践源码.docx(29页珍藏版)》请在冰豆网上搜索。
JspServlet留言板实践源码
系统概述
一个简单的留言板所实现的功能有:
用户注册、用户登录、查看留言信息和留言四个功能。
在学习了JSP/Servlet后编写的一个简单的实例,虽然简单,却拥有一个完整系统的必要功能,所以可以让自己初步了解使用JSP/Servlet技术开发系统的一般步骤。
系统功能简介:
用户注册:
当用户注册一个新用户时,就是向数据库user_table表中添加一条记录。
当用户输入注册信息后,将用户的的注册信息提交到服务端负责处理注册信息的Servlet。
当Servlet成功处理完用户的信息后,
客户端自动跳转到【登录界面】进行登录。
用户登录:
当用户输入用户名、密码和验证码时。
系统将信息提交的处理登录信息的Servlet。
Servlet则调用服务器控制器里
的方法来处理用户登录。
当用户登录成功时,客户端自动跳转到【留言板】。
留言板:
调用数据库中的留言信息,显示在页面上。
同时用户可以通过【留言】按钮,跳转到【留言】界面,留言功能和注册功能
类似,向数据库ly_table表中添加一条记录。
数据库的设计:
对于该系统来说有两个表【user_table】和【ly_table】。
字段名
类型
含义
id
int
留言信息的id
userId
int
用户的id
title
varchar(25)
标题名字
date
date
留言时间
Content
text
留言类容
【user_table】如下:
字段名
类型
含义
id
int
用户id
username
varchar(20)
用户名
password
varchar(20)
密码
【ly_table】如下:
实现系统的基础类:
实现在注册、登录系统中使用的一些重要的类:
连接和操作数据库的DB类、存储用户的User类、
存储留言信息的LeaveMessageTable类和实现图形验证码的ValidationCode类。
连接和操作数据库的DB类中具体包括如下方法:
publicUsercheckUser(Stringusername,Stringpassword):
检查用户时候存在,存在就返回一个User对象,否则返回null。
publicbooleancheckValidationCode(HttpServletRequestrequest,StringvalidationCode):
检测验证码是否正确。
publicbooleanaddInfo(LeaveMessageTablely):
向数据库插入留言。
publicbooleaninsertUser(Stringusername,Stringpassword):
向数据库存入用户。
publicArrayListfindLyInfo():
从数据库中导出留言,返回一个ArrayList对象。
privateResultSetexecSQL(Stringsql,Object...args):
执行SQL语句。
在DB类的构造函数中连接数据库。
这样有Servlet类创建DB对象时,便在创建过程中进行数据库的连接。
packageblogs.jbelial.DBServlet;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.util.*;
importjavax.servlet.http.HttpServletRequest;
importCommon.Encrypter;
importCommon.LeaveMessageTable;
importCommon.User;
publicclassDB{
//定义数据库连接变量
privateConnectionconnection;
//定义参数
privateStringsql_driver="com.mysql.jdbc.Driver";
privateStringsql_url="jdbc:
mysql:
//localhost:
3306/web_ly_table";
privateStringsql_username="root";
privateStringsql_password="hezuoan";
publicDB()
{
try{
//建立数据库的连接
Class.forName(sql_driver);
connection=DriverManager.getConnection(sql_url,sql_username,sql_password);
}
catch(Exceptione)
{
e.printStackTrace();
}
}
//用于执行各种SQL语句的方法
privateResultSetexecSQL(Stringsql,Object...args)
throwsSQLException
{
PreparedStatementpstmt=connection.prepareStatement(sql);
//为PreparedStatement对象设置SQL参数
for(inti=0;i { pstmt.setObject(1+i,args[i]); } //运行 pstmt.execute(); returnpstmt.getResultSet(); } //核对用户输入的验证码是否正确 publicbooleancheckValidationCode(HttpServletRequestrequest, StringvalidationCode) { StringvalidationCodeSession=(String)request.getSession().getAttribute("validationCode"); if(validationCodeSession==null) { //给result.jsp设置信息 request.setAttribute("info","验证码过期"); //给login.jsp设置信息 request.setAttribute("codeError","验证码过期"); returnfalse; } if(! validationCode.equalsIgnoreCase(validationCodeSession)) { request.setAttribute("info","验证码错误"); request.setAttribute("codeError","验证码错误"); returnfalse; } returntrue; } //检查用户登录信息 publicUsercheckUser(Stringusername,Stringpassword) { try{ Stringsql="select*fromuser_tablewhereusername=? andpassword=? "; ResultSetrs=execSQL(sql,username,password); Useruser=newUser(); while(rs.next()) { user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); returnuser; } returnnull; } catch(Exceptione) { e.printStackTrace(); returnnull; } } //插入留言 publicbooleanaddInfo(LeaveMessageTablely){ try{ Stringsql="insertintoly_table(userId,data,title,content)values(? ? ? ? )"; execSQL(sql,ly.getUserId(),ly.getDate(),ly.getTitle(),ly.getContent()); returntrue; }catch(Exceptione){ e.printStackTrace(); returnfalse; } } //插入用户 publicbooleaninsertUser(Stringusername,Stringpassword){ try{ Stringsql="insertintouser_table(username,password)values(? ? )"; execSQL(sql,username,password); returntrue; }catch(Exceptione){ e.printStackTrace(); returnfalse; } } //获取留言信息。 publicArrayListfindLyInfo() { ArrayListarrayList=newArrayList(); try { Stringsql="select*fromly_table"; ResultSetrs=execSQL(sql); while(rs.next()) { LeaveMessageTablely=newLeaveMessageTable(); ly.setId(rs.getInt("id")); ly.setUserId(rs.getInt("userId")); ly.setDate(rs.getDate("data")); ly.setTitle(rs.getString("title")); ly.setContent(rs.getString("content")); arrayList.add(ly); } returnarrayList; } catch(Exceptione) { e.printStackTrace(); returnnull; } } //获取用户名 publicStringgetUserName(intid) { Stringusername=null; try{ Stringsql="selectusernamefromuser_tablewhereid=? "; ResultSetrs=execSQL(sql,newObject[]{id}); while(rs.next()){ username=rs.getString (1); } returnusername; }catch(Exceptione){ e.printStackTrace(); returnnull; } } } User类和LeaveMessageTable类: User类中则包含Id、用户名和密码三个属性。 同时包含各个属性的set和get方法。 packageCommon; publicclassUser{ //用户的id privateintid; //用户名 privateStringusername; //用户密码 privateStringpassword; publicintgetId(){ returnid; } publicvoidsetId(intid){ this.id=id; } publicStringgetUsername(){ returnusername; } publicvoidsetUsername(Stringusername){ this.username=username; } publicStringgetPassword(){ returnpassword; } publicvoidsetPassword(Stringpassword){ this.password=password; } } LeaveMessageTable类: 包含了如下属性Id、留言用户Id、留言标题、留言时间、留言类容属性。 同时也包含了各个属性的 set和get方法。 packageCommon; importjava.sql.Date; publicclassLeaveMessageTable{ privateintid; privateintuserId; privateDatedate; privateStringtitle; privateStringcontent; publicintgetId(){ returnid; } publicvoidsetId(intid){ this.id=id; } publicintgetUserId(){ returnuserId; } publicvoidsetUserId(intuserId){ this.userId=userId; } publicDategetDate(){ returndate; } publicvoidsetDate(Datedate){ this.date=date; } publicStringgetTitle(){ returntitle; } publicvoidsetTitle(Stringtitle){ this.title=title; } publicStringgetContent(){ returncontent; } publicvoidsetContent(Stringcontent){ this.content=content; } } 实现图形验证码: 实现图形验证码大致分为5步上来完成: 1、建立图形缓冲区; 2、在图形缓冲区用随机颜色填充背景。 3、在图形缓冲区上输出验证码。 4、将验证码保存在HttpSession对象中。 5、向客户端输出图形验证码。 通过ValidationCode类来实现验证码功能,该类也是Servlet类,在客户端只要像访问普通Servlet一样访问ValidationCode类即可。 packageblogs.jbelial.Validation; importjava.awt.*; importjava.awt.image.BufferedImage; importjava.io.*; importjava.util.Random; importjavax.imageio.ImageIO; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; @SuppressWarnings("serial") publicclassValidationCodeextendsHttpServlet { //图形验证码的字符集合,系统通过随机从这些字符串中选择一些字符作为验证码 privatestaticStringcodeChars= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTYVWXYZ"; //返回一个随机颜色 privatestaticColorgetRandomColor(intminColor,intmaxColor) { Randomrandom=newRandom(); if(minColor>255) minColor=255; if(maxColor>255) maxColor=255; //获取颜色的随机值 intred=minColor+random.nextInt(maxColor-minColor); intgreen=minColor+random.nextInt(maxColor-minColor); intblue=minColor+random.nextInt(maxColor-minColor); returnnewColor(red,green,blue); } publicvoiddoGet(HttpServletRequestrequest, HttpServletResponseresponse)throwsIOException { //获取验证码集合的长度。 intcharsLength=codeChars.length(); //关闭浏览器缓冲区 response.setHeader("ragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires",0); //设置图片传送的格式。 response.setContentType("image/jpeg"); //设置图形验证码的长和宽度 intwidth=90; intheight=20; //建立图形缓冲区 BufferedImageimage=newBufferedImage(width,height, BufferedImage.TYPE_INT_RGB); //获取用于输出文字的Graphics对象 Graphicsgraphics=image.getGraphics(); Randomrandom=newRandom(); //设置要填充的颜色 graphics.setColor(getRandomColor(180,250)); //填充图形背景 graphics.fillRect(0,0,width,height); //设置初始字体和颜色 graphics.setFont(newFont("TimeNewRoman",Font.ITALIC,height)); graphics.setColor(getRandomColor(120,180)); //保存验证码 StringBuildervalidationCode=newStringBuilder(); //验证码的随机字体 String[]fontNames={"TimesNewRoman","Bookantiqua","Arial"}; //随机生成验证码 for(inti=0;i<4;++i) { //设置当前验证码字符的字体 graphics.setFont(newFont(fontNames[random.nextInt(3)],Font.ITALIC, height)); //随机获得验证码的字符 charcodeChar=codeChars.charAt(random.nextInt(charsLength)); validationCode.append(codeChar); graphics.setColor(getRandomColor(20,120)); //在图形上输出验证码字符 graphics.drawString(String.valueOf(codeChar),16*i+random.nextInt(7), height-random.nextInt(6)); } //获得Session对象,并设置Session对象为3分钟 HttpSessionsession=request.getSession(); session.setMaxInactiveInterval(5*60); //将验证码放入session对象中. session.setAttribute("validationCode",validationCode.toString()); //关闭graphics对象。 graphics.dispose(); //向客户端发送图形验证码 ImageIO.write(image,"JPEG",response.getOutputStream()); } publicvoiddoPost(HttpServletRequestrequest, HttpServletResponseresponse)throwsIOException { doGet(request,response); } } 实现注册系统: 包括一个register.jsp、result.jsp和RegisterServlet类。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Jsp Servlet留言板实践源码 Servlet 留言板 实践 源码