博客網站開發

1、需求分析:javascript

根據博客網站的特色,並與用戶進行溝通。要求本系統具備如下功能:
一、  統1、友好的操做界面,用以保證系統的易用性。
二、  強大的查詢功能,便於用戶查詢各項信息。
三、  添加評論的功能,以方便用戶對博主發表的文章添加評論。
四、  添加了友情連接,以方便用戶進入其餘網站。
五、  博客文章管理功能,以方便博主添加、修改、刪除博客文章。
六、  公告管理功能,以方便博主添加、修改、刪除公告信息。
七、  日誌管理功能,以方便博主添加、修改、刪除日誌信息。
八、  我的相片設置功能,以方便博主添加、修改、刪除相片功能。
九、  朋友信息管理功能,以方便博主添加、修改、刪除朋友信息。
十、博主信息設置,以方便及時的更新博主信息。java

2、  設計目標

根據博客網站的需求進行開發設計,主要實現以下目標:web

一、         界面設計友好、美觀,數據存儲安全、可靠。sql

二、         強大的查詢功能,方便用戶瀏覽網站信息。數據庫

三、        設置了登陸模塊,保證了網站的數據安全性。數組

四、        實現對博主發表的文章、公告、相片、日誌等信息的添加、修改、刪除功能,便於更新網站內容。瀏覽器

五、        系統最大限度地實現了易維護性和易操做性。緩存

六、         採用人機對話的操做方式,方便用戶的平常操做。安全

3、 開發及運行環境
硬件平臺:
一、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像素。服務器

4、技術準備:

 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>

5、公共類設計

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();
}

6、前臺功能

因爲時間關係網站前臺的一些功能直接給出代碼以下;

<%
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對象方法
%>

7、網站後臺功能界面

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); } %>

相關文章
相關標籤/搜索