
2011年4月14日
1 getCurrentSession創(chuàng)建的session會和綁定到當(dāng)前線程,而openSession每次創(chuàng)建新的session。
2 getCurrentSession創(chuàng)建的線程會在事務(wù)回滾或事物提交后自動關(guān)閉,而openSession必須手動關(guān)閉
這里getCurrentSession本地事務(wù)(本地事務(wù):jdbc)時 要在配置文件里進(jìn)行如下設(shè)置
* 如果使用的是本地事務(wù)(jdbc事務(wù))
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事務(wù)(jta事務(wù))
<property name="hibernate.current_session_context_class">jta</property>
getCurrentSession () 在事務(wù)結(jié)束之前使用當(dāng)前的session
openSession() 每次重新建立一個新的session
在一個應(yīng)用程序中,如果DAO 層使用Spring 的hibernate 模板,通過Spring 來控制session 的生命周期,則首選getCurrentSession ()。
使用Hibernate的大多數(shù)應(yīng)用程序需要某種形式的“上下文相關(guān)的” session,特定的session在整個特定的上下文范圍內(nèi)始終有效。然而,對不同類型的應(yīng)用程序而言,要為什么是組成這種“上下文”下一個定義通常 是困難的;不同的上下文對“當(dāng)前”這個概念定義了不同的范圍。在3.0版本之前,使用Hibernate的程序要么采用自行編寫的基于 ThreadLocal的上下文session,要么采用HibernateUtil這樣的輔助類,要么采用第三方框架(比如Spring或Pico), 它們提供了基于代理(proxy)或者基于攔截器(interception)的上下文相關(guān)session。
從3.0.1版本開 始,Hibernate增加了SessionFactory.getCurrentSession()方法。一開始,它假定了采用JTA事務(wù),JTA事務(wù) 定義了當(dāng)前session的范圍和上下文(scope and context)。Hibernate開發(fā)團(tuán)隊堅信,因為有好幾個獨立的JTA TransactionManager實現(xiàn)穩(wěn)定可用,不論是否被部署到一個J2EE容器中,大多數(shù)(假若不是所有的)應(yīng)用程序都應(yīng)該采用JTA事務(wù)管理。 基于這一點,采用JTA的上下文相關(guān)session可以滿足你一切需要。
更好的是,從3.1開 始,SessionFactory.getCurrentSession()的后臺實現(xiàn)是可拔插的。因此,我們引入了新的擴(kuò)展接口 (org.hibernate.context.CurrentSessionContext)和新的配置參數(shù) (hibernate.current_session_context_class),以便對什么是“當(dāng)前session”的范圍和上下文(scope and context)的定義進(jìn)行拔插。
請參閱 org.hibernate.context.CurrentSessionContext接口的Javadoc,那里有關(guān)于它的契約的詳細(xì)討論。它定義 了單一的方法,currentSession(),特定的實現(xiàn)用它來負(fù)責(zé)跟蹤當(dāng)前的上下文session。Hibernate內(nèi)置了此接口的兩種實現(xiàn)。
org.hibernate.context.JTASessionContext - 當(dāng)前session根據(jù)JTA來跟蹤和界定。這和以前的僅支持JTA的方法是完全一樣的。詳情請參閱Javadoc。
org.hibernate.context.ThreadLocalSessionContext - 當(dāng)前session通過當(dāng)前執(zhí)行的線程來跟蹤和界定。詳情也請參閱Javadoc。
這 兩種實現(xiàn)都提供了“每數(shù)據(jù)庫事務(wù)對應(yīng)一個session”的編程模型,也稱作每次請求一個session。Hibernate session的起始和終結(jié)由數(shù)據(jù)庫事務(wù)的生存來控制。假若你采用自行編寫代碼來管理事務(wù)(比如,在純粹的J2SE,或者 JTA/UserTransaction/BMT),建議你使用Hibernate Transaction API來把底層事務(wù)實現(xiàn)從你的代碼中隱藏掉。如果你在支持CMT的EJB容器中執(zhí)行,事務(wù)邊界是聲明式定義的,你不需要在代碼中進(jìn)行任何事務(wù)或 session管理操作。請參閱第 11 章 事務(wù)和并發(fā)一節(jié)來閱讀更多的內(nèi)容和示例代碼。
hibernate.current_session_context_class 配置參數(shù)定義了應(yīng)該采用哪個org.hibernate.context.CurrentSessionContext實現(xiàn)。注意,為了向下兼容,如果未 配置此參數(shù),但是存在org.hibernate.transaction.TransactionManagerLookup的配 置,Hibernate會采用org.hibernate.context.JTASessionContext。一般而言,此參數(shù)的值指明了要使用的實 現(xiàn)類的全名,但那兩個內(nèi)置的實現(xiàn)可以使用簡寫,即"jta"和"thread"。
1、getCurrentSession()與openSession()的區(qū)別?
* 采用getCurrentSession()創(chuàng)建的session會綁定到當(dāng)前線程中,而采用openSession()
創(chuàng)建的session則不會
* 采用getCurrentSession()創(chuàng)建的session在commit或rollback時會自動關(guān)閉,而采用openSession()
創(chuàng)建的session必須手動關(guān)閉
2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
* 如果使用的是本地事務(wù)(jdbc事務(wù))
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事務(wù)(jta事務(wù))
<property name="hibernate.current_session_context_class">jta</property>
利于ThreadLocal模式管理Session
早在Java1.2推出之時,Java平臺中就引入了一個新的支持:java.lang.ThreadLocal,給我們在編寫多線程程序
時提供了一種新的選擇。ThreadLocal是什么呢?其實ThreadLocal并非是一個線程的本地實現(xiàn)版本,它并不是一個Thread,
而是thread local variable(線程局部變量)。也許把它命名為ThreadLocalVar更加合適。線程局部變量(ThreadLocal)
其實的功用非常簡單,就是為每一個使用某變量的線程都提供一個該變量值的副本,是每一個線程都可以獨立地改變自己的副本,
而不會和其它線程的副本沖突。從線程的角度看,就好像每一個線程都完全擁有一個該變量。
ThreadLocal是如何做到為每一個線程維護(hù)變量的副本的呢?其實實現(xiàn)的思路很簡單,在ThreadLocal類中有一個Map,
用于存儲每一個線程的變量的副本。比如下面的示例實現(xiàn)(為了簡單,沒有考慮集合的泛型):
public class HibernateUtil {
public static final ThreadLocal session =new ThreadLocal();
public static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session currentSession() throws HibernateException {
Session s = session.get();
if(s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = session.get();
if(s != null) {
s.close();
}
session.set(null);
}
}
在這里比較了下getCurrentSession()是否是用的是同一個session...............
package com.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class HibernateIDTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass() {
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testTeacherSave() {
System.out.println("------------");
Teacher t = new Teacher();
t.setId(1);
t.setName("t1");
t.setTitle("middle");
t.setBirthDate(new Date());
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
Session session2 = sessionFactory.getCurrentSession();
System.out.println("比較"+(session.hashCode()==session2.hashCode()));
}
}
執(zhí)行之后不的到結(jié)果是 session.hashCode()==session2.hashCode()這兩個只是false的,也就是說,在事務(wù)結(jié)束之后getCuttentSession 也是創(chuàng)建了新的session。。。。。。
openSession() 與 getCurrentSession() 有何不同和關(guān)聯(lián)呢?
在 SessionFactory 啟動的時候, Hibernate 會根據(jù)配置創(chuàng)建相應(yīng)的 CurrentSessionContext ,在 getCurrentSession() 被調(diào)用的時候,實際被執(zhí)行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 執(zhí)行時,如果當(dāng)前 Session 為空, currentSession 會調(diào)用 SessionFactory 的 openSession 。所以 getCurrentSession() 對于 Java EE 來說是更好的獲取 Session 的方法。
posted @
2011-04-14 10:46 龍ぜ?xì)垊?閱讀(5688) |
評論 (1) |
編輯 收藏

2011年3月6日
jfreechart主要是用來動態(tài)產(chǎn)生各種數(shù)據(jù)圖形的,可最初使用的時候大都會碰到圖片中的中文亂碼或是一個小方塊的情況。
仔細(xì)研究主要有以下2種原因:
1:服務(wù)器缺少中文字體,這多發(fā)生在Hp等unix操作系統(tǒng)上,解決的方法就是下載可用字體庫到系統(tǒng)中,
有人也提出在Windows上產(chǎn)生圖片在傳回到Unix主機(jī)上的方法。
2:軟件版本問題,jfreechart-1.0.10有人說沒有問題,但jfreechart-1.0.11到13都有問題,我用的最新的jfreechart-1.0.13不做設(shè)置是有問題的。
究其原因,是它代碼的內(nèi)部設(shè)置的字體有問題.
其下是具體的解決辦法:
public static void configFont(JFreeChart chart){
// 設(shè)置字體
Font xfont = new Font("宋體",Font.PLAIN,12) ;// X軸
Font yfont = new Font("宋體",Font.PLAIN,12) ;// Y軸
Font kfont = new Font("宋體",Font.PLAIN,12) ;// 底部
Font titleFont = new Font("隸書", Font.BOLD , 25) ; // 圖片標(biāo)題
CategoryPlot plot = chart.getCategoryPlot();// 圖形的繪制結(jié)構(gòu)對象
// 圖片標(biāo)題
chart.setTitle(new TextTitle(chart.getTitle().getText(),titleFont));
// 底部
chart.getLegend().setItemFont(kfont);
// X 軸
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(xfont);// 軸標(biāo)題
domainAxis.setTickLabelFont(xfont);// 軸數(shù)值
domainAxis.setTickLabelPaint(Color.BLUE) ; // 字體顏色
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 橫軸上的label斜顯示
// Y 軸
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(yfont);
rangeAxis.setLabelPaint(Color.BLUE) ; // 字體顏色
rangeAxis.setTickLabelFont(yfont);
}
posted @
2011-03-06 22:47 龍ぜ?xì)垊?閱讀(553) |
評論 (0) |
編輯 收藏
JFreeChart項目簡介
JFreeChart是開放源代碼站點SourceForge.net上的一個JAVA項目,它主要用來各種各樣的圖表,這些圖表包括:餅圖、柱狀圖(普 通柱狀圖以及堆棧柱狀圖)、線圖、區(qū)域圖、分布圖、混合圖、甘特圖以及一些儀表盤等等。這些不同式樣的圖表基本上可以滿足目前的要求。為了減少篇幅本文主 要介紹前面三種類型的圖表,讀者可以觸類旁通去開發(fā)其他樣式的圖表。
這里有點筆者在開發(fā)中遇見的問題需要注意的是:在使用Eclipse開發(fā)的時候會報一個莫名其妙的錯誤,錯誤可能指向某個類文件的第一行。遇到這樣的問題一般是因為沒有把Jcommon的jar包設(shè)置到項目的類路徑中的緣故。具體的原因不祥。
1 餅圖
對于餅圖而言,數(shù)據(jù)集的獲取用的不是同一個數(shù)據(jù)集類,另外餅圖不支持同一個類別的項目中還有子項目這樣的數(shù)據(jù)。我們只給出創(chuàng)建餅圖的代碼,至于寫圖表到一個文件則與柱狀圖一致,無需重復(fù)..
實例代碼如下:
package com.dr.demo;
import java.awt.Color;
import java.awt.Font;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
/**
*
* @author 詹成榜
* @date 2010-2-25
* @ClassName PolyLine.java
* @Email 289153044@qq.com
* @param 餅圖
* @param
*/
public class SalesCountServlet {
protected static void doGet() {
System.out.println("圖表已經(jīng)建立!");
CategoryDataset dataset = getDataSet();
String fileName = "SalesCount.jpg";//文件名稱
JFreeChart chart = ChartFactory.createBarChart3D("產(chǎn)品銷量圖", // 圖表標(biāo)題
"產(chǎn)品", // 目錄軸的顯示標(biāo)簽
"銷量", // 數(shù)值軸的顯示標(biāo)簽
dataset, // 數(shù)據(jù)集
PlotOrientation.VERTICAL, // 圖表方向:水平、垂直
true, // 是否顯示圖例(對于簡單的柱狀圖必須是false)
false, // 是否生成工具
false // 是否生成URL鏈接
);
configFont(chart);//設(shè)置中文格式
FileOutputStream fos_jpg = null;
try {
String statImagePath = "d:";//存放文件的路徑
try {
fos_jpg = new FileOutputStream(statImagePath+ fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
ChartUtilities.writeChartAsJPEG(fos_jpg, 0.5f, chart, 400, 300,null);
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
fos_jpg.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void configFont(JFreeChart chart){
// 配置字體
Font xfont = new Font("宋體",Font.PLAIN,12) ;// X軸
Font yfont = new Font("宋體",Font.PLAIN,12) ;// Y軸
Font kfont = new Font("宋體",Font.PLAIN,12) ;// 底部
Font titleFont = new Font("隸書", Font.BOLD , 25) ; // 圖片標(biāo)題
CategoryPlot plot = chart.getCategoryPlot();// 圖形的繪制結(jié)構(gòu)對象
// 圖片標(biāo)題
chart.setTitle(new TextTitle(chart.getTitle().getText(),titleFont));
// 底部
chart.getLegend().setItemFont(kfont);
// X 軸
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(xfont);// 軸標(biāo)題
domainAxis.setTickLabelFont(xfont);// 軸數(shù)值
domainAxis.setTickLabelPaint(Color.BLUE) ; // 字體顏色
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 橫軸上的label斜顯示
// Y 軸
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(yfont);
rangeAxis.setLabelPaint(Color.BLUE) ; // 字體顏色
rangeAxis.setTickLabelFont(yfont);
}
private static CategoryDataset getDataSet() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(20, "銷售圖表", "蘋果");
dataset.addValue(20, "銷售圖表", "梨");
dataset.addValue(30, "銷售圖表", "香蕉");
dataset.addValue(40, "銷售圖表", "葡萄");
dataset.addValue(50, "銷售圖表", "桔子");
return dataset;
}
public static void main(String args[]){
doGet();
}
}
posted @
2011-03-06 22:36 龍ぜ?xì)垊?閱讀(421) |
評論 (3) |
編輯 收藏
hibernate工作原理
原理:
1.讀取并解析配置文件
2.讀取并解析映射信息,創(chuàng)建SessionFactory
3.打開Sesssion
4.創(chuàng)建事務(wù)Transation
5.持久化操作
6.提交事務(wù)
7.關(guān)閉Session
8.關(guān)閉SesstionFactory
為什么要用:
1. 對JDBC訪問數(shù)據(jù)庫的代碼做了封裝,大大簡化了數(shù)據(jù)訪問層繁瑣的重復(fù)性代碼。
2. Hibernate是一個基于JDBC的主流持久化框架,是一個優(yōu)秀的ORM實現(xiàn)。他很大程度的簡化DAO層的編碼工作
3. hibernate使用Java反射機(jī)制,而不是字節(jié)碼增強(qiáng)程序來實現(xiàn)透明性。
4. hibernate的性能非常好,因為它是個輕量級框架。映射的靈活性很出色。它支持各種關(guān)系數(shù)據(jù)庫,從一對一到多對多的各種復(fù)雜關(guān)系。
2. Hibernate是如何延遲加載?
1. Hibernate2延遲加載實現(xiàn):a)實體對象 b)集合(Collection)
2. Hibernate3 提供了屬性的延遲加載功能
當(dāng)Hibernate在查詢數(shù)據(jù)的時候,數(shù)據(jù)并沒有存在與內(nèi)存中,當(dāng)程序真正對數(shù)據(jù)的操作時,對象才存在與內(nèi)存中,就實現(xiàn)了延遲加載,他節(jié)省了服務(wù)器的內(nèi)存開銷,從而提高了服務(wù)器的性能。
3.Hibernate中怎樣實現(xiàn)類之間的關(guān)系?(如:一對多、多對多的關(guān)系)
類與類之間的關(guān)系主要體現(xiàn)在表與表之間的關(guān)系進(jìn)行操作,它們都市對對象進(jìn)行操作,我們程序中把所有的表與類都映射在一起,它們通過配置文件中的many-to-one、one-to-many、many-to-many、
4. 說下Hibernate的緩存機(jī)制
1. 內(nèi)部緩存存在Hibernate中又叫一級緩存,屬于應(yīng)用事物級緩存
2. 二級緩存:
a) 應(yīng)用及緩存
b) 分布式緩存
條件:數(shù)據(jù)不會被第三方修改、數(shù)據(jù)大小在可接受范圍、數(shù)據(jù)更新頻率低、同一數(shù)據(jù)被系統(tǒng)頻繁使用、非 關(guān)鍵數(shù)據(jù)
c) 第三方緩存的實現(xiàn)
5. Hibernate的查詢方式
Sql、Criteria,object comptosition
Hql:
1、 屬性查詢
2、 參數(shù)查詢、命名參數(shù)查詢
3、 關(guān)聯(lián)查詢
4、 分頁查詢
5、 統(tǒng)計函數(shù)
6. 如何優(yōu)化Hibernate?
1.使用雙向一對多關(guān)聯(lián),不使用單向一對多
2.靈活使用單向一對多關(guān)聯(lián)
3.不用一對一,用多對一取代
4.配置對象緩存,不使用集合緩存
5.一對多集合使用Bag,多對多集合使用Set
6. 繼承類使用顯式多態(tài)
7. 表字段要少,表關(guān)聯(lián)不要怕多,有二級緩存撐
spring工作原理
1.spring mvc請所有的請求都提交給DispatcherServlet,它會委托應(yīng)用系統(tǒng)的其他模塊負(fù)責(zé)負(fù)責(zé)對請求進(jìn)行真正的處理工作。
2.DispatcherServlet查詢一個或多個HandlerMapping,找到處理請求的Controller.
3.DispatcherServlet請請求提交到目標(biāo)Controller
4.Controller進(jìn)行業(yè)務(wù)邏輯處理后,會返回一個ModelAndView
5.Dispathcher查詢一個或多個ViewResolver視圖解析器,找到ModelAndView對象指定的視圖對象
6.視圖對象負(fù)責(zé)渲染返回給客戶端。
為什么用:
{AOP 讓開發(fā)人員可以創(chuàng)建非行為性的關(guān)注點,稱為橫切關(guān)注點,并將它們插入到應(yīng)用程序代碼中。使用 AOP 后,公共服務(wù) (比如日志、持久性、事務(wù)等)就可以分解成方面并應(yīng)用到域?qū)ο笊希瑫r不會增加域?qū)ο蟮膶ο竽P偷膹?fù)雜性。
IOC 允許創(chuàng)建一個可以構(gòu)造對象的應(yīng)用環(huán)境,然后向這些對象傳遞它們的協(xié)作對象。正如單詞 倒置 所表明的,IOC 就像反 過來的 JNDI。沒有使用一堆抽象工廠、服務(wù)定位器、單元素(singleton)和直接構(gòu)造(straight construction),每一個對象都是用其協(xié)作對象構(gòu)造的。因此是由容器管理協(xié)作對象(collaborator)。
Spring即使一個AOP框架,也是一IOC容器。 Spring 最好的地方是它有助于您替換對象。有了 Spring,只要用 JavaBean 屬性和配置文件加入依賴性(協(xié)作對象)。然后可以很容易地在需要時替換具有類似接口的協(xié)作對象。}
Spring 框架是一個分層架構(gòu),由 7 個定義良好的模塊組成。Spring 模塊構(gòu)建在核心容器之上,核心容器定義了創(chuàng)建、配置和管理 bean 的方式,如圖 1 所示。
組成 Spring 框架的每個模塊(或組件)都可以單獨存在,或者與其他一個或多個模塊聯(lián)合實現(xiàn)。每個模塊的功能如下:
☆ 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要組件是 BeanFactory,它是工廠模式的實現(xiàn)。BeanFactory 使用控制反轉(zhuǎn) (IOC)模式將應(yīng)用程序的配置和依賴性規(guī)范與實際的應(yīng)用程序代碼分開。
☆ Spring 上下文:Spring 上下文是一個配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企業(yè)服務(wù),例如 JNDI、EJB、電子郵件、國際化、校驗和調(diào)度功能。
☆ Spring AOP:通過配置管理特性,Spring AOP 模塊直接將面向方面的編程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何對象支持 AOP。Spring AOP 模塊為基于 Spring 的應(yīng)用程序中的對象提供了事務(wù)管理服務(wù)。通過使用 Spring AOP,不用依賴 EJB 組件,就可以將聲明性事務(wù)管理集成到應(yīng)用程序中。
☆ Spring DAO:JDBC DAO 抽象層提供了有意義的異常層次結(jié)構(gòu),可用該結(jié)構(gòu)來管理異常處理和不同數(shù)據(jù)庫供應(yīng)商拋出的錯誤消息。異常層次結(jié)構(gòu)簡化了錯誤處理,并且極大地降低了需要編寫的異常代碼數(shù)量(例如打開和關(guān)閉連接)。Spring DAO 的面向 JDBC 的異常遵從通用的 DAO 異常層次結(jié)構(gòu)。
☆ Spring ORM:Spring 框架插入了若干個 ORM 框架,從而提供了 ORM 的對象關(guān)系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有這些都遵從 Spring 的通用事務(wù)和 DAO 異常層次結(jié)構(gòu)。
☆ Spring Web 模塊:Web 上下文模塊建立在應(yīng)用程序上下文模塊之上,為基于 Web 的應(yīng)用程序提供了上下文。所以,Spring 框架支持與 Jakarta Struts 的集成。Web 模塊還簡化了處理多部分請求以及將請求參數(shù)綁定到域?qū)ο蟮墓ぷ鳌?br />
☆ Spring MVC 框架:MVC 框架是一個全功能的構(gòu)建 Web 應(yīng)用程序的 MVC 實現(xiàn)。通過策略接口,MVC 框架變成為高度可配置的,MVC 容納了大量視圖技術(shù),其中包括 JSP、Velocity、Tiles、iText 和 POI。
Spring 框架的功能可以用在任何 J2EE 服務(wù)器中,大多數(shù)功能也適用于不受管理的環(huán)境。Spring 的核心要點是:支持不綁定到特定 J2EE 服務(wù)的可重用業(yè)務(wù)和數(shù)據(jù)訪問對象。毫無疑問,這樣的對象可以在不同 J2EE 環(huán)境 (Web 或 EJB)、獨立應(yīng)用程序、測試環(huán)境之間重用。
IOC 和 AOP
控制反轉(zhuǎn)模式(也稱作依賴性介入)的基本概念是:不創(chuàng)建對象,但是描述創(chuàng)建它們的方式。在代碼中不直接與對象和服務(wù)連接,但在配置文件中描述哪一個組件需要哪一項服務(wù)。容器(在 Spring 框架中是 IOC 容器) 負(fù)責(zé)將這些聯(lián)系在一起。
在典型的 IOC 場景中,容器創(chuàng)建了所有對象,并設(shè)置必要的屬性將它們連接在一起,決定什么時間調(diào)用方法。下表列出了 IOC 的一個實現(xiàn)模式。
struts工作原理
Struts工作機(jī)制?為什么要使用Struts?
工作機(jī)制:
Struts的工作流程:
在web應(yīng)用啟動時就會加載初始化ActionServlet,ActionServlet從
struts-config.xml文件中讀取配置信息,把它們存放到各種配置對象
當(dāng)ActionServlet接收到一個客戶請求時,將執(zhí)行如下流程.
-(1)檢索和用戶請求匹配的ActionMapping實例,如果不存在,就返回請求路徑無效信息;
-(2)如果ActionForm實例不存在,就創(chuàng)建一個ActionForm對象,把客戶提交的表單數(shù)據(jù)保存到ActionForm對象中;
-(3)根據(jù)配置信息決定是否需要表單驗證.如果需要驗證,就調(diào)用ActionForm的validate()方法;
-(4)如果ActionForm的validate()方法返回null或返回一個不包含ActionMessage的ActuibErrors對象, 就表示表單驗證成功;
-(5)ActionServlet根據(jù)ActionMapping所包含的映射信息決定將請求轉(zhuǎn)發(fā)給哪個Action,如果相應(yīng)的 Action實例不存在,就先創(chuàng)建這個實例,然后調(diào)用Action的execute()方法;
-(6)Action的execute()方法返回一個ActionForward對象,ActionServlet在把客戶請求轉(zhuǎn)發(fā)給 ActionForward對象指向的JSP組件;
-(7)ActionForward對象指向JSP組件生成動態(tài)網(wǎng)頁,返回給客戶;
為什么要用:
JSP、Servlet、JavaBean技術(shù)的出現(xiàn)給我們構(gòu)建強(qiáng)大的企業(yè)應(yīng)用系統(tǒng)提供了可能。但用這些技術(shù)構(gòu)建的系統(tǒng)非常的繁亂,所以在此之上,我們需要一個規(guī)則、一個把這些技術(shù)組織起來的規(guī)則,這就是框架,Struts便應(yīng)運而生。
基于Struts開發(fā)的應(yīng)用由3類組件構(gòu)成:控制器組件、模型組件、視圖組件
8. Struts的validate框架是如何驗證的?
在struts配置文件中配置具體的錯誤提示,再在FormBean中的validate()方法具體調(diào)用。
9. 說下Struts的設(shè)計模式
MVC模式: web應(yīng)用程序啟動時就會加載并初始化ActionServler。用戶提交表單時,一個配置好的ActionForm對象被創(chuàng)建,并被填入表單相應(yīng)的數(shù)據(jù),ActionServler根據(jù)Struts-config.xml文件配置好的設(shè)置決定是否需要表單驗證,如果需要就調(diào)用ActionForm的 Validate()驗證后選擇將請求發(fā)送到哪個Action,如果Action不存在,ActionServlet會先創(chuàng)建這個對象,然后調(diào)用 Action的execute()方法。Execute()從ActionForm對象中獲取數(shù)據(jù),完成業(yè)務(wù)邏輯,返回一個ActionForward對象,ActionServlet再把客戶請求轉(zhuǎn)發(fā)給ActionForward對象指定的jsp組件,ActionForward對象指定的jsp生成動態(tài)的網(wǎng)頁,返回給客戶。
posted @
2011-03-06 19:59 龍ぜ?xì)垊?閱讀(458) |
評論 (0) |
編輯 收藏

2011年3月5日
Spring 是一個開源框架,是為了解決企業(yè)應(yīng)用程序開發(fā)復(fù)雜性而創(chuàng)建的。框架的主要優(yōu)勢之一就是其分層架構(gòu),分層架構(gòu)允許您選擇使用哪一個組件,同時為 J2EE 應(yīng)用程序開發(fā)提供集成的框架。
☆
核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要組件是 BeanFactory,它是工廠模式的實現(xiàn)。BeanFactory 使用控制反轉(zhuǎn) (IOC) 模式將應(yīng)用程序的配置和依賴性規(guī)范與實際的應(yīng)用程序代碼分開。
☆
Spring 上下文:Spring 上下文是一個配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企業(yè)服務(wù),例如 JNDI、EJB、電子郵件、國際化、校驗和調(diào)度功能。
☆
Spring AOP:通過配置管理特性,Spring AOP 模塊直接將面向方面的編程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何對象支持 AOP。Spring AOP 模塊為基于 Spring 的應(yīng)用程序中的對象提供了事務(wù)管理服務(wù)。通過使用 Spring AOP,不用依賴 EJB 組件,就可以將聲明性事務(wù)管理集成到應(yīng)用程序中。
在此 我做了個小demo 基于Spring的核心Ioc(inversion of control) 與面向切面編程AOP(Aspect Oriented Programming)。。。。。
這個例子主要完成的義務(wù)邏輯是對信息的保存,主要代碼如下:
package com.dr.service;
import com.dr.DAO.ProductDAO;
import com.dr.model.Product;
public class ProductService {
private ProductDAO productDAO;
public void add(Product product){
productDAO.save(product);
}
public ProductService(ProductDAO productDAO){
super();
System.out.println("ProductServic :ProductService");
this.productDAO = productDAO;
}
}
DAO層代碼如下:
package com.dr.DAO;
import com.dr.model.Product;
public interface ProductDAO {
public void save(Product product);
}
package com.dr.DAO.impl;
import com.dr.DAO.ProductDAO;
import com.dr.model.Product;
public class ProductDAOImpl implements ProductDAO {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("ProductDAOImple :setName");
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
System.out.println("ProductDAOImpl :setId");
this.id = id;
}
public void save(Product product) {
//Hibernate
//JDBC
//XML
//NetWork
System.out.println("ProductDAOImpl :save :product saved!");
this.toString();
}
public String toString(){
System.out.println("id:"+id+"|name:"+name);
return null;
}
}
beans.xml部分代碼:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="p" class="com.dr.DAO.impl.ProductDAOImpl">
<!--采用 setter()方法依賴注入-->
<property name="name" value="11"></property>
<property name="id" value="22"></property>
</bean>
<bean id="productService" class="com.dr.service.ProductService">
<constructor-arg>
<ref bean="p"/>
</constructor-arg>
</bean>
</beans>
測試類的代碼如下所示:
package com.dr.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dr.model.Product;
import com.dr.service.ProductService;
//Dependency Injection 依賴注入
//Inverse of Control 控制反轉(zhuǎn)
public class ProductServiceTest {
@Test
public void testAdd() throws Exception {
//實例化應(yīng)用上下文,Xml類路徑應(yīng)用上下文
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//getBean() 所得到得對象是Object類型的,所有在此必須強(qiáng)制轉(zhuǎn)換。。。
ProductService service = (ProductService) ctx.getBean("productService");
Product product = new Product();
product.toString();
product.setId(20);
product.setName("蘋果");
service.add(product);
}
}
posted @
2011-03-05 21:49 龍ぜ?xì)垊?閱讀(2722) |
評論 (0) |
編輯 收藏

2011年3月4日
用Java程序
現(xiàn)在許多網(wǎng)站都必須統(tǒng)計瀏覽量,在此為了記錄當(dāng)前在線人數(shù),我設(shè)計了一個計數(shù)器。其功能是:計數(shù)器就將自動加一,離開時就自動減一。。
這里就做了個很小的
demo:
Java 代碼如下:
package com.dr.demo2.servlet;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.log4j.Logger;
public class SessionCounter implements HttpSessionListener,
ServletRequestListener {
private static Logger log = Logger.getLogger(SessionCounter.class);
private static final String CONTENT_TYPE = "text/html; charset=GBK";
private static int activeSessions = 0;// 當(dāng)前活動的人數(shù)
private HttpServletRequest request;
private static ArrayList list = new ArrayList();// 用來存放不同ip的地址
public void init() throws ServletException {
log.info("SessionCounter init!");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info("SessionCounter doGet!");
response.setContentType(CONTENT_TYPE);
HttpSession session = request.getSession();
}
public void destroy() {
log.info("SessionCounter destroy!");
}
public void requestDestroyed(ServletRequestEvent event) {
// To change body of implemented methods use File | Settings | File
// Templates.
log.info("SessionCounter requestDestroyed!");
}
public void requestInitialized(ServletRequestEvent sre) {
request = (HttpServletRequest) sre.getServletRequest();
log.info("SessionCounter requestInitialized!");
}
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
log.info("SessionCounter sessionCreater!");
String sessionId = httpSessionEvent.getSession().getId();
Timestamp createTime = new Timestamp(System.currentTimeMillis());
String loginIp = request.getRemoteAddr();
boolean rs = true;
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (loginIp.equals(list.get(i))) {
rs = false;
}
}
}
if (rs) { // 如果隊列中存在相同的IP 則SESSION不增加
list.add(loginIp);
log.info("ipList隊列新增ip: " + loginIp);
activeSessions++;
log.info("新增SESSION,sessionId = " + sessionId + "; createTime = "
+ createTime + "; loginIp = " + loginIp + "; 當(dāng)前總SESSION值為 "
+ activeSessions);
}
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
log.info("SessionCounter sessionDestroyed!");
String sessionId = httpSessionEvent.getSession().getId();
Timestamp overTime = new Timestamp(System.currentTimeMillis());
String loginIp = request.getRemoteAddr();
if (activeSessions > 0) {
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (loginIp.equals(list.get(i))) {
list.remove(i);
log.info("ipList隊列移除ip: " + loginIp);
}
}
}
activeSessions--; // 在用戶銷毀的時候,從隊列中踢出這個IP
log.info("銷毀SESSION,sessionId = " + sessionId + "; overTime = "
+ overTime + "; loginIp = " + loginIp + "; 當(dāng)前總SESSION值為 "
+ activeSessions);
}
}
public static int getActiveSessions() {
log.info("SessionCounter getActiveSessions!");
return activeSessions;
}
public void setActiveSessions(int i) {
log.info("SessionCounter setActiveSessions!");
activeSessions = i;
}
}
jsp 部分代碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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 'online.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">
-->
</head>
<body>
<%@ page import= "com.dr.demo2.servlet.SessionCounter" %>
在線: <%= SessionCounter.getActiveSessions() %>人
</body>
</html>
啟動tomcat ,在瀏覽器中輸入:http://127.0.0.1:8080/OnlineCount/online.jsp
執(zhí)行效果如下:
posted @
2011-03-04 09:12 龍ぜ?xì)垊?閱讀(1130) |
評論 (0) |
編輯 收藏

2011年3月3日
首先我 用一種比較簡單的方法,做了個小小的demo,但是這種方法用的的是Spring 框架來完成的,因為使用這種方法是一種比較實用的方法,由于很多的代碼被Spring 封裝在最底層。。具體的源代碼如下:
Java 代碼:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
JavaMailSender mailSender= (JavaMailSender) context.getBean("mailSender");
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom("avasd@126.com");
mail.setTo("abcd@gmail.com");
mail.setSubject(" 測試Mail 程序");
mail.setText("這里是發(fā)送的內(nèi)容");
mailSender.send(mail);
}
}
配置文件中的主要代碼如下:
Spring-Mail.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.126.com" />
<property name="port" value="25" />
<property name="username" value="avasd@126.com" />
<property name="password" value="你的密碼" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
</beans>
在此用純Java代碼做了個小demo來發(fā)送電子郵件:
package com.cmcc.mail;
/**
* 發(fā)送郵件需要使用的基本信息
*/
import java.util.Properties;
public class MailSenderInfo {
// 發(fā)送郵件的服務(wù)器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 郵件發(fā)送者的地址
private String fromAddress;
// 郵件接收者的地址
private String toAddress;
// 登陸郵件發(fā)送服務(wù)器的用戶名和密碼
private String userName;
private String password;
// 是否需要身份驗證
private boolean validate = false;
// 郵件主題
private String subject;
// 郵件的文本內(nèi)容
private String content;
// 郵件附件的文件名
private String[] attachFileNames;
/**
* 獲得郵件會話屬性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}
package com.cmcc.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* 簡單郵件(不帶附件的郵件)發(fā)送器
*/
public class SimpleMailSender {
/**
* 以文本格式發(fā)送郵件
* @param mailInfo 待發(fā)送的郵件的信息
*/
public boolean sendTextMail(MailSenderInfo mailInfo) {
// 判斷是否需要身份認(rèn)證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份認(rèn)證,則創(chuàng)建一個密碼驗證器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據(jù)郵件會話屬性和密碼驗證器構(gòu)造一個發(fā)送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據(jù)session創(chuàng)建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創(chuàng)建郵件發(fā)送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設(shè)置郵件消息的發(fā)送者
mailMessage.setFrom(from);
// 創(chuàng)建郵件的接收者地址,并設(shè)置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設(shè)置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設(shè)置郵件消息發(fā)送的時間
mailMessage.setSentDate(new Date());
// 設(shè)置郵件消息的主要內(nèi)容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// 發(fā)送郵件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
/**
* 以HTML格式發(fā)送郵件
* @param mailInfo 待發(fā)送的郵件信息
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// 判斷是否需要身份認(rèn)證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份認(rèn)證,則創(chuàng)建一個密碼驗證器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據(jù)郵件會話屬性和密碼驗證器構(gòu)造一個發(fā)送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據(jù)session創(chuàng)建一個郵件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 創(chuàng)建郵件發(fā)送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 設(shè)置郵件消息的發(fā)送者
mailMessage.setFrom(from);
// 創(chuàng)建郵件的接收者地址,并設(shè)置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO屬性表示接收者的類型為TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設(shè)置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設(shè)置郵件消息發(fā)送的時間
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
Multipart mainPart = new MimeMultipart();
// 創(chuàng)建一個包含HTML內(nèi)容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 設(shè)置HTML內(nèi)容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 將MiniMultipart對象設(shè)置為郵件內(nèi)容
mailMessage.setContent(mainPart);
// 發(fā)送郵件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}
測試程序如下:
package com.cmcc.mail;
/*****************************************************
*
* @author 詹成榜 *
* @since 2011-3-3 *
*****************************************************/
public class TestMail {
public static void main(String[] args){
//這個類主要是設(shè)置郵件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("smtp.126.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("郵箱號@126.com");
mailInfo.setPassword("郵箱密碼");//您的郵箱密碼
mailInfo.setFromAddress("good_hans@126.com");
mailInfo.setToAddress("656426515@qq.com");
mailInfo.setSubject("計算中心北調(diào)課通知單");
String content = "";
String header = "尊敬的"+"aa 老師:\n"+
"您好!\n"+
"這是一封計算中心(北)智能排課平臺自動給您發(fā)送的機(jī)房課程通知單,請您按照下表的相應(yīng)的時間通知學(xué)生到相應(yīng)的機(jī)房上課\n"+
"謝謝您的支持,您的滿意是我們計算中心最大的快樂!\n"+
"如果您對課表有任何疑問,請您撥打0315-2792027\n";
content += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"+
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
"<head>\n" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n" +
// "<!--[if IE]><link href='/css/fkie.css' rel='stylesheet' type='text/css' media='all' /><![endif]-->\n" +
"<style type=\"text/css\">\n" +
"<!--\n"+
"html{border:0;height:100%;border:0;}\n" +
"body{margin:0;padding:0;height:100%;font:12px/120% Arial, Helvetica, sans-serif; text-align:left;}\n" +
"#main{ padding:15px 25px 15px 10px;}\n" +
".tables{ background:#b2bac5; width:100%; margin:1px 0;}\n"+
".tables caption{background:#e5e8ed; padding:1px 0 0 0; _border-bottom:solid 3px #fff; height:26px;}\n"+
".tables th{text-align:center;background:#eef7e2; color:#016bb7; font-weight: normal; line-height:22px;}\n"+
".tables tr{ background:#fff;}\n"+
".tables tr td{line-height:22px;}\n"+
".area-contrl{background:#e5e8ed; padding:1px 0 0 0; _border-bottom:solid 3px #fff; height:26px;}\n" +
"-->\n"+
"</style>\n" +
"</head>\n" +
"<body>\n" +
"<div id=\"main\">\n" +
"<div class=\"area-contrl\">\n" +
"<table class='tables' border='0' cellpadding='3' cellspacing='1'><tr><th width='35'>周次</th><th width='35'>星期</th><th width='35'>講次</th><th width='180'>機(jī)房</th><th width='50'>人數(shù)</th><th width='100'>任課教師</th><th width='200'>班級</th><th width='300'>課程名稱</th></tr>\n"
+"<tr><td align='center'>aaa</td><td align='center'>bbb</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>eee</td><td align='center'>fff</td></tr>\n"
+"<tr><td align='center'>aaa</td><td align='center'>bbb</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>eee</td><td align='center'>fff</td></tr>\n"
+"<tr><td align='center'>aaa</td><td align='center'>bbb</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>eee</td><td align='center'>fff</td></tr>\n"
+"<tr><td align='center'>aaa</td><td align='center'>bbb</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>ccc</td><td align='center'>ddd</td><td align='center'>eee</td><td align='center'>fff</td></tr>";
content += "</table></div></div></body></html>";
System.out.println(content);
mailInfo.setContent(content);
//這個類主要來發(fā)送郵件
SimpleMailSender sms = new SimpleMailSender();
// sms.sendTextMail(mailInfo);//發(fā)送文體格式
sms.sendHtmlMail(mailInfo);//發(fā)送html格式
}
}
posted @
2011-03-03 13:47 龍ぜ?xì)垊?閱讀(1659) |
評論 (0) |
編輯 收藏

2011年3月2日
jQuery確實是一個挺好的輕量級的JS框架,能幫助我們快速的開發(fā)JS應(yīng)用,并在一定程度上改變了我們寫JavaScript代碼的習(xí)慣。
廢話少說,直接進(jìn)入正題,我們先來看一些簡單的方法,這些方法都是對jQuery.ajax()進(jìn)行封裝以方便我們使用的方法,當(dāng)然,如果要處理復(fù)雜的邏輯,還是需要用到j(luò)Query.ajax()的(這個后面會說到).
1. load( url, [data], [callback] ) :載入遠(yuǎn)程 HTML 文件代碼并插入至 DOM 中。
url (String) : 請求的HTML頁的URL地址。
data (Map) : (可選參數(shù)) 發(fā)送至服務(wù)器的 key/value 數(shù)據(jù)。
callback (Callback) : (可選參數(shù)) 請求完成時(不需要是success的)的回調(diào)函數(shù)。
這個方法默認(rèn)使用 GET 方式來傳遞的,如果[data]參數(shù)有傳遞數(shù)據(jù)進(jìn)去,就會自動轉(zhuǎn)換為POST方式的。jQuery 1.2 中,可以指定選擇符,來篩選載入的 HTML 文檔,DOM 中將僅插入篩選出的 HTML 代碼。語法形如 "url #some > selector"。
這個方法可以很方便的動態(tài)加載一些HTML文件,例如表單。
2. jQuery.get( url, [data], [callback] ):使用GET方式來進(jìn)行異步請求
參數(shù):
url (String) : 發(fā)送請求的URL地址.
data (Map) : (可選) 要發(fā)送給服務(wù)器的數(shù)據(jù),以 Key/value 的鍵值對形式表示,會做為QueryString附加到請求URL中。
callback (Function) : (可選) 載入成功時回調(diào)函數(shù)(只有當(dāng)Response的返回狀態(tài)是success才是調(diào)用該方法)。
這是一個簡單的 GET 請求功能以取代復(fù)雜 $.ajax 。請求成功時可調(diào)用回調(diào)函數(shù)。如果需要在出錯時執(zhí)行函數(shù),請使用 $.ajax。示例代碼:
$.get("./Ajax.aspx", {Action:"get",Name:"lulu"}, function (data, textStatus){
//返回的 data 可以是 xmlDoc, jsonObj, html, text, 等等.
this; // 在這里this指向的是Ajax請求的選項配置信息,請參考下圖
alert(data);
//alert(textStatus);//請求狀態(tài):success,error等等。
當(dāng)然這里捕捉不到error,因為error的時候根本不會運行該回調(diào)函數(shù)
//alert(this);
});
示例代碼:
$.getJSON("servlet/TableServlet?flag=query", "", function(response){
$.each(response,function(i){
sel.src.add({id: response[i].id, name: response[i].name, address: response[i].address});
})
sel.render();
});
});
下面我做了一個 利用jQuery Ajax 做了以小小的Demo;
其中java 部分主要代碼:
package com.bx.web.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import com.bx.dao.impl.HibernateUserDAO;
import com.bx.hibernate.User;
public class TableServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 5469871499359894890L;
User user=new User();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String flag=request.getParameter("flag");
if(flag!=null&&"flag".equals("flag")){
query(request,response);
}
}
public void query(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HibernateUserDAO test=new HibernateUserDAO();
List<User> list = test.getUserList();
for(User userlist:list){
System.out.println("Table UserName+++"+userlist.getName()+
"......Hibernate Dbconfig....User.Address"+userlist.getAddress());
}
JSONArray jr=JSONArray.fromObject(list);
String jsonUser=jr.toString();
PrintWriter out = response.getWriter();
out.print(jsonUser);
out.flush();
out.close();
}
}
jsp中的代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>tabledemo</title>
<link href="css/style.css" type="text/css" rel="stylesheet"/>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/PagerView.js" type="text/javascript"></script>
<script src="scripts/SelectorView.js" type="text/javascript"></script>
<script src="scripts/SortView.js" type="text/javascript"></script>
<script src="scripts/TableView.js" type="text/javascript"></script>
<script type="text/javascript">
$ (document).ready (function() {
var sel = new SelectorView('sel_div');
sel.src.header = {
id : '編號',
name : '姓名',
address: '地址'
};
sel.dst.header = {
id : '編號',
name: '姓名',
address: '地址'
};
sel.src.dataKey = 'id';
sel.src.title = '可選';
sel.dst.dataKey = 'id';
sel.dst.title = '已選';
sel.render();
$.getJSON("servlet/TableServlet?flag=query", "", function(response){
$.each(response,function(i){
sel.src.add({id: response[i].id, name: response[i].name, address: response[i].address});
})
sel.render();
});
});
</script>
</head>
<body>
<div id="sel_div"></div>
</body>
</html>
最后在瀏覽器URL中輸入:http://localhost:8080/TableWebProject/pagerList.jsp運行結(jié)果
一些資源
一個jQuery的Ajax Form表單插件:http://www.malsup.com/jquery/form/
一個專門生成Loading圖片的站點:http://ajaxload.info/ 大家覺得那些Loading比較炫的可以在這里跟帖曬一下,方便大家取用,嘎嘎
posted @
2011-03-02 15:11 龍ぜ?xì)垊?閱讀(357) |
評論 (0) |
編輯 收藏

2011年1月1日
AJAX全稱為“Asynchronous JavaScript and XML”(異步JavaScript和XML),是指一種創(chuàng)建交互式網(wǎng)頁應(yīng)用的網(wǎng)頁開發(fā)技術(shù)。
傳統(tǒng)的web應(yīng)用允許用戶填寫表單(form),當(dāng)提交表單時就向web服務(wù)器發(fā)送一個請求。服務(wù)器接收并處理傳來的表單,然后返回一個新的網(wǎng)頁。這個做法浪費了許多帶寬,因為在前后兩個頁面中的大部分HTML代碼往往是相同的。由于每次應(yīng)用的交互都需要向服務(wù)器發(fā)送請求,應(yīng)用的響應(yīng)時間就依賴于服務(wù)器的響應(yīng)時間。這導(dǎo)致了用戶界面的響應(yīng)比本地應(yīng)用慢得多。
與此不同,AJAX應(yīng)用可以僅向服務(wù)器發(fā)送并取回必需的數(shù)據(jù),它使用SOAP或其它一些基于XML的web service接口,并在客戶端采用JavaScript處理來自服務(wù)器的響應(yīng)。因為在服務(wù)器和瀏覽器之間交換的數(shù)據(jù)大量減少,結(jié)果我們就能看到響應(yīng)更快的應(yīng)用。同時很多的處理工作可以在發(fā)出請求的客戶端機(jī)器上完成,所以Web服務(wù)器的處理時間也減少了。
Ajax應(yīng)用程序的優(yōu)勢在于:
1. 通過異步模式,提升了用戶體驗
2. 優(yōu)化了瀏覽器和服務(wù)器之間的傳輸,減少不必要的數(shù)據(jù)往返,減少了帶寬占用
3. Ajax引擎在客戶端運行,承擔(dān)了一部分本來由服務(wù)器承擔(dān)的工作,從而減少了大用戶量下的服務(wù)器負(fù)載。
XMLHttpRequest 對象
通過使用 XMLHttpRequest 對象,web 開發(fā)者可以做到在頁面已加載后從服務(wù)器更新頁面!
Ajax屬性:
1. onreadystatechange 屬性
onreadystatechange 屬性存有處理服務(wù)器響應(yīng)的函數(shù)。下面的代碼定義一個空的函數(shù),可同時對 onreadystatechange 屬性進(jìn)行設(shè)置:
例如:
function getResult(username,password){
createXmlHttp(); //創(chuàng)建XMLHttpRequest對象
xmlHttp.open("POST", "UserServlet?flag=add&username="+username+"&password="+password);
2. readyState 屬性
readyState 屬性存有服務(wù)器響應(yīng)的狀態(tài)信息。每當(dāng) readyState 改變時,onreadystatechange 函數(shù)就會被執(zhí)行。
狀態(tài) 描述 |
0 |
請求未初始化(在調(diào)用 open() 之前)
|
1 |
請求已提出(調(diào)用 send() 之前) |
2 |
請求已發(fā)送(這里通常可以從響應(yīng)得到內(nèi)容頭部) |
3 |
請求處理中(響應(yīng)中通常有部分?jǐn)?shù)據(jù)可用,但是服務(wù)器還沒有完成響應(yīng))
|
4 |
請求已完成(可以訪問服務(wù)器響應(yīng)并使用它) |
其中send()方法需要包含有三個參數(shù),第一個是發(fā)送請求所使用的(Get()和Post()方法),第二個參數(shù)是規(guī)定服務(wù)器端腳本的Url,三個參數(shù)規(guī)定是設(shè)置對請求進(jìn)行異步處理。
咱們不再這里費口舌了,來個Servlet Ajax的小例子吧:
首先 我們來配置Web.xml。在里面配置一個servlet,跟往常一樣:
<servlet>
<servlet-name>selectcity</servlet-name>
<servlet-class>com.bx.servlet.SelectCityServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>selectcity</servlet-name>
<url-pattern>/selectCityServlet</url-pattern>
</servlet-mapping>
現(xiàn)在看我們的.jsp 文件:
<html>
<head>
<title>select city</title>
</head>
<script type="text/javascript">
function getResult(stateVal) {
alert(stateVal);
var url = "selectCityServlet?state="+stateVal;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req){
req.open("GET",url, true);
req.onreadystatechange = complete;
req.send(null);
}
}
function complete(){
if (req.readyState == 4) {
if (req.status == 200) {
var city = req.responseXML.getElementsByTagName("city");
var str=new Array();
for(var i=0;i<city.length;i++){
str[i]=city[i].firstChild.data;
}
buildSelect(str,document.getElementById("city"));
}
}
}
function buildSelect(str,sel) {
for(var i=0;i<str.length;i++) {
sel.options[sel.options.length]=new Option(str[i],str[i]);
}
}
</script>
<body>
<select name="state" onChange="getResult(this.value)">
<option value="">Select</option>
<option value="zj">浙江</option>
<option value="zs">江蘇</option>
</select>
<select id="city">
<option value="">CITY</option>
</select>
</body>
</html>
最后我們來看看servlet文件吧:
public class SelectCityServlet extends HttpServlet {
public SelectCityServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Thread.sleep(1000*3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Hello | " + request.getParameter("state"));
response.setContentType("text/xml");
response.setCharacterEncoding("utf-8");
response.setHeader("Cache-Control", "no-cache");
String state = request.getParameter("state");
StringBuffer sb=new StringBuffer("<state>");
if ("zj".equals(state)){
sb.append("<city>hangzhou</city><city>huzhou</city>");
} else if("zs".equals(state)){
sb.append("<city>nanjing</city><city>yangzhou</city><city>suzhou</city>");
} else if("hb".equals(state)){
sb.append("<city>tangshan</city><city>handan</city>");
}
sb.append("</state>");
System.out.println(sb);
PrintWriter out=response.getWriter();
out.write(sb.toString());
out.close();
}
}
這里是不是挺簡單的呢,首先是通過request取得state參數(shù),然后通過state參數(shù)生成相應(yīng)的xml文件,最后在講xml中的數(shù)據(jù)從printWriter輸出。。目前為止,這個例子已經(jīng)結(jié)束了,是不是挺簡單的呢??
運行結(jié)果如下:
posted @
2011-01-01 12:36 龍ぜ?xì)垊?閱讀(2512) |
評論 (0) |
編輯 收藏

2010年12月11日
MVC (
Model View Controler) 本來是存在于Desktop程序中的,M是指的是數(shù)據(jù)模型,V是指的是用戶界面,C則是控制器。使用MVC的目的是將M和V的實現(xiàn)代碼分離,從而使同一個程序可以使用不同的表現(xiàn)形式。比如說一批統(tǒng)計數(shù)據(jù)你可以分別用柱狀圖,餅狀圖來表示。C存在的目的是確保M和V的同步,一旦M改變了,V應(yīng)該同步更新。
MVC構(gòu)架為:
說明:
模型——視圖——控制器(MVC)是Xerox PARC在很在代為編程的語言Smalltalk--80發(fā)明的一種軟件設(shè)計模式,至今運用仍為廣泛。最近幾年被推薦為Sun公司J2EE平臺設(shè)計模式,并且受到越來越多的使用 ColdFusion 和 PHP 的開發(fā)者的歡迎。模型-視圖-控制器模式是一個有用的工具箱,它有很多好處,但也有一些缺點。
MVC如何工作
MVC是一個設(shè)計模式,他是強(qiáng)制的使用程序的輸入,處理和輸出分開。使用MVC應(yīng)用程序分成了三個核心部件:模型,視圖,控制器。他們各自處理自己的任務(wù)。
模型
模型表示企業(yè)數(shù)據(jù)和業(yè)務(wù)規(guī)則。在MVC的三個部件中,模型擁有最多的處理任務(wù)。例如它可能用象EJBs和ColdFusion Components這樣的構(gòu)件對象來處理數(shù)據(jù)庫。被模型返回的數(shù)據(jù)是中立的,就是說模型與數(shù)據(jù)格式無關(guān),這樣一個模型能為多個視圖提供數(shù)據(jù)。由于應(yīng)用于模型的代碼只需寫一次就可以被多個視圖重用,所以減少了代碼的重復(fù)性。
視圖
視圖是用戶看到并與之交互的界面。如何處理應(yīng)用程序界面變得越來越有挑戰(zhàn)性。MVC一個大的好處是他能為你的應(yīng)用程序處理很多不同的視圖。在視圖中其實沒有真正的處理發(fā)生,不管這些數(shù)據(jù)是聯(lián)機(jī)存儲的還是一個雇員列表,作為視圖來講,它只是作為一種輸出數(shù)據(jù)并允許用戶操縱的方式。
控制器
控制器接受用戶的輸入并調(diào)用模型和視圖去完成用戶的需求。所以當(dāng)單擊Web頁面中的超鏈接和發(fā)送HTML表單時,控制器本身不輸出任何東西和做任何處理。它只是接收請求并決定調(diào)用哪個模型構(gòu)件去處理請求,然后用確定用哪個視圖來顯示模型處理返回的數(shù)據(jù)。
MVC并不適合小型甚至中等規(guī)模的應(yīng)用程序,花費大量時間將MVC應(yīng)用到規(guī)模并不是很大的應(yīng)用程序通常會得不償失。但是MVC設(shè)計模式是一個很好創(chuàng)建軟件的途徑,它所提倡的一些原則,像內(nèi)容和顯示互相分離可能比較好理解。但是如果你要隔離模型、視圖和控制器的構(gòu)件,你可能需要重新思考你的應(yīng)用程序,尤其是應(yīng)用程序的構(gòu)架方面。如果你肯接受MVC,并且有能力應(yīng)付它所帶來的額外的工作和復(fù)雜性,MVC將會使你的軟件在健壯性,代碼重用和結(jié)構(gòu)方面上一個新的臺階。
這里我做了個比較簡單的程序其中使用了MVC思想:
在這里創(chuàng)建了一個實體的類,也就是M(model),即User類:
package com.bx.jstl;
public class User {
private int id; //聲明了兩給屬性;
private String name;
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;
}
}
然后在此編寫了一個類JSTLServlet 是繼承了類HttpServlet類的:
package com.bx.JSServlet;
import java.io.IOException;
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.bx.jstl.User;
public class JSTLServlet extends HttpServlet{
public void doGet(HttpServletRequest request , HttpServletResponse response)
throws IOException , ServletException
{
List<User> list = new ArrayList<User>();
for(int i = 0 ; i < 8 ; i++)
{
User u = new User();
u.setId(i);
u.setName("name"+i);
list.add(u);
}
request.setAttribute("UserList", list);
request.getRequestDispatcher("/c_forEach.jsp").forward(request, response);
}
}
現(xiàn)在我們應(yīng)該來配置WEB.xml了,這是每個Web項目都做的一步,如下所示:
<servlet>
<servlet-name>JSTLServlet</servlet-name>
<servlet-class>com.bx.JSServlet.JSTLServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSTLServlet</servlet-name>
<url-pattern>/jstl</url-pattern>
</servlet-mapping>
下面我們建立一個c_forEach.jsp,在其body中的編寫代碼如下:
<table>
<tr><th>ID</th><th>index</th><th>count</th><th>isFirst?</th><th>isLast</th></tr>
<c:forEach var="user" items="${UserList}" varStatus="status">
<tr>
<td>
${user.id}
</td>
<td>
${user.name}
</td>
<td>
${status.index}
</td>
<td>
${status.count}
</td>
<td>
${status.first}
</td>
<td>
${status.last}
</td>
</tr>
</c:forEach>
</table>
現(xiàn)在我們開啟comcat 運行此項目,在瀏覽器中輸入:
http://localhost:8080/JSP_JSTL_Project/jstl
得到網(wǎng)頁為:
posted @
2010-12-11 17:45 龍ぜ?xì)垊?閱讀(1371) |
評論 (2) |
編輯 收藏