
2011年3月2日
1 getCurrentSession創(chuàng)建的session會和綁定到當前線程,而openSession每次創(chuàng)建新的session。
2 getCurrentSession創(chuàng)建的線程會在事務回滾或事物提交后自動關(guān)閉,而openSession必須手動關(guān)閉
這里getCurrentSession本地事務(本地事務:jdbc)時 要在配置文件里進行如下設置
* 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事務(jta事務)
<property name="hibernate.current_session_context_class">jta</property>
getCurrentSession () 在事務結(jié)束之前使用當前的session
openSession() 每次重新建立一個新的session
在一個應用程序中,如果DAO 層使用Spring 的hibernate 模板,通過Spring 來控制session 的生命周期,則首選getCurrentSession ()。
使用Hibernate的大多數(shù)應用程序需要某種形式的“上下文相關(guān)的” session,特定的session在整個特定的上下文范圍內(nèi)始終有效。然而,對不同類型的應用程序而言,要為什么是組成這種“上下文”下一個定義通常 是困難的;不同的上下文對“當前”這個概念定義了不同的范圍。在3.0版本之前,使用Hibernate的程序要么采用自行編寫的基于 ThreadLocal的上下文session,要么采用HibernateUtil這樣的輔助類,要么采用第三方框架(比如Spring或Pico), 它們提供了基于代理(proxy)或者基于攔截器(interception)的上下文相關(guān)session。
從3.0.1版本開 始,Hibernate增加了SessionFactory.getCurrentSession()方法。一開始,它假定了采用JTA事務,JTA事務 定義了當前session的范圍和上下文(scope and context)。Hibernate開發(fā)團隊堅信,因為有好幾個獨立的JTA TransactionManager實現(xiàn)穩(wěn)定可用,不論是否被部署到一個J2EE容器中,大多數(shù)(假若不是所有的)應用程序都應該采用JTA事務管理。 基于這一點,采用JTA的上下文相關(guān)session可以滿足你一切需要。
更好的是,從3.1開 始,SessionFactory.getCurrentSession()的后臺實現(xiàn)是可拔插的。因此,我們引入了新的擴展接口 (org.hibernate.context.CurrentSessionContext)和新的配置參數(shù) (hibernate.current_session_context_class),以便對什么是“當前session”的范圍和上下文(scope and context)的定義進行拔插。
請參閱 org.hibernate.context.CurrentSessionContext接口的Javadoc,那里有關(guān)于它的契約的詳細討論。它定義 了單一的方法,currentSession(),特定的實現(xiàn)用它來負責跟蹤當前的上下文session。Hibernate內(nèi)置了此接口的兩種實現(xiàn)。
org.hibernate.context.JTASessionContext - 當前session根據(jù)JTA來跟蹤和界定。這和以前的僅支持JTA的方法是完全一樣的。詳情請參閱Javadoc。
org.hibernate.context.ThreadLocalSessionContext - 當前session通過當前執(zhí)行的線程來跟蹤和界定。詳情也請參閱Javadoc。
這 兩種實現(xiàn)都提供了“每數(shù)據(jù)庫事務對應一個session”的編程模型,也稱作每次請求一個session。Hibernate session的起始和終結(jié)由數(shù)據(jù)庫事務的生存來控制。假若你采用自行編寫代碼來管理事務(比如,在純粹的J2SE,或者 JTA/UserTransaction/BMT),建議你使用Hibernate Transaction API來把底層事務實現(xiàn)從你的代碼中隱藏掉。如果你在支持CMT的EJB容器中執(zhí)行,事務邊界是聲明式定義的,你不需要在代碼中進行任何事務或 session管理操作。請參閱第 11 章 事務和并發(fā)一節(jié)來閱讀更多的內(nèi)容和示例代碼。
hibernate.current_session_context_class 配置參數(shù)定義了應該采用哪個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會綁定到當前線程中,而采用openSession()
創(chuàng)建的session則不會
* 采用getCurrentSession()創(chuàng)建的session在commit或rollback時會自動關(guān)閉,而采用openSession()
創(chuàng)建的session必須手動關(guān)閉
2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
* 如果使用的是本地事務(jdbc事務)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事務(jta事務)
<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是如何做到為每一個線程維護變量的副本的呢?其實實現(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的,也就是說,在事務結(jié)束之后getCuttentSession 也是創(chuàng)建了新的session。。。。。。
openSession() 與 getCurrentSession() 有何不同和關(guān)聯(lián)呢?
在 SessionFactory 啟動的時候, Hibernate 會根據(jù)配置創(chuàng)建相應的 CurrentSessionContext ,在 getCurrentSession() 被調(diào)用的時候,實際被執(zhí)行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 執(zhí)行時,如果當前 Session 為空, currentSession 會調(diào)用 SessionFactory 的 openSession 。所以 getCurrentSession() 對于 Java EE 來說是更好的獲取 Session 的方法。
posted @
2011-04-14 10:46 龍ぜ殘劍 閱讀(5688) |
評論 (1) |
編輯 收藏
jfreechart主要是用來動態(tài)產(chǎn)生各種數(shù)據(jù)圖形的,可最初使用的時候大都會碰到圖片中的中文亂碼或是一個小方塊的情況。
仔細研究主要有以下2種原因:
1:服務器缺少中文字體,這多發(fā)生在Hp等unix操作系統(tǒng)上,解決的方法就是下載可用字體庫到系統(tǒng)中,
有人也提出在Windows上產(chǎn)生圖片在傳回到Unix主機上的方法。
2:軟件版本問題,jfreechart-1.0.10有人說沒有問題,但jfreechart-1.0.11到13都有問題,我用的最新的jfreechart-1.0.13不做設置是有問題的。
究其原因,是它代碼的內(nèi)部設置的字體有問題.
其下是具體的解決辦法:
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) ; // 圖片標題
CategoryPlot plot = chart.getCategoryPlot();// 圖形的繪制結(jié)構(gòu)對象
// 圖片標題
chart.setTitle(new TextTitle(chart.getTitle().getText(),titleFont));
// 底部
chart.getLegend().setItemFont(kfont);
// X 軸
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(xfont);// 軸標題
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 龍ぜ殘劍 閱讀(553) |
評論 (0) |
編輯 收藏
JFreeChart項目簡介
JFreeChart是開放源代碼站點SourceForge.net上的一個JAVA項目,它主要用來各種各樣的圖表,這些圖表包括:餅圖、柱狀圖(普 通柱狀圖以及堆棧柱狀圖)、線圖、區(qū)域圖、分布圖、混合圖、甘特圖以及一些儀表盤等等。這些不同式樣的圖表基本上可以滿足目前的要求。為了減少篇幅本文主 要介紹前面三種類型的圖表,讀者可以觸類旁通去開發(fā)其他樣式的圖表。
這里有點筆者在開發(fā)中遇見的問題需要注意的是:在使用Eclipse開發(fā)的時候會報一個莫名其妙的錯誤,錯誤可能指向某個類文件的第一行。遇到這樣的問題一般是因為沒有把Jcommon的jar包設置到項目的類路徑中的緣故。具體的原因不祥。
1 餅圖
對于餅圖而言,數(shù)據(jù)集的獲取用的不是同一個數(shù)據(jù)集類,另外餅圖不支持同一個類別的項目中還有子項目這樣的數(shù)據(jù)。我們只給出創(chuàng)建餅圖的代碼,至于寫圖表到一個文件則與柱狀圖一致,無需重復..
實例代碼如下:
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)品銷量圖", // 圖表標題
"產(chǎn)品", // 目錄軸的顯示標簽
"銷量", // 數(shù)值軸的顯示標簽
dataset, // 數(shù)據(jù)集
PlotOrientation.VERTICAL, // 圖表方向:水平、垂直
true, // 是否顯示圖例(對于簡單的柱狀圖必須是false)
false, // 是否生成工具
false // 是否生成URL鏈接
);
configFont(chart);//設置中文格式
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) ; // 圖片標題
CategoryPlot plot = chart.getCategoryPlot();// 圖形的繪制結(jié)構(gòu)對象
// 圖片標題
chart.setTitle(new TextTitle(chart.getTitle().getText(),titleFont));
// 底部
chart.getLegend().setItemFont(kfont);
// X 軸
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(xfont);// 軸標題
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 龍ぜ殘劍 閱讀(421) |
評論 (3) |
編輯 收藏
hibernate工作原理
原理:
1.讀取并解析配置文件
2.讀取并解析映射信息,創(chuàng)建SessionFactory
3.打開Sesssion
4.創(chuàng)建事務Transation
5.持久化操作
6.提交事務
7.關(guān)閉Session
8.關(guān)閉SesstionFactory
為什么要用:
1. 對JDBC訪問數(shù)據(jù)庫的代碼做了封裝,大大簡化了數(shù)據(jù)訪問層繁瑣的重復性代碼。
2. Hibernate是一個基于JDBC的主流持久化框架,是一個優(yōu)秀的ORM實現(xiàn)。他很大程度的簡化DAO層的編碼工作
3. hibernate使用Java反射機制,而不是字節(jié)碼增強程序來實現(xiàn)透明性。
4. hibernate的性能非常好,因為它是個輕量級框架。映射的靈活性很出色。它支持各種關(guān)系數(shù)據(jù)庫,從一對一到多對多的各種復雜關(guān)系。
2. Hibernate是如何延遲加載?
1. Hibernate2延遲加載實現(xiàn):a)實體對象 b)集合(Collection)
2. Hibernate3 提供了屬性的延遲加載功能
當Hibernate在查詢數(shù)據(jù)的時候,數(shù)據(jù)并沒有存在與內(nèi)存中,當程序真正對數(shù)據(jù)的操作時,對象才存在與內(nèi)存中,就實現(xiàn)了延遲加載,他節(jié)省了服務器的內(nèi)存開銷,從而提高了服務器的性能。
3.Hibernate中怎樣實現(xiàn)類之間的關(guān)系?(如:一對多、多對多的關(guān)系)
類與類之間的關(guān)系主要體現(xiàn)在表與表之間的關(guān)系進行操作,它們都市對對象進行操作,我們程序中把所有的表與類都映射在一起,它們通過配置文件中的many-to-one、one-to-many、many-to-many、
4. 說下Hibernate的緩存機制
1. 內(nèi)部緩存存在Hibernate中又叫一級緩存,屬于應用事物級緩存
2. 二級緩存:
a) 應用及緩存
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,它會委托應用系統(tǒng)的其他模塊負責負責對請求進行真正的處理工作。
2.DispatcherServlet查詢一個或多個HandlerMapping,找到處理請求的Controller.
3.DispatcherServlet請請求提交到目標Controller
4.Controller進行業(yè)務邏輯處理后,會返回一個ModelAndView
5.Dispathcher查詢一個或多個ViewResolver視圖解析器,找到ModelAndView對象指定的視圖對象
6.視圖對象負責渲染返回給客戶端。
為什么用:
{AOP 讓開發(fā)人員可以創(chuàng)建非行為性的關(guān)注點,稱為橫切關(guān)注點,并將它們插入到應用程序代碼中。使用 AOP 后,公共服務 (比如日志、持久性、事務等)就可以分解成方面并應用到域?qū)ο笊希瑫r不會增加域?qū)ο蟮膶ο竽P偷膹碗s性。
IOC 允許創(chuàng)建一個可以構(gòu)造對象的應用環(huán)境,然后向這些對象傳遞它們的協(xié)作對象。正如單詞 倒置 所表明的,IOC 就像反 過來的 JNDI。沒有使用一堆抽象工廠、服務定位器、單元素(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)模式將應用程序的配置和依賴性規(guī)范與實際的應用程序代碼分開。
☆ Spring 上下文:Spring 上下文是一個配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企業(yè)服務,例如 JNDI、EJB、電子郵件、國際化、校驗和調(diào)度功能。
☆ Spring AOP:通過配置管理特性,Spring AOP 模塊直接將面向方面的編程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何對象支持 AOP。Spring AOP 模塊為基于 Spring 的應用程序中的對象提供了事務管理服務。通過使用 Spring AOP,不用依賴 EJB 組件,就可以將聲明性事務管理集成到應用程序中。
☆ Spring DAO:JDBC DAO 抽象層提供了有意義的異常層次結(jié)構(gòu),可用該結(jié)構(gòu)來管理異常處理和不同數(shù)據(jù)庫供應商拋出的錯誤消息。異常層次結(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 的通用事務和 DAO 異常層次結(jié)構(gòu)。
☆ Spring Web 模塊:Web 上下文模塊建立在應用程序上下文模塊之上,為基于 Web 的應用程序提供了上下文。所以,Spring 框架支持與 Jakarta Struts 的集成。Web 模塊還簡化了處理多部分請求以及將請求參數(shù)綁定到域?qū)ο蟮墓ぷ鳌?br />
☆ Spring MVC 框架:MVC 框架是一個全功能的構(gòu)建 Web 應用程序的 MVC 實現(xiàn)。通過策略接口,MVC 框架變成為高度可配置的,MVC 容納了大量視圖技術(shù),其中包括 JSP、Velocity、Tiles、iText 和 POI。
Spring 框架的功能可以用在任何 J2EE 服務器中,大多數(shù)功能也適用于不受管理的環(huán)境。Spring 的核心要點是:支持不綁定到特定 J2EE 服務的可重用業(yè)務和數(shù)據(jù)訪問對象。毫無疑問,這樣的對象可以在不同 J2EE 環(huán)境 (Web 或 EJB)、獨立應用程序、測試環(huán)境之間重用。
IOC 和 AOP
控制反轉(zhuǎn)模式(也稱作依賴性介入)的基本概念是:不創(chuàng)建對象,但是描述創(chuàng)建它們的方式。在代碼中不直接與對象和服務連接,但在配置文件中描述哪一個組件需要哪一項服務。容器(在 Spring 框架中是 IOC 容器) 負責將這些聯(lián)系在一起。
在典型的 IOC 場景中,容器創(chuàng)建了所有對象,并設置必要的屬性將它們連接在一起,決定什么時間調(diào)用方法。下表列出了 IOC 的一個實現(xiàn)模式。
struts工作原理
Struts工作機制?為什么要使用Struts?
工作機制:
Struts的工作流程:
在web應用啟動時就會加載初始化ActionServlet,ActionServlet從
struts-config.xml文件中讀取配置信息,把它們存放到各種配置對象
當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,如果相應的 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)建強大的企業(yè)應用系統(tǒng)提供了可能。但用這些技術(shù)構(gòu)建的系統(tǒng)非常的繁亂,所以在此之上,我們需要一個規(guī)則、一個把這些技術(shù)組織起來的規(guī)則,這就是框架,Struts便應運而生。
基于Struts開發(fā)的應用由3類組件構(gòu)成:控制器組件、模型組件、視圖組件
8. Struts的validate框架是如何驗證的?
在struts配置文件中配置具體的錯誤提示,再在FormBean中的validate()方法具體調(diào)用。
9. 說下Struts的設計模式
MVC模式: web應用程序啟動時就會加載并初始化ActionServler。用戶提交表單時,一個配置好的ActionForm對象被創(chuàng)建,并被填入表單相應的數(shù)據(jù),ActionServler根據(jù)Struts-config.xml文件配置好的設置決定是否需要表單驗證,如果需要就調(diào)用ActionForm的 Validate()驗證后選擇將請求發(fā)送到哪個Action,如果Action不存在,ActionServlet會先創(chuàng)建這個對象,然后調(diào)用 Action的execute()方法。Execute()從ActionForm對象中獲取數(shù)據(jù),完成業(yè)務邏輯,返回一個ActionForward對象,ActionServlet再把客戶請求轉(zhuǎn)發(fā)給ActionForward對象指定的jsp組件,ActionForward對象指定的jsp生成動態(tài)的網(wǎng)頁,返回給客戶。
posted @
2011-03-06 19:59 龍ぜ殘劍 閱讀(458) |
評論 (0) |
編輯 收藏
Spring 是一個開源框架,是為了解決企業(yè)應用程序開發(fā)復雜性而創(chuàng)建的。框架的主要優(yōu)勢之一就是其分層架構(gòu),分層架構(gòu)允許您選擇使用哪一個組件,同時為 J2EE 應用程序開發(fā)提供集成的框架。
☆
核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要組件是 BeanFactory,它是工廠模式的實現(xiàn)。BeanFactory 使用控制反轉(zhuǎn) (IOC) 模式將應用程序的配置和依賴性規(guī)范與實際的應用程序代碼分開。
☆
Spring 上下文:Spring 上下文是一個配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企業(yè)服務,例如 JNDI、EJB、電子郵件、國際化、校驗和調(diào)度功能。
☆
Spring AOP:通過配置管理特性,Spring AOP 模塊直接將面向方面的編程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何對象支持 AOP。Spring AOP 模塊為基于 Spring 的應用程序中的對象提供了事務管理服務。通過使用 Spring AOP,不用依賴 EJB 組件,就可以將聲明性事務管理集成到應用程序中。
在此 我做了個小demo 基于Spring的核心Ioc(inversion of control) 與面向切面編程AOP(Aspect Oriented Programming)。。。。。
這個例子主要完成的義務邏輯是對信息的保存,主要代碼如下:
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 {
//實例化應用上下文,Xml類路徑應用上下文
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//getBean() 所得到得對象是Object類型的,所有在此必須強制轉(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 龍ぜ殘劍 閱讀(2722) |
評論 (0) |
編輯 收藏
用Java程序
現(xiàn)在許多網(wǎng)站都必須統(tǒng)計瀏覽量,在此為了記錄當前在線人數(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;// 當前活動的人數(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 + "; 當前總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 + "; 當前總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 龍ぜ殘劍 閱讀(1130) |
評論 (0) |
編輯 收藏
首先我 用一種比較簡單的方法,做了個小小的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ā)送郵件的服務器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 郵件發(fā)送者的地址
private String fromAddress;
// 郵件接收者的地址
private String toAddress;
// 登陸郵件發(fā)送服務器的用戶名和密碼
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) {
// 判斷是否需要身份認證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份認證,則創(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());
// 設置郵件消息的發(fā)送者
mailMessage.setFrom(from);
// 創(chuàng)建郵件的接收者地址,并設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發(fā)送的時間
mailMessage.setSentDate(new Date());
// 設置郵件消息的主要內(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){
// 判斷是否需要身份認證
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份認證,則創(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());
// 設置郵件消息的發(fā)送者
mailMessage.setFrom(from);
// 創(chuàng)建郵件的接收者地址,并設置到郵件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO屬性表示接收者的類型為TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 設置郵件消息的主題
mailMessage.setSubject(mailInfo.getSubject());
// 設置郵件消息發(fā)送的時間
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
Multipart mainPart = new MimeMultipart();
// 創(chuàng)建一個包含HTML內(nèi)容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 設置HTML內(nèi)容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 將MiniMultipart對象設置為郵件內(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){
//這個類主要是設置郵件
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ā)送的機房課程通知單,請您按照下表的相應的時間通知學生到相應的機房上課\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'>機房</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 龍ぜ殘劍 閱讀(1659) |
評論 (0) |
編輯 收藏
jQuery確實是一個挺好的輕量級的JS框架,能幫助我們快速的開發(fā)JS應用,并在一定程度上改變了我們寫JavaScript代碼的習慣。
廢話少說,直接進入正題,我們先來看一些簡單的方法,這些方法都是對jQuery.ajax()進行封裝以方便我們使用的方法,當然,如果要處理復雜的邏輯,還是需要用到jQuery.ajax()的(這個后面會說到).
1. load( url, [data], [callback] ) :載入遠程 HTML 文件代碼并插入至 DOM 中。
url (String) : 請求的HTML頁的URL地址。
data (Map) : (可選參數(shù)) 發(fā)送至服務器的 key/value 數(shù)據(jù)。
callback (Callback) : (可選參數(shù)) 請求完成時(不需要是success的)的回調(diào)函數(shù)。
這個方法默認使用 GET 方式來傳遞的,如果[data]參數(shù)有傳遞數(shù)據(jù)進去,就會自動轉(zhuǎn)換為POST方式的。jQuery 1.2 中,可以指定選擇符,來篩選載入的 HTML 文檔,DOM 中將僅插入篩選出的 HTML 代碼。語法形如 "url #some > selector"。
這個方法可以很方便的動態(tài)加載一些HTML文件,例如表單。
2. jQuery.get( url, [data], [callback] ):使用GET方式來進行異步請求
參數(shù):
url (String) : 發(fā)送請求的URL地址.
data (Map) : (可選) 要發(fā)送給服務器的數(shù)據(jù),以 Key/value 的鍵值對形式表示,會做為QueryString附加到請求URL中。
callback (Function) : (可選) 載入成功時回調(diào)函數(shù)(只有當Response的返回狀態(tài)是success才是調(diào)用該方法)。
這是一個簡單的 GET 請求功能以取代復雜 $.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等等。
當然這里捕捉不到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 龍ぜ殘劍 閱讀(357) |
評論 (0) |
編輯 收藏