我不是个十全十美的人,也没要求过十全十美的东西 ------ 刷新

博客网站开发

一、需求分析:

根据博客网站的特点,并与用户进行沟通。要求本系统具有以下功能:
1、  统一、友好的操作界面,用以保证系统的易用性。
2、  强大的查询功能,便于用户查询各项信息。
3、  添加评论的功能,以方便用户对博主发表的文章添加评论。
4、  添加了友情链接,以方便用户进入其他网站。
5、  博客文章管理功能,以方便博主添加、修改、删除博客文章。
6、  公告管理功能,以方便博主添加、修改、删除公告信息。
7、  日志管理功能,以方便博主添加、修改、删除日志信息。
8、  个人相片设置功能,以方便博主添加、修改、删除相片功能。
9、  朋友信息管理功能,以方便博主添加、修改、删除朋友信息。
10、博主信息设置,以方便及时的更新博主信息。

二、  设计目标

根据博客网站的需求进行开发设计,主要实现如下目标:

1、         界面设计友好、美观,数据存储安全、可靠。

2、         强大的查询功能,方便用户浏览网站信息。

3、        设置了登录模块,保证了网站的数据安全性。

4、        实现对博主发表的文章、公告、相片、日志等信息的添加、修改、删除功能,便于更新网站内容。

5、        系统最大限度地实现了易维护性和易操作性。

6、         采用人机对话的操作方式,方便用户的日常操作。

三、 开发及运行环境
硬件平台:
1、CPU:P41.8GHz。
2   内存:256MB以上。
软件平台:
1 操作系统:Windows XP/Windows 2000/Windows 2003
2 数据库:SQL Server 2000。
3 开发工具包:JDK Version1.6。
4 JSP服务器:Tomcat 6.0
5 浏览器:IE6.0。
6 分辨率:最佳效果1024×768像素。

四、技术准备:

 Hibernate配置文件;
Hibernate从其配置文件中读取和数据库连接有关的信息,Hibernate的配置文件有两种形式:一种是XML格式的文件;还有一种是Java属性文件,采用“键 = 值”的形式。博客网站采用的是Java的属性文件的格式来创建Hibernate的配置文件。这种配置文件的默认文件名是hibernate.properties。代码如下:
hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.connection.driver_class=net.sourceforge.jtds.jdbc.Driver
hibernate.connection.url=jdbc:jtds:sqlserver://localhost:1433/db_BlodMay
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.show_sql=true
hibernate.hbm2ddl.auto=none

 创建持久化类:
持久化类是指需要被Hibernate持久化到数据库中的类。持久化类符合JavaBean的规范。包含一些属性,以及与之对应的getXXX()和setXXX()方法。下面是定义了一个持久化类Friend。代码如下:

public class Friend {
private int id;
private String name;
private String QQNumber;
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQQNumber() {
return QQNumber;
}
public void setQQNumber(String number) {
QQNumber = number;
}
}

 Hibernate映射文件
Hibernate采用XML格式的文件来指定对象和关系数据之间的映射。程序运行时,Hibernate将根据这个映射文件来生成各种SQL语句。下面的实例将创建一个名为Friend.hbm.xml的文件。用于完成Friend类与数据表tb_friend的映射。代码如下:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.Hibernate.persistence.Friend" table="tb_friend" lazy="false">
<id name="id" column="id" type="int" >
<generator class="increment"/>
</id>
<property name="name" column="name" type="string"/>
<property name="QQNumber" column="QQNumber" type="string"/>
<property name="description" column="description" type="string"/>
</class>
</hibernate-mapping>

五、公共类设计

1.1 获得当前系统时间类

获得当前系统时间类封装在CountTime类中。java.text包中的DateFormat类是日期/时间格式化子类的抽象类。该类的静态方法getDateInstance()可获得默认语言环境的日期格式。CountTime类的代码如下。

package com.wy.tool;
import java.util.Date;
import java.text.DateFormat;
public class CountTime {
public String currentlyTime() {
Date date = new Date(); //创建Date对象
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
return dateFormat.format(date);
}
}

1.2 字符处理类的编写
在JSP页面中输出中文要考虑中文的乱码问题,解决这一问题有很多种方法。博客网站中将字符处理类封装在Chinese类中,该类实现了Filter接口,并重写了该接口中的方法。在Filter接口中有3个方法,分别是init()方法、destroy()方法和doFilter()方法。init()方法只在此过滤器第一次初始化时执行,对于简单的过滤器此方法体可以为空。destroy()方法在利用一个给定的过滤器对象持久地终止服务器时调用,一般情况下此方法体为空。doFilter()方法为大多数过滤器的关键部分,该方法包括ServletRequest、ServletResponse、FilterChain3个参数。在调用FilterChain的doFolter()方法时,激活一个相关的过滤器。如果没有另一个过滤器与Servlet或JSP页面关联,则Serlet或JSP页面被激活。代码如下。

package com.wy.tool;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Chinese implements Filter {
public void destroy() { //destroy()方法,该方法体可以为空。
}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("gb2312"); //设置request的编码格式
response.setCharacterEncoding("gb2312"); //设置response的编码格式
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {//init方法,该方法体为空。
}
}


若想要使Chinese类在程序中自动被调用,还需在web.xml文件中配置如下代码。
<filter>
<filter-name>chinese</filter-name>
<filter-class>com.wy.tool.Chinese</filter-class>
</filter>
<filter-mapping>
<filter-name>chinese</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

代码导读
<filter>元素用于声明过滤器,它的两个子元素分别是:
<filter-name>指定过滤器的名称,名称可自定义。
<filter-class>指定过滤器的完整路径。
<filter-mapping>用于指定需要处理的请求。它的两个子元素分别是:
<filter-name>指定过滤器的名称,与<filter>中的子元素<filter-name>对应。
<url-pattern>过滤请求环境相关路径,配置成“/*”会过滤所有文件。

1.3 将字符串转化成字符数组类
在程序设计时经常会遇到将字符串转化成字符数组的问题,例如保存兴趣爱好信息时,数据库中保存的信息是以字符串形式保存,在应用程序中可能会需要将字符串转换成字符数组,因此将字符串转化成字符数组作为单独的公共类提出来。代码如下。
package com.wy.tool;
public class ConverUtil {
public static String[] str2String(String strStr) { //定义静态方法。
String[] intarris = null; //定义String数组。
if (strStr != null && !strStr.equalsIgnoreCase("")) {
String str[] = strStr.split(" "); //将字符串以空格作为标记进行拆分。

if (str != null && str.length > 0) {
intarris = new String[str.length];
for (int i = 0; i < str.length; i++) {
intarris[i] = str[i];
}
}
}
return intarris; //将字符数组变量作为返回值返回。
}
}

1.4 Hibernate的初始化与Session管理类的编写
Hibernate的初始化负责读取Hibernate的配置信息以及Hibernate映射文件的信息,最后创建SessionFactory实例。博客网站中完成Hibernate的初始化代码如下所示。
package com.Hibernate.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.Hibernate.persistence.*;
public class Hibernate {
private static SessionFactory sf = null;

static {
try {
Configuration conf = new Configuration().addClass(AriticleType.class)
.addClass(Article.class).addClass(Consumer.class)
.addClass(Discuss.class).addClass(Friend.class)
.addClass(Photo.class).addClass(Vote.class).addClass(Comm.class);
sf = conf.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

技术细节
hibernate的初始化主要分为以下几步:
(1)创建Configuration类实例,Configuration类的构造方法把默认文件路径下的hibernate.properties配置文件中的配置信息读入到内存中。
(2)调用Configuration类的addClass()方法将映射文件信息读入到内存中。
(3)调用Configuration类的buildSessionFactory()方法创建一个SessionFactory实例。
完成Hibernate的初始化后,就可以调用SessionFactory对象的openSession()方法来获得Session实例,然后通过Session实例来执行访问数据库的操作。Session接口提供了各种方法,如save()、delete()等。通常Session实例和一个数据库事务绑定,也就是说,每执行一个数据库事务,都应该先创建一个新的Session实例,最后调用Session的close()方法。释放Session实例占用的资源。博客网站中将Session的获取与关闭作为公告类来编写,代码如下。

public Session openSession(){ //开启Session方法
Session session = sf.openSession();
return session;
}
public void closeSession(Session session){ //关闭Session方法
if(session != null){
session.close();
}

六、前台功能

由于时间关系网站前台的一些功能直接给出代码如下;

<%
Integer number= new Integer(1);
int num = 1 ;
if(application.getAttribute("number")!=null){
number=(Integer)application.getAttribute("number");
num = number.intValue();
num++;
}
application.setAttribute("number",new Integer(num));
%>
<%@ page language="java" import="java.util.*" %>
<%! String days[]; %>
<%
days=new String[42];
for(int i=0;i<42;i++)
{
days[i]="";
}
%>
<%
GregorianCalendar currentDay = new GregorianCalendar();
int today=currentDay.get(Calendar.DAY_OF_MONTH); //取得当前日期
int month=currentDay.get(Calendar.MONTH); //取得当前月份
int year= currentDay.get(Calendar.YEAR); //取得当前年份
//通过request取值不为空的时候,程序运行如下代码
if(request.getParameter("month")!=null&&request.getParameter("year")!=null){
int requestMonth=Integer.parseInt(request.getParameter("month"));
int requestYear=Integer.parseInt(request.getParameter("year"));
Calendar thisMonth=Calendar.getInstance();
thisMonth.set(Calendar.MONTH, month );
thisMonth.set(Calendar.YEAR, year );
thisMonth.setFirstDayOfWeek(Calendar.SUNDAY);
thisMonth.set(Calendar.DAY_OF_MONTH,1);
int firstIndex=thisMonth.get(Calendar.DAY_OF_WEEK)-1; //月份的1日为星期几
int maxIndex=thisMonth.getActualMaximum(Calendar.DAY_OF_MONTH); //月份为多少天
for(int i=0;i<maxIndex;i++)
{
days[firstIndex+i]=String.valueOf(i+1);
}
%>
<table width="180" height="81" border="1" align="center" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="CBB180">
<tr bgcolor="FFFCF1">
<th height="15" colspan="7" align="center"><%=year%>年<%=month+1%>月</th>
</tr>
<tr bgcolor="C9B65A">
<th width="25" height="15" >日</th>
<th width="25" height="16" bgcolor="C9B65A">一</th>
<th width="25" height="16" bgcolor="C9B65A">二</th>
<th width="25" height="16" bgcolor="C9B65A">三</th>
<th width="25" height="16" bgcolor="C9B65A">四</th>
<th width="25" height="16" bgcolor="C9B65A">五</th>
<th width="25" height="16" bgcolor="C9B65A">六</th>
</tr>
<% for(int j=0;j<6;j++) { //循环网络日历的内容%>
<tr bgcolor="FFFCF1">
<% for(int i=j*7;i<(j+1)*7;i++) { %>
<td width="25" height="1" align="center" valign="middle">
<%if((i-firstIndex+1)==today){%>
<b> <font color="red"><%=days[i]%></font></b>
<%} else {%>
<%=days[i]%>
<%}%></td>
<% } %>
</tr>
<% } %>
</table>
package com.Hibernate.persistence;
public class Consumer {
private int id; //博主ID值
private String account; //博主帐号
private String passWord; //登录网站密码
private String name; ///博主姓名
private String sex; //博主性别
private String QQNumber; //博主QQ号
private String mainPage; //主页信息
private String interest; //博主爱好
private String EMail; //博主邮箱地址
public String getEMail() {
return EMail;
}
public void setEMail(String mail) {
EMail = mail;
}
……//省略了其他属性的setXXX()和getXXX()方法
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.Hibernate.persistence.Consumer" table="tb_consumer" lazy="false">
<id name="id" column="id" type="int" >
<generator class="increment"/>
</id>
<property name="account" column="account" type="string"/>
<property name="passWord" column="passWord" type="string"/>
<property name="name" column="name" type="string"/>
<property name="sex" column="sex" type="string"/>
<property name="QQNumber" column="QQNumber" type="string"/>
<property name="mainPage" column="mainPage" type="string"/>
<property name="interest" column="interest" type="string"/>
<property name="EMail" column="EMail" type="string"/>
</class>
</hibernate-mapping>
package com.Hibernate.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.Hibernate.persistence.*;
public class Gethibernate {
private Session session; //创建Session实例
private Hibernate hib = new Hibernate(); //创建公共类对象
public List findUser(String strUserName) {
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类的开启session方法.
tx = (Transaction) session.beginTransaction(); //开启事物
Query query = session.createQuery("from Consumer as u where u.account=:strUserName"); //应用HQL检索满足条件的集合
query.setString("strUserName", strUserName); //动态绑定参数
list = query.list(); //list()方法用来执行HQL语句
tx.commit(); //事务的提交
hib.closeSession(session); //关闭session
} catch (Exception e) {
e.printStackTrace(); //输出异常信息
tx.rollback(); //事务的回滚
}
return list;
}
<table width="800" height="71" border="0" align="center" cellpadding="0" cellspacing="0" background="images/head_04.jpg">
<tr>
<td width="31">&nbsp;</td>
<td width="640"><table width="619" border="0" align="center" cellpadding="0" cellspacing="0">
<%
Gethibernate hib = new Gethibernate();
List list = hib.findUser("mr");
for(int i = 0;i < list.size();i++){
Consumer cons = (Consumer)list.get(i);
%>
<tr>
<td height="20"><span class="style1">博主信息</span></td>
<td colspan="2">

<div align="right"><span class="style2">【</span><a href="enter.jsp" class="in">进入后台</a><span class="style2">】</span></div>

</td>
</tr>
<tr>
<td height="20"><span class="style3 style2">姓名:<%=cons.getName()%></span></td>
<td width="212"><span class="style3 style2">性别:<%=cons.getSex()%></span></td>
<td width="195"><span class="style3 style2">兴趣:<%=cons.getInterest() %></span></td>
</tr>
<tr>
<td height="20"><span class="style3 style2">QQ号码:<%=cons.getQQNumber()%></span></td>
<td><span class="style3 style2">E-Mail:<%=cons.getEMail() %></span></td>
<td><span class="style3 style2">主页:<%=cons.getMainPage()%></span></td>
</tr>
<%} %>
</table>
public List findAriticleType() {
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类的开启session方法.
tx = (Transaction) session.beginTransaction();
Query query = session.createQuery("from AriticleType");
list = query.list(); //list()方法用来执行HQL语句
tx.commit(); //事务的提交
hib.closeSession(session); //调用公告类方法关闭session
} catch (Exception e) {
e.printStackTrace(); //输出异常信息
tx.rollback(); //事务的回滚
}
return list;
}
<table width="390" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<%
Gethibernate geth = new Gethibernate();
List list=geth.findAriticleType();
for(int i=0;i<list.size();i++){
AriticleType articleType = (AriticleType)list.get(i);
%>
<a href="head_ArticleList.jsp?typeId=<%=articleType.getId()%>"> [<%=articleType.getTypeName()%>]</a>&nbsp; //以超链接的形似显示文章类型
<%}%>
</td>
</tr>
</table>
public List findArity(int aid,int intFrist,int intPages) {
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类方法获取Session对象
tx = (Transaction) session.beginTransaction(); //开启事务
Query query = session
.createQuery("from Article as c where c.typeID =:aid");
//创建Query对象
query.setInteger("aid", aid); //动态绑定参数
query.setFirstResult(intFrist);
query.setMaxResults(intPages);
list = query.list();
tx.commit();
hib.closeSession(session);
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return list;
}
public int findAritiCount(int aid) {
Transaction tx = null;
int intCount=0;
try {
session = hib.openSession(); //调用公共类方法开启Session
tx = (Transaction) session.beginTransaction(); //开启事务
intCount = ((Integer) session.createQuery("select count(*)from Article u where u.typeID ="+"'"+aid+"'").uniqueResult()).intValue(); //查询指定文章类型的文章总数
tx.commit(); //提交事务
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return intCount;
}
<%
String currPage = request.getParameter("currPage");
int iCurrPage = 1 ; //定义int型变量,代表当前页数。
int pages = 1 ; //定义int型变量,代表总页数。
int allRecCount = 0 ; //定义int型变量,代表对象总数。
int recPerPage = 5 ; //定义intr型变量,确定每页显示的记录数。
int intid = 4; //定义int型变量,确定显示文章的文章类型。
String strId = request.getParameter("typeId");
if(strId !=null){
intid = Integer.parseInt(strId);
}
allRecCount = geth.findAritiCount(intid); //查询特定文章类型的文章总数
pages = (allRecCount - 1)/recPerPage + 1; //获取总页数
if(pages == 0){ //如果总页数是0,则将pages变量设置为1
pages = 1;
}
if(currPage != null && !currPage.equalsIgnoreCase("")){
iCurrPage = Integer.parseInt(currPage);
}
List listAri = geth.findArity(intid,(iCurrPage - 1) * recPerPage, recPerPage);
if(!listAri.isEmpty()&& listAri.size()>0){
for(int articleI=0;articleI<listAri.size();articleI++){
Article article = (Article)listAri.get(articleI);
String articleContent = article.getContent();
if(articleContent.length()>100){
articleContent=articleContent.substring(0,100)+"...";
}
%>
<table width="380" border="0" align="center">
<tr>
<td width="377" height="22"><font color="BE9110"><b><%=article.getTitle()%></b></font></td>
</tr>
<tr>
<td valign="top"><span class="style7"><%=articleContent%></span></td>
</tr>
<tr>
<td height="17" class="head-02"><a href="head_ArticleForm.jsp?id=<%=article.getId()%>" class="head-02">阅读全文&gt;&gt;</a></td>
</tr>
<tr>
<td height="17" align="right"><%=article.getPhTime()%>&nbsp
</tr>
</table>
<% if(recPerPage < allRecCount){
String href = "&nbsp;&nbsp;<a href='head_ArticleList.jsp?currPage=";
StringBuffer sbf = new StringBuffer(); //制作分页条
if(iCurrPage > 1){
sbf.append(href+(iCurrPage - 1)+"'>上一页</a>"); //构造上一页
}
for(int i = 1 ; i <= pages ; i ++){
if(i == iCurrPage){
sbf.append(href+i+"'>["+i+"]</a>"); //追加串
}
else{
sbf.append(href+i+"'>"+i+"</a>");
}
}
if(iCurrPage < pages){
sbf.append(href+(iCurrPage + 1)+"'>下一页</a>"); //构造下一页
}
%>
<%out.print("当前页数:["+iCurrPage+"/"+pages+"]");%>
<%=sbf.toString()%>
<%}%>
function addRestore(){ //评论添加
if(document.form.reTitle.value==""){ //判断用户是否输入评论题目
window.alert("请输入评论题目!");
return false;
}
if(document.form.reContent.value==""){ //判断用户是否输入评论内容
window.alert("请输入评论内容!");
return false;
}
if(document.form.reContent.value.length > 1000){ //判断用户输出评论内容的长度是否大于1000
window.alert("评论内容之多可输出1000位!");
return false;
}
if(document.form.prerson.value==""){ //判断用户是否输入名字
window.alert("请输入您的名字!");
return false;
}
return true;
}
public void saveComm(Comm comm) { //保存评论信息方法
Transaction tx = null; //声明事务对象
try {
session = hib.openSession(); //调用公共类方法打开Session
tx = (Transaction) session.beginTransaction(); //开启事务
session.save(comm); //保存comm对象
tx.commit(); //提交事务
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback(); //如果发生异常事务回滚
}
}
<%
Gethibernate geth = new Gethibernate();
Comm comm = new Comm();
String strid = request.getParameter("id");
comm.setArticleId(Integer.parseInt(strid));
comm.setPerson(request.getParameter("prerson"));
comm.setReTitle(request.getParameter("reTitle"));
comm.setReContent(request.getParameter("reContent"));
geth.saveComm(comm); //调用保存comm对象方法
%>

七、网站后台功能界面

1.1 网站后台主要功能模块设计
用户进入网站后台管理必须经过登录模块,博客网站后台分为以下功能:
q 博客文章管理
q 公告管理
q 日志管理
q 用户相片设置
q 朋友信息管理
q 博主设计

博客网站首页提供了“进入后台”超链接,单击此链接可进入网站后台。但是用户必须输入正确的用于名和密码才能进入网站后台,登录页面的运行结果如图1所示。

 

1.2 后台首页设计
当用户登录成功以后则进入系统后台首页,博客网站后台首页的运行结果如图所示。

由于时间关系给出代码自己琢磨吧

q 博客文章管理
q 公告管理
q 日志管理
q 用户相片设置
q 朋友信息管理
q 博主设计
public List findUser(String strUserName, String strPwd) {
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类的开启session方法.
tx = (Transaction) session.beginTransaction();
Query query = session.createQuery("from Consumer as u where u.account=:strUserName and u.passWord=:strPwd"); //应用HQL检索查找满足条件的集合
query.setString("strUserName", strUserName); //动态绑定参数
query.setString("strPwd", strPwd);
list = query.list(); //list()方法用来执行HQL语句
tx.commit(); //事务的提交
hib.closeSession(session); //调用公共类方法关闭session
} catch (Exception e) {
e.printStackTrace(); //输出异常信息
tx.rollback(); //事务的回滚
}
return list;
}
<%
String strname = request.getParameter("account"); //获取用户输入的信息
String password = request.getParameter("password");
Gethibernate geth = new Gethibernate();
List list = geth.findUser(strname,password); //调用公共类中方法
if(list.size()!=0){
for(int i= 0;i<list.size();i++){
Consumer cons = (Consumer)list.get(i);
application.setAttribute("cons",cons);
}
response.sendRedirect("backMainPage.jsp");
}
else{
%>
<script language="javascript">
alert("用户名或密码输出错误!");
window.location.href='enter.jsp';
</script>
<%}%>
<jsp:include page=”url” flush = “true | false”/>
url:表示所要包含文件对应的URL,可以是一个字符串,也可以是一个JSP表达式。
flush:该值是true表示当缓存区满时,缓存区将被清空,默认为false。
<jsp:include page="back_Top.jsp" flush="true" />
q getCollection()方法
public Collection getCollection(){
return m_files.values();
}
getEnumeration()方法
public Enumeration getEnumeration(){
return m_files.elements();
}
文件上传与文件下载必须实现的方法
initialize(ServletConfig config, HttpServletRequest request, HttpServletResponse response)
initialize(ServletContext application, HttpSession session, HttpServletRequest request, HttpServletResponse response, JspWriter out)
initialize(PageContext pageContext)
文件上传使用的方法
save(String destPathName)
save(String destPathName, int option)
<%
Gethibernate geth = new Gethibernate(); //创建Gethibernate对象
Photo photoForm = new Photo(); //创建持久化
com.jspsmart.upload.SmartUpload su = new com.jspsmart.upload.SmartUpload();
String result = "上传的照片格式和大小有问题,上传照片失败!";
String type = null;
String imageType[] = { "JPG", "jpg", "gif", "bmp", "BMP" };
String filedir = "file/";
long maxsize = 2 * 1024 * 1024; //设置每个上传文件的大小,为2MB
try {
su.initialize(this.getServletConfig(), request, response);
su.setMaxFileSize(maxsize); //限制上传文件的大小
su.upload(); //上传文件
Files files = su.getFiles(); //获取所有的上传文件
for (int i = 0; i < files.getCount(); i++) { //逐个获取上传的文件
File singlefile = files.getFile(i);
type = singlefile.getFileExt();

for (int j = 0; j < imageType.length;j++) {
if (imageType[j].equals(type)) {
if (!singlefile.isMissing()) { //如果选择了文件
String photoTime = su.getRequest().getParameter(
"phtoTime");
String photoDescription = su.getRequest()
.getParameter("photoDescription");
photoForm.setPhtoTime(photoTime);
photoForm.setPhotoDescription(photoDescription);
filedir = singlefile.getFilePathName();
photoForm.setPhotoAddress(filedir);
result = "上传照片成功!";
request.setAttribute("result", result);
//就字符串信息保存到request对象中
}
}
}
}
geth.savePhoto(photoForm);
} catch (Exception e) {
e.printStackTrace();
}
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("back_PhotoInsert.jsp");
requestDispatcher.forward(request, response);
%>
public List findPhoto(int intFrist,int intPages) { //页面查询相片信息
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类方法打开Session
tx = (Transaction) session.beginTransaction();
Query query = session
.createQuery("from Photo");
query.setFirstResult(intFrist); //设置从哪一个对象开始检索
query.setMaxResults(intPages); //设置最多检索出的对象的数目
list = query.list();
tx.commit();
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return list;
}
public int findPhotoCount() { //查询照片总数
Transaction tx = null;
int intCount=0;
try {
session = hib.openSession(); //调用公共类方法打开Session
tx = (Transaction) session.beginTransaction();
intCount = ((Integer) session.createQuery("select count(*)from Photo").uniqueResult()).intValue();
tx.commit();
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return intCount;
}
<%
String currPage = request.getParameter("currPage"); //获取页面的请求参数
Gethibernate geth = new Gethibernate(); //创建Gethibernat对象
int iCurrPage = 1 ; //定义int型变量,用于保存当前页数
int pages = 1 ; //定义int型变量,用于保存共分的页数
int allRecCount = 0 ; //定义int型变量,用于保存总的记录数
int recPerPage = 4 ; //定义int型变量,用于保存每页显示的记录数
allRecCount = geth.findPhotoCount(); //查询出总的记录数
pages = (allRecCount - 1)/recPerPage + 1; //计算出总的页数
if(pages == 0){ //对页数进行有效性处理,使页数的最小值是1
pages = 1;
}
if(currPage != null && !currPage.equalsIgnoreCase("")){
iCurrPage = Integer.parseInt(currPage);
}
List listPhoto = geth.findPhoto((iCurrPage - 1) * recPerPage, recPerPage);
if(!listPhoto.isEmpty()&& listPhoto.size()>0){
for(int i=0;i<listPhoto.size();i++){
Photo photoForm=(Photo)listPhoto.get(i);
if(i % 2 == 0 ){ //如果相片数量整除2时,显示照片的形式
%>
<tr bgcolor="#FFFFFF"> <td width="230"><div align="center">
<table width="200" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="150"><div align="center"><a href="#" onClick="window.open('photoSelectOne.jsp?image=<%=photoForm.getPhotoAddress()%>','','width=600,height=700');"><img src="<%=photoForm.getPhotoAddress()%>" width="160" height="140"></a></div></td>
</tr> <tr>
<td height="20"><div align="center"><%=photoForm.getPhotoDescription()%></div></td>
</tr> <tr>
<td height="20"><div align="center"><a href="deletePhoto.jsp?id=<%=photoForm.getId()%>">删除</a></div></td>
</tr></table> </div></td>
<%}else{%>
<td width="212"><div align="center">
<table width="200" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="150"><div align="center"><a href="#" onClick="window.open('photoSelectOne.jsp?image=<%=photoForm.getPhotoAddress()%>','','width=600,height=700');"><img src="<%=photoForm.getPhotoAddress()%>" width="160" height="140"></a></div></td>
</tr> <tr>
<td height="20"><div align="center"><%=photoForm.getPhotoDescription()%></div></td>
</tr><tr><td height="20"><div align="center"><a href="deletePhoto.jsp?id=<%=photoForm.getId()%>">删除</a></div></td>
</tr> </table></div> </td> </tr>
<%}}}%>
<%if(listPhoto.size()%2 ==1){%> //如果相片数量不整除2时,显示照片的形式
<td bgcolor="#FFFFFF"><div align="center">
<table width="200" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><td height="150"><div align="center"></div></td>
</tr><tr><td height="20"><div align="center"></div></td>
</tr><tr> <td height="20"><div align="center"></div></td>
</tr></table> </div></td>
<%}%>
</table>
<%
Gethibernate geth = new Gethibernate();
List list = geth.findUser("mr");
if(!list.isEmpty() && list.size()>0){
for(int i = 0 ;i<list.size();i++){
Consumer cons = (Consumer)list.get(i);
%>
<form name="form" method="post" action="ConsumerSave.jsp?id=<%=cons.getId()%>" onSubmit="return hostUpdate()">
<table width="325" border="1" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#FECE62"> <tr>
/************篇幅有限,这里只介绍显示博主性别与兴趣爱好的代码********************/
<tr>
<td height="30"><div align="center">性别:</div></td>
<td bgcolor="#FFFFFF"><div align="center">
<input name="sex" type="radio" class="inputinputinput" value="男" <%if(cons.getSex().trim().equals("男")){%>checked<%}%> >男
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sex" type="radio" class="inputinputinput" value="女" <%if(cons.getSex().trim().equals("女")){%>checked<%}%> > 女
</div></td> </tr> <tr>
<td height="30"><div align="center">兴趣爱好:</div></td>
<td bgcolor="#FFFFFF"><p><div align="center">
<%
String[] hobbys = ConverUtil.str2String(cons.getInterest());
%>
<input name="hobby1" type="checkbox" <%if( hobbys!=null && hobbys.length > 0){for(int ii=0;ii<hobbys.length;ii++){if(hobbys[ii].intValue().equalsIgnoreCase("上网"))out.print("checked='checked'");}} %> class="noborder" value="上网">上网
<input name="hobby2" type="checkbox" <%if( hobbys!=null && hobbys.length > 0) {for(int ii=0;ii<hobbys.length;ii++){if(hobbys[ii]. .equalsIgnoreCase("旅游"))out.print("checked='checked'");}} %> class="noborder" value="旅游">旅游
<input name="hobby3" type="checkbox" <%if( hobbys!=null && hobbys.length > 0) { for(int ii=0;ii<hobbys.length;ii++){if(hobbys[ii]. .equalsIgnoreCase("篮球"))out.print("checked='checked'");}} %> class="noborder" value="篮球">篮球</p> <p>
<input name="hobby4" type="checkbox" <%if( hobbys!=null && hobbys.length > 0) { for(int ii=0;ii<hobbys.length;ii++){if(hobbys[ii]. .equalsIgnoreCase("看书"))out.print("checked='checked'");} }%> class="noborder" value="看书">看书
<input name="hobby5" type="checkbox" <%if( hobbys!=null && hobbys.length > 0) {for(int ii=0;ii<hobbys.length;ii++){if(hobbys[ii]. .equalsIgnoreCase("台球"))out.print("checked='checked'");} }%> class="noborder" value="台球">台球
<input name="hobby6" type="checkbox" <%if( hobbys!=null && hobbys.length > 0) { for(int ii=0;ii<hobbys.length;ii++){if(hobbys[ii]. .equalsIgnoreCase("羽毛球"))out.print("checked='checked'");} }%> class="noborder" value="羽毛球">羽毛球</p></td> </tr> <tr>
<%}} %>
public List findAriticleType() {
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类方法打开Session
tx = (Transaction) session.beginTransaction(); //开启事务
Query query = session.createQuery("from AriticleType");
//检索AriticleType中所有对象
list = query.list(); //调用list()方法执行HQL语句
tx.commit();
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return list;
}
<%
Gethibernate geth = new Gethibernate(); //创建Gethibernate类对象
List list = geth.findAriticleType(); //调用findAriticleType()方法
if (!list.isEmpty() && list.size() > 0) { //判断list集合是否为空
%>
<select name="typeId" class="inputinput">
<%
for (int i = 0; i < list.size(); i++) { //循环遍历集合
AriticleType atype = (AriticleType) list.get(i);
%>
<option value="<%=atype.getId()%>"><%=atype.getTypeName()%>
</option>
<%}}%>
<tr>
<td height="30">
<div align="center">
发布时间:
</div>
</td>
<%
GetTime gettime = new GetTime(); //创建GetTime类对象
Date date = gettime.getDate(); //调用getDate()方法
%>
<td bgcolor="#FFFFFF">
<div align="center">
<input name="phTime" type="text" class="inputinput"
value="<%=date%>" size="30" readonly="readonly"
onClick="alert('此文本框已设为只读,用户不能修改')">
</div>
</td>
</tr>
public void saveArricle(Article ariticle) {
Transaction tx = null;
try {
session = hib.openSession(); //调用公共类方法开启Session
tx = (Transaction) session.beginTransaction();
session.save(ariticle); //保存Article对象
tx.commit(); //提交事务
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
}
<%
Gethibernate geth = new Gethibernate();
Article ari = new Article(); //创建Article对象
ari.setContent(request.getParameter("content"));
ari.setPhTime(request.getParameter("phTime"));
ari.setTitle(request.getParameter("title"));
String strname = request.getParameter("typeId");
ari.setTypeID(Integer.parseInt(strname));
geth.saveArricle(ari); //调用保存文章方法。
%>
<script language="javascript">
alert("文章添加成功!");
window.location.href='back_ArticleAdd.jsp';
</script>
public List findMain(int id) {
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类的开启session方法.
tx = (Transaction) session.beginTransaction(); //开启事物
Query query = session.createQuery("from Article where id =:id");
//应用HQL检索查找满足条件的集合
query.setInteger("id", id);
list = query.list(); //list()方法用来执行HQL语句
tx.commit(); //事务的提交
hib.closeSession(session); //关闭session
} catch (Exception e) {
e.printStackTrace(); //输出异常信息
tx.rollback(); //事务的回滚
}
return list;
}
<%
String strid = request.getParameter("id"); //获取页面提交的请求参数
int intid = Integer.parseInt(strid);
Gethibernate geth = new Gethibernate(); //创建Gethibernate对象
List listA = geth.findMain(intid); //调用findMain()方法
if(!listA.isEmpty()&&listA.size()>0){ //判断list集合是否为空
for(int i= 0;i<listA.size();i++){ //循环遍历集合
Article art = (Article)listA.get(i); //获取指定位置的Article对象
%>
<table width="340" border="1" cellpadding="1" cellspacing="1" bordercolor="#FFFFFF" bgcolor="#FECE62">
<tr>
<td width="77" height="30">
<div align="center">文章主题:</div>
</td>
<td width="250" bgcolor="#FFFFFF"><div align="center">
<input name="title" type="text" class="inputinput" size="30" value="<%=art.getTitle()%>">
</div></td></tr>
<tr>
<td height="30">
<div align="center">文章类别:</div> </td>
<td bgcolor="#FFFFFF"><div align="center">
<select name="typeId2" >
<% listAtype = geth.findAriticleType();
if(!listAtype.isEmpty() && listAtype.size()>0){
for(int j = 0;j < listAtype.size();j++){
AriticleType atype = (AriticleType)listAtype.get(j);
%>
<option value="<%=atype.getId()%>"
<%if( atype.getId() == art.getTypeID() ){%>
selected="selected"><%=atype.getTypeName()%></option>
<%} else{ %>
<option value="<%=atype.getId()%>"><%=atype.getTypeName()%></option>
<%}}} %>
</select>
/************省略了显示文章内容以及文章发表时间的代码****************/
public void updateAri(Article ariticle) {
Transaction tx = null;
try {
session = hib.openSession(); //调用公共类方法打开Session
tx = (Transaction) session.beginTransaction();
session.update(ariticle); //更新Article对象
tx.commit();
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
}
<%
Gethibernate geth = new Gethibernate();
String strid = request.getParameter("id");
List listA = geth.findMain(Integer.parseInt(strid));
Article article = null;
if(!listA.isEmpty() && listA.size()>0){
for(int i = 0;i<listA.size();i++){
article = (Article)listA.get(i);
}
}
article.setContent(request.getParameter("content")); //修改文章内容
article.setTypeID(Integer.parseInt(request.getParameter("typeId2"))); //修改文章类型
article.setTitle(request.getParameter("title")); //修改文章题目
geth.updateAri(article);
%>
<script type="text/javascript">
function deleteForm(id){
if(confirm("确定要删除此文章信息吗?")){
window.location.href="aritdele.jsp?id="+id;
}
}
</script>
public void deleAri(Article ariticle) {
Transaction tx = null;
try {
session = hib.openSession(); //调用公共类方法开打Session
tx = (Transaction) session.beginTransaction(); //开启事务
session.delete(ariticle); //执行删除操作
tx.commit(); //提交事务
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
}
<%
String strid = request.getParameter("id"); //获取前台页面的请求参数
Gethibernate geth = new Gethibernate(); //创建Gethibernate对象
List listA = geth.findMain(Integer.parseInt(strid)); //调用findMain()方法获取要修改的文章对象
Article ari = null;
if(!listA.isEmpty() && listA.size()>0){
for(int i= 0;i<listA.size();i++){
ari = (Article)listA.get(i);
geth.deleAri(ari); //执行删除文章对象方法
}
}
%>
public List finAritId(int intid) { //查找指定Id号的文章类型对象
Transaction tx = null; //创建Transaction对象
List list = null; //创建List对象
try {
session = hib.openSession(); //调用公共类方法开启Session
tx = (Transaction) session.beginTransaction(); //开启事务
Query query = session.createQuery("from AriticleType as p where p.id=:intid"); query.setInteger("intid",intid); //动态绑定参数
list = query.list(); //执行HQL语句
tx.commit();
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return list;
}
public List findArity(int aid) { //检索指定文章类型的文章对象
Transaction tx = null;
List list = null;
try {
session = hib.openSession(); //调用公共类方法打开Session
tx = (Transaction) session.beginTransaction();
Query query = session
.createQuery("from Article as c where c.typeID =:aid");
query.setInteger("aid", aid);
list = query.list();
tx.commit();
hib.closeSession(session); //调用公共类方法关闭Session
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
}
return list;
}
<%
String strid = request.getParameter("id");//获取前台页面的请求参数,保存了文章类型对象的id号
Gethibernate geth = new Gethibernate();//创建Gethibernate对象
List listAtype = geth.finAritId(Integer.parseInt(strid));
AriticleType atype = null;
if(!listAtype.isEmpty() && listAtype.size()>0){
for(int i= 0 ;i<listAtype.size();i++){
atype = (AriticleType)listAtype.get(i);
}
}
geth.deleAritype(atype);
List listAtye = geth.findArity(Integer.parseInt(strid));
Article article = null;
if(!listAtye.isEmpty() && listAtye.size() >0 ){
for(int j = 0 ;j < listAtye.size() ;j++){
article = (Article)listAtye.get(j);
}
geth.deleAri(article);
}
%>

 




posted @ 2018-01-26 15:21  姗姗不来迟  阅读(652)  评论(0编辑  收藏  举报

web应用开发&研究 - 创建于 2017年12月24日

这是我的个人站。

致力于对计算机技术的兴趣,希望大家多多交流


Font Awesome | Respond.js | Bootstrap中文网