
2010年12月8日
1 getCurrentSession創(chuàng)建的session會(huì)和綁定到當(dāng)前線程,而openSession每次創(chuàng)建新的session。
2 getCurrentSession創(chuàng)建的線程會(huì)在事務(wù)回滾或事物提交后自動(dòng)關(guān)閉,而openSession必須手動(dòng)關(guān)閉
這里getCurrentSession本地事務(wù)(本地事務(wù):jdbc)時(shí) 要在配置文件里進(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() 每次重新建立一個(gè)新的session
在一個(gè)應(yīng)用程序中,如果DAO 層使用Spring 的hibernate 模板,通過Spring 來控制session 的生命周期,則首選getCurrentSession ()。
使用Hibernate的大多數(shù)應(yīng)用程序需要某種形式的“上下文相關(guān)的” session,特定的session在整個(gè)特定的上下文范圍內(nèi)始終有效。然而,對不同類型的應(yīng)用程序而言,要為什么是組成這種“上下文”下一個(gè)定義通常 是困難的;不同的上下文對“當(dāng)前”這個(gè)概念定義了不同的范圍。在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)隊(duì)堅(jiān)信,因?yàn)橛泻脦讉€(gè)獨(dú)立的JTA TransactionManager實(shí)現(xiàn)穩(wěn)定可用,不論是否被部署到一個(gè)J2EE容器中,大多數(shù)(假若不是所有的)應(yīng)用程序都應(yīng)該采用JTA事務(wù)管理。 基于這一點(diǎn),采用JTA的上下文相關(guān)session可以滿足你一切需要。
更好的是,從3.1開 始,SessionFactory.getCurrentSession()的后臺(tái)實(shí)現(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(),特定的實(shí)現(xiàn)用它來負(fù)責(zé)跟蹤當(dāng)前的上下文session。Hibernate內(nèi)置了此接口的兩種實(shí)現(xiàn)。
org.hibernate.context.JTASessionContext - 當(dāng)前session根據(jù)JTA來跟蹤和界定。這和以前的僅支持JTA的方法是完全一樣的。詳情請參閱Javadoc。
org.hibernate.context.ThreadLocalSessionContext - 當(dāng)前session通過當(dāng)前執(zhí)行的線程來跟蹤和界定。詳情也請參閱Javadoc。
這 兩種實(shí)現(xiàn)都提供了“每數(shù)據(jù)庫事務(wù)對應(yīng)一個(gè)session”的編程模型,也稱作每次請求一個(gè)session。Hibernate session的起始和終結(jié)由數(shù)據(jù)庫事務(wù)的生存來控制。假若你采用自行編寫代碼來管理事務(wù)(比如,在純粹的J2SE,或者 JTA/UserTransaction/BMT),建議你使用Hibernate Transaction API來把底層事務(wù)實(shí)現(xiàn)從你的代碼中隱藏掉。如果你在支持CMT的EJB容器中執(zhí)行,事務(wù)邊界是聲明式定義的,你不需要在代碼中進(jìn)行任何事務(wù)或 session管理操作。請參閱第 11 章 事務(wù)和并發(fā)一節(jié)來閱讀更多的內(nèi)容和示例代碼。
hibernate.current_session_context_class 配置參數(shù)定義了應(yīng)該采用哪個(gè)org.hibernate.context.CurrentSessionContext實(shí)現(xiàn)。注意,為了向下兼容,如果未 配置此參數(shù),但是存在org.hibernate.transaction.TransactionManagerLookup的配 置,Hibernate會(huì)采用org.hibernate.context.JTASessionContext。一般而言,此參數(shù)的值指明了要使用的實(shí) 現(xiàn)類的全名,但那兩個(gè)內(nèi)置的實(shí)現(xiàn)可以使用簡寫,即"jta"和"thread"。
1、getCurrentSession()與openSession()的區(qū)別?
* 采用getCurrentSession()創(chuàng)建的session會(huì)綁定到當(dāng)前線程中,而采用openSession()
創(chuàng)建的session則不會(huì)
* 采用getCurrentSession()創(chuàng)建的session在commit或rollback時(shí)會(huì)自動(dòng)關(guān)閉,而采用openSession()
創(chuàng)建的session必須手動(dòng)關(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推出之時(shí),Java平臺(tái)中就引入了一個(gè)新的支持:java.lang.ThreadLocal,給我們在編寫多線程程序
時(shí)提供了一種新的選擇。ThreadLocal是什么呢?其實(shí)ThreadLocal并非是一個(gè)線程的本地實(shí)現(xiàn)版本,它并不是一個(gè)Thread,
而是thread local variable(線程局部變量)。也許把它命名為ThreadLocalVar更加合適。線程局部變量(ThreadLocal)
其實(shí)的功用非常簡單,就是為每一個(gè)使用某變量的線程都提供一個(gè)該變量值的副本,是每一個(gè)線程都可以獨(dú)立地改變自己的副本,
而不會(huì)和其它線程的副本沖突。從線程的角度看,就好像每一個(gè)線程都完全擁有一個(gè)該變量。
ThreadLocal是如何做到為每一個(gè)線程維護(hù)變量的副本的呢?其實(shí)實(shí)現(xiàn)的思路很簡單,在ThreadLocal類中有一個(gè)Map,
用于存儲(chǔ)每一個(gè)線程的變量的副本。比如下面的示例實(shí)現(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()是否是用的是同一個(gè)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()這兩個(gè)只是false的,也就是說,在事務(wù)結(jié)束之后getCuttentSession 也是創(chuàng)建了新的session。。。。。。
openSession() 與 getCurrentSession() 有何不同和關(guān)聯(lián)呢?
在 SessionFactory 啟動(dòng)的時(shí)候, Hibernate 會(huì)根據(jù)配置創(chuàng)建相應(yīng)的 CurrentSessionContext ,在 getCurrentSession() 被調(diào)用的時(shí)候,實(shí)際被執(zhí)行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 執(zhí)行時(shí),如果當(dāng)前 Session 為空, currentSession 會(huì)調(diào)用 SessionFactory 的 openSession 。所以 getCurrentSession() 對于 Java EE 來說是更好的獲取 Session 的方法。
posted @
2011-04-14 10:46 龍ぜ?xì)垊?閱讀(5688) |
評(píng)論 (1) |
編輯 收藏
jfreechart主要是用來動(dòng)態(tài)產(chǎn)生各種數(shù)據(jù)圖形的,可最初使用的時(shí)候大都會(huì)碰到圖片中的中文亂碼或是一個(gè)小方塊的情況。
仔細(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) |
評(píng)論 (0) |
編輯 收藏
JFreeChart項(xiàng)目簡介
JFreeChart是開放源代碼站點(diǎn)SourceForge.net上的一個(gè)JAVA項(xiàng)目,它主要用來各種各樣的圖表,這些圖表包括:餅圖、柱狀圖(普 通柱狀圖以及堆棧柱狀圖)、線圖、區(qū)域圖、分布圖、混合圖、甘特圖以及一些儀表盤等等。這些不同式樣的圖表基本上可以滿足目前的要求。為了減少篇幅本文主 要介紹前面三種類型的圖表,讀者可以觸類旁通去開發(fā)其他樣式的圖表。
這里有點(diǎn)筆者在開發(fā)中遇見的問題需要注意的是:在使用Eclipse開發(fā)的時(shí)候會(huì)報(bào)一個(gè)莫名其妙的錯(cuò)誤,錯(cuò)誤可能指向某個(gè)類文件的第一行。遇到這樣的問題一般是因?yàn)闆]有把Jcommon的jar包設(shè)置到項(xiàng)目的類路徑中的緣故。具體的原因不祥。
1 餅圖
對于餅圖而言,數(shù)據(jù)集的獲取用的不是同一個(gè)數(shù)據(jù)集類,另外餅圖不支持同一個(gè)類別的項(xiàng)目中還有子項(xiàng)目這樣的數(shù)據(jù)。我們只給出創(chuàng)建餅圖的代碼,至于寫圖表到一個(gè)文件則與柱狀圖一致,無需重復(fù)..
實(shí)例代碼如下:
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) |
評(píng)論 (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是一個(gè)基于JDBC的主流持久化框架,是一個(gè)優(yōu)秀的ORM實(shí)現(xiàn)。他很大程度的簡化DAO層的編碼工作
3. hibernate使用Java反射機(jī)制,而不是字節(jié)碼增強(qiáng)程序來實(shí)現(xiàn)透明性。
4. hibernate的性能非常好,因?yàn)樗莻€(gè)輕量級(jí)框架。映射的靈活性很出色。它支持各種關(guān)系數(shù)據(jù)庫,從一對一到多對多的各種復(fù)雜關(guān)系。
2. Hibernate是如何延遲加載?
1. Hibernate2延遲加載實(shí)現(xiàn):a)實(shí)體對象 b)集合(Collection)
2. Hibernate3 提供了屬性的延遲加載功能
當(dāng)Hibernate在查詢數(shù)據(jù)的時(shí)候,數(shù)據(jù)并沒有存在與內(nèi)存中,當(dāng)程序真正對數(shù)據(jù)的操作時(shí),對象才存在與內(nèi)存中,就實(shí)現(xiàn)了延遲加載,他節(jié)省了服務(wù)器的內(nèi)存開銷,從而提高了服務(wù)器的性能。
3.Hibernate中怎樣實(shí)現(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中又叫一級(jí)緩存,屬于應(yīng)用事物級(jí)緩存
2. 二級(jí)緩存:
a) 應(yīng)用及緩存
b) 分布式緩存
條件:數(shù)據(jù)不會(huì)被第三方修改、數(shù)據(jù)大小在可接受范圍、數(shù)據(jù)更新頻率低、同一數(shù)據(jù)被系統(tǒng)頻繁使用、非 關(guān)鍵數(shù)據(jù)
c) 第三方緩存的實(shí)現(xiàn)
5. Hibernate的查詢方式
Sql、Criteria,object comptosition
Hql:
1、 屬性查詢
2、 參數(shù)查詢、命名參數(shù)查詢
3、 關(guān)聯(lián)查詢
4、 分頁查詢
5、 統(tǒng)計(jì)函數(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)不要怕多,有二級(jí)緩存撐
spring工作原理
1.spring mvc請所有的請求都提交給DispatcherServlet,它會(huì)委托應(yīng)用系統(tǒng)的其他模塊負(fù)責(zé)負(fù)責(zé)對請求進(jìn)行真正的處理工作。
2.DispatcherServlet查詢一個(gè)或多個(gè)HandlerMapping,找到處理請求的Controller.
3.DispatcherServlet請請求提交到目標(biāo)Controller
4.Controller進(jìn)行業(yè)務(wù)邏輯處理后,會(huì)返回一個(gè)ModelAndView
5.Dispathcher查詢一個(gè)或多個(gè)ViewResolver視圖解析器,找到ModelAndView對象指定的視圖對象
6.視圖對象負(fù)責(zé)渲染返回給客戶端。
為什么用:
{AOP 讓開發(fā)人員可以創(chuàng)建非行為性的關(guān)注點(diǎn),稱為橫切關(guān)注點(diǎn),并將它們插入到應(yīng)用程序代碼中。使用 AOP 后,公共服務(wù) (比如日志、持久性、事務(wù)等)就可以分解成方面并應(yīng)用到域?qū)ο笊希瑫r(shí)不會(huì)增加域?qū)ο蟮膶ο竽P偷膹?fù)雜性。
IOC 允許創(chuàng)建一個(gè)可以構(gòu)造對象的應(yīng)用環(huán)境,然后向這些對象傳遞它們的協(xié)作對象。正如單詞 倒置 所表明的,IOC 就像反 過來的 JNDI。沒有使用一堆抽象工廠、服務(wù)定位器、單元素(singleton)和直接構(gòu)造(straight construction),每一個(gè)對象都是用其協(xié)作對象構(gòu)造的。因此是由容器管理協(xié)作對象(collaborator)。
Spring即使一個(gè)AOP框架,也是一IOC容器。 Spring 最好的地方是它有助于您替換對象。有了 Spring,只要用 JavaBean 屬性和配置文件加入依賴性(協(xié)作對象)。然后可以很容易地在需要時(shí)替換具有類似接口的協(xié)作對象。}
Spring 框架是一個(gè)分層架構(gòu),由 7 個(gè)定義良好的模塊組成。Spring 模塊構(gòu)建在核心容器之上,核心容器定義了創(chuàng)建、配置和管理 bean 的方式,如圖 1 所示。
組成 Spring 框架的每個(gè)模塊(或組件)都可以單獨(dú)存在,或者與其他一個(gè)或多個(gè)模塊聯(lián)合實(shí)現(xiàn)。每個(gè)模塊的功能如下:
☆ 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要組件是 BeanFactory,它是工廠模式的實(shí)現(xiàn)。BeanFactory 使用控制反轉(zhuǎn) (IOC)模式將應(yīng)用程序的配置和依賴性規(guī)范與實(shí)際的應(yīng)用程序代碼分開。
☆ Spring 上下文:Spring 上下文是一個(gè)配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企業(yè)服務(wù),例如 JNDI、EJB、電子郵件、國際化、校驗(yàn)和調(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)商拋出的錯(cuò)誤消息。異常層次結(jié)構(gòu)簡化了錯(cuò)誤處理,并且極大地降低了需要編寫的異常代碼數(shù)量(例如打開和關(guān)閉連接)。Spring DAO 的面向 JDBC 的異常遵從通用的 DAO 異常層次結(jié)構(gòu)。
☆ Spring ORM:Spring 框架插入了若干個(gè) 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è)全功能的構(gòu)建 Web 應(yīng)用程序的 MVC 實(shí)現(xiàn)。通過策略接口,MVC 框架變成為高度可配置的,MVC 容納了大量視圖技術(shù),其中包括 JSP、Velocity、Tiles、iText 和 POI。
Spring 框架的功能可以用在任何 J2EE 服務(wù)器中,大多數(shù)功能也適用于不受管理的環(huán)境。Spring 的核心要點(diǎn)是:支持不綁定到特定 J2EE 服務(wù)的可重用業(yè)務(wù)和數(shù)據(jù)訪問對象。毫無疑問,這樣的對象可以在不同 J2EE 環(huán)境 (Web 或 EJB)、獨(dú)立應(yīng)用程序、測試環(huán)境之間重用。
IOC 和 AOP
控制反轉(zhuǎn)模式(也稱作依賴性介入)的基本概念是:不創(chuàng)建對象,但是描述創(chuàng)建它們的方式。在代碼中不直接與對象和服務(wù)連接,但在配置文件中描述哪一個(gè)組件需要哪一項(xiàng)服務(wù)。容器(在 Spring 框架中是 IOC 容器) 負(fù)責(zé)將這些聯(lián)系在一起。
在典型的 IOC 場景中,容器創(chuàng)建了所有對象,并設(shè)置必要的屬性將它們連接在一起,決定什么時(shí)間調(diào)用方法。下表列出了 IOC 的一個(gè)實(shí)現(xiàn)模式。
struts工作原理
Struts工作機(jī)制?為什么要使用Struts?
工作機(jī)制:
Struts的工作流程:
在web應(yīng)用啟動(dòng)時(shí)就會(huì)加載初始化ActionServlet,ActionServlet從
struts-config.xml文件中讀取配置信息,把它們存放到各種配置對象
當(dāng)ActionServlet接收到一個(gè)客戶請求時(shí),將執(zhí)行如下流程.
-(1)檢索和用戶請求匹配的ActionMapping實(shí)例,如果不存在,就返回請求路徑無效信息;
-(2)如果ActionForm實(shí)例不存在,就創(chuàng)建一個(gè)ActionForm對象,把客戶提交的表單數(shù)據(jù)保存到ActionForm對象中;
-(3)根據(jù)配置信息決定是否需要表單驗(yàn)證.如果需要驗(yàn)證,就調(diào)用ActionForm的validate()方法;
-(4)如果ActionForm的validate()方法返回null或返回一個(gè)不包含ActionMessage的ActuibErrors對象, 就表示表單驗(yàn)證成功;
-(5)ActionServlet根據(jù)ActionMapping所包含的映射信息決定將請求轉(zhuǎn)發(fā)給哪個(gè)Action,如果相應(yīng)的 Action實(shí)例不存在,就先創(chuàng)建這個(gè)實(shí)例,然后調(diào)用Action的execute()方法;
-(6)Action的execute()方法返回一個(gè)ActionForward對象,ActionServlet在把客戶請求轉(zhuǎn)發(fā)給 ActionForward對象指向的JSP組件;
-(7)ActionForward對象指向JSP組件生成動(dòng)態(tài)網(wǎng)頁,返回給客戶;
為什么要用:
JSP、Servlet、JavaBean技術(shù)的出現(xiàn)給我們構(gòu)建強(qiáng)大的企業(yè)應(yīng)用系統(tǒng)提供了可能。但用這些技術(shù)構(gòu)建的系統(tǒng)非常的繁亂,所以在此之上,我們需要一個(gè)規(guī)則、一個(gè)把這些技術(shù)組織起來的規(guī)則,這就是框架,Struts便應(yīng)運(yùn)而生。
基于Struts開發(fā)的應(yīng)用由3類組件構(gòu)成:控制器組件、模型組件、視圖組件
8. Struts的validate框架是如何驗(yàn)證的?
在struts配置文件中配置具體的錯(cuò)誤提示,再在FormBean中的validate()方法具體調(diào)用。
9. 說下Struts的設(shè)計(jì)模式
MVC模式: web應(yīng)用程序啟動(dòng)時(shí)就會(huì)加載并初始化ActionServler。用戶提交表單時(shí),一個(gè)配置好的ActionForm對象被創(chuàng)建,并被填入表單相應(yīng)的數(shù)據(jù),ActionServler根據(jù)Struts-config.xml文件配置好的設(shè)置決定是否需要表單驗(yàn)證,如果需要就調(diào)用ActionForm的 Validate()驗(yàn)證后選擇將請求發(fā)送到哪個(gè)Action,如果Action不存在,ActionServlet會(huì)先創(chuàng)建這個(gè)對象,然后調(diào)用 Action的execute()方法。Execute()從ActionForm對象中獲取數(shù)據(jù),完成業(yè)務(wù)邏輯,返回一個(gè)ActionForward對象,ActionServlet再把客戶請求轉(zhuǎn)發(fā)給ActionForward對象指定的jsp組件,ActionForward對象指定的jsp生成動(dòng)態(tài)的網(wǎng)頁,返回給客戶。
posted @
2011-03-06 19:59 龍ぜ?xì)垊?閱讀(458) |
評(píng)論 (0) |
編輯 收藏
Spring 是一個(gè)開源框架,是為了解決企業(yè)應(yīng)用程序開發(fā)復(fù)雜性而創(chuàng)建的。框架的主要優(yōu)勢之一就是其分層架構(gòu),分層架構(gòu)允許您選擇使用哪一個(gè)組件,同時(shí)為 J2EE 應(yīng)用程序開發(fā)提供集成的框架。
☆
核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要組件是 BeanFactory,它是工廠模式的實(shí)現(xiàn)。BeanFactory 使用控制反轉(zhuǎn) (IOC) 模式將應(yīng)用程序的配置和依賴性規(guī)范與實(shí)際的應(yīng)用程序代碼分開。
☆
Spring 上下文:Spring 上下文是一個(gè)配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企業(yè)服務(wù),例如 JNDI、EJB、電子郵件、國際化、校驗(yàn)和調(diào)度功能。
☆
Spring AOP:通過配置管理特性,Spring AOP 模塊直接將面向方面的編程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何對象支持 AOP。Spring AOP 模塊為基于 Spring 的應(yīng)用程序中的對象提供了事務(wù)管理服務(wù)。通過使用 Spring AOP,不用依賴 EJB 組件,就可以將聲明性事務(wù)管理集成到應(yīng)用程序中。
在此 我做了個(gè)小demo 基于Spring的核心Ioc(inversion of control) 與面向切面編程AOP(Aspect Oriented Programming)。。。。。
這個(gè)例子主要完成的義務(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 {
//實(shí)例化應(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) |
評(píng)論 (0) |
編輯 收藏
用Java程序
現(xiàn)在許多網(wǎng)站都必須統(tǒng)計(jì)瀏覽量,在此為了記錄當(dāng)前在線人數(shù),我設(shè)計(jì)了一個(gè)計(jì)數(shù)器。其功能是:計(jì)數(shù)器就將自動(dòng)加一,離開時(shí)就自動(dòng)減一。。
這里就做了個(gè)很小的
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)前活動(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) { // 如果隊(duì)列中存在相同的IP 則SESSION不增加
list.add(loginIp);
log.info("ipList隊(duì)列新增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隊(duì)列移除ip: " + loginIp);
}
}
}
activeSessions--; // 在用戶銷毀的時(shí)候,從隊(duì)列中踢出這個(gè)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>
啟動(dòng)tomcat ,在瀏覽器中輸入:http://127.0.0.1:8080/OnlineCount/online.jsp
執(zhí)行效果如下:
posted @
2011-03-04 09:12 龍ぜ?xì)垊?閱讀(1130) |
評(píng)論 (0) |
編輯 收藏
首先我 用一種比較簡單的方法,做了個(gè)小小的demo,但是這種方法用的的是Spring 框架來完成的,因?yàn)槭褂眠@種方法是一種比較實(shí)用的方法,由于很多的代碼被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代碼做了個(gè)小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;
// 是否需要身份驗(yàn)證
private boolean validate = false;
// 郵件主題
private String subject;
// 郵件的文本內(nèi)容
private String content;
// 郵件附件的文件名
private String[] attachFileNames;
/**
* 獲得郵件會(huì)話屬性
*/
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)建一個(gè)密碼驗(yàn)證器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據(jù)郵件會(huì)話屬性和密碼驗(yàn)證器構(gòu)造一個(gè)發(fā)送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據(jù)session創(chuàng)建一個(gè)郵件消息
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ā)送的時(shí)間
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)建一個(gè)密碼驗(yàn)證器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根據(jù)郵件會(huì)話屬性和密碼驗(yàn)證器構(gòu)造一個(gè)發(fā)送郵件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根據(jù)session創(chuàng)建一個(gè)郵件消息
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ā)送的時(shí)間
mailMessage.setSentDate(new Date());
// MiniMultipart類是一個(gè)容器類,包含MimeBodyPart類型的對象
Multipart mainPart = new MimeMultipart();
// 創(chuàng)建一個(gè)包含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){
//這個(gè)類主要是設(shè)置郵件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("smtp.126.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("郵箱號(hào)@126.com");
mailInfo.setPassword("郵箱密碼");//您的郵箱密碼
mailInfo.setFromAddress("good_hans@126.com");
mailInfo.setToAddress("656426515@qq.com");
mailInfo.setSubject("計(jì)算中心北調(diào)課通知單");
String content = "";
String header = "尊敬的"+"aa 老師:\n"+
"您好!\n"+
"這是一封計(jì)算中心(北)智能排課平臺(tái)自動(dòng)給您發(fā)送的機(jī)房課程通知單,請您按照下表的相應(yīng)的時(shí)間通知學(xué)生到相應(yīng)的機(jī)房上課\n"+
"謝謝您的支持,您的滿意是我們計(jì)算中心最大的快樂!\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'>班級(jí)</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);
//這個(gè)類主要來發(fā)送郵件
SimpleMailSender sms = new SimpleMailSender();
// sms.sendTextMail(mailInfo);//發(fā)送文體格式
sms.sendHtmlMail(mailInfo);//發(fā)送html格式
}
}
posted @
2011-03-03 13:47 龍ぜ?xì)垊?閱讀(1659) |
評(píng)論 (0) |
編輯 收藏
jQuery確實(shí)是一個(gè)挺好的輕量級(jí)的JS框架,能幫助我們快速的開發(fā)JS應(yīng)用,并在一定程度上改變了我們寫JavaScript代碼的習(xí)慣。
廢話少說,直接進(jìn)入正題,我們先來看一些簡單的方法,這些方法都是對jQuery.ajax()進(jìn)行封裝以方便我們使用的方法,當(dāng)然,如果要處理復(fù)雜的邏輯,還是需要用到j(luò)Query.ajax()的(這個(gè)后面會(huì)說到).
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ù)) 請求完成時(shí)(不需要是success的)的回調(diào)函數(shù)。
這個(gè)方法默認(rèn)使用 GET 方式來傳遞的,如果[data]參數(shù)有傳遞數(shù)據(jù)進(jìn)去,就會(huì)自動(dòng)轉(zhuǎn)換為POST方式的。jQuery 1.2 中,可以指定選擇符,來篩選載入的 HTML 文檔,DOM 中將僅插入篩選出的 HTML 代碼。語法形如 "url #some > selector"。
這個(gè)方法可以很方便的動(dòng)態(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 的鍵值對形式表示,會(huì)做為QueryString附加到請求URL中。
callback (Function) : (可選) 載入成功時(shí)回調(diào)函數(shù)(只有當(dāng)Response的返回狀態(tài)是success才是調(diào)用該方法)。
這是一個(gè)簡單的 GET 請求功能以取代復(fù)雜 $.ajax 。請求成功時(shí)可調(diào)用回調(diào)函數(shù)。如果需要在出錯(cuò)時(shí)執(zhí)行函數(shù),請使用 $.ajax。示例代碼:
$.get("./Ajax.aspx", {Action:"get",Name:"lulu"}, function (data, textStatus){
//返回的 data 可以是 xmlDoc, jsonObj, html, text, 等等.
this; // 在這里this指向的是Ajax請求的選項(xiàng)配置信息,請參考下圖
alert(data);
//alert(textStatus);//請求狀態(tài):success,error等等。
當(dāng)然這里捕捉不到error,因?yàn)閑rror的時(shí)候根本不會(huì)運(yùn)行該回調(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();
});
});
下面我做了一個(gè) 利用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 : '編號(hào)',
name : '姓名',
address: '地址'
};
sel.dst.header = {
id : '編號(hào)',
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運(yùn)行結(jié)果
一些資源
一個(gè)jQuery的Ajax Form表單插件:http://www.malsup.com/jquery/form/
一個(gè)專門生成Loading圖片的站點(diǎn):http://ajaxload.info/ 大家覺得那些Loading比較炫的可以在這里跟帖曬一下,方便大家取用,嘎嘎
posted @
2011-03-02 15:11 龍ぜ?xì)垊?閱讀(357) |
評(píng)論 (0) |
編輯 收藏
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)提交表單時(shí)就向web服務(wù)器發(fā)送一個(gè)請求。服務(wù)器接收并處理傳來的表單,然后返回一個(gè)新的網(wǎng)頁。這個(gè)做法浪費(fèi)了許多帶寬,因?yàn)樵谇昂髢蓚€(gè)頁面中的大部分HTML代碼往往是相同的。由于每次應(yīng)用的交互都需要向服務(wù)器發(fā)送請求,應(yīng)用的響應(yīng)時(shí)間就依賴于服務(wù)器的響應(yīng)時(shí)間。這導(dǎo)致了用戶界面的響應(yīng)比本地應(yīng)用慢得多。
與此不同,AJAX應(yīng)用可以僅向服務(wù)器發(fā)送并取回必需的數(shù)據(jù),它使用SOAP或其它一些基于XML的web service接口,并在客戶端采用JavaScript處理來自服務(wù)器的響應(yīng)。因?yàn)樵诜?wù)器和瀏覽器之間交換的數(shù)據(jù)大量減少,結(jié)果我們就能看到響應(yīng)更快的應(yīng)用。同時(shí)很多的處理工作可以在發(fā)出請求的客戶端機(jī)器上完成,所以Web服務(wù)器的處理時(shí)間也減少了。
Ajax應(yīng)用程序的優(yōu)勢在于:
1. 通過異步模式,提升了用戶體驗(yàn)
2. 優(yōu)化了瀏覽器和服務(wù)器之間的傳輸,減少不必要的數(shù)據(jù)往返,減少了帶寬占用
3. Ajax引擎在客戶端運(yùn)行,承擔(dān)了一部分本來由服務(wù)器承擔(dān)的工作,從而減少了大用戶量下的服務(wù)器負(fù)載。
XMLHttpRequest 對象
通過使用 XMLHttpRequest 對象,web 開發(fā)者可以做到在頁面已加載后從服務(wù)器更新頁面!
Ajax屬性:
1. onreadystatechange 屬性
onreadystatechange 屬性存有處理服務(wù)器響應(yīng)的函數(shù)。下面的代碼定義一個(gè)空的函數(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 改變時(shí),onreadystatechange 函數(shù)就會(huì)被執(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()方法需要包含有三個(gè)參數(shù),第一個(gè)是發(fā)送請求所使用的(Get()和Post()方法),第二個(gè)參數(shù)是規(guī)定服務(wù)器端腳本的Url,三個(gè)參數(shù)規(guī)定是設(shè)置對請求進(jìn)行異步處理。
咱們不再這里費(fèi)口舌了,來個(gè)Servlet Ajax的小例子吧:
首先 我們來配置Web.xml。在里面配置一個(gè)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輸出。。目前為止,這個(gè)例子已經(jīng)結(jié)束了,是不是挺簡單的呢??
運(yùn)行結(jié)果如下:
posted @
2011-01-01 12:36 龍ぜ?xì)垊?閱讀(2512) |
評(píng)論 (0) |
編輯 收藏
MVC (
Model View Controler) 本來是存在于Desktop程序中的,M是指的是數(shù)據(jù)模型,V是指的是用戶界面,C則是控制器。使用MVC的目的是將M和V的實(shí)現(xiàn)代碼分離,從而使同一個(gè)程序可以使用不同的表現(xiàn)形式。比如說一批統(tǒng)計(jì)數(shù)據(jù)你可以分別用柱狀圖,餅狀圖來表示。C存在的目的是確保M和V的同步,一旦M改變了,V應(yīng)該同步更新。
MVC構(gòu)架為:
說明:
模型——視圖——控制器(MVC)是Xerox PARC在很在代為編程的語言Smalltalk--80發(fā)明的一種軟件設(shè)計(jì)模式,至今運(yùn)用仍為廣泛。最近幾年被推薦為Sun公司J2EE平臺(tái)設(shè)計(jì)模式,并且受到越來越多的使用 ColdFusion 和 PHP 的開發(fā)者的歡迎。模型-視圖-控制器模式是一個(gè)有用的工具箱,它有很多好處,但也有一些缺點(diǎn)。
MVC如何工作
MVC是一個(gè)設(shè)計(jì)模式,他是強(qiáng)制的使用程序的輸入,處理和輸出分開。使用MVC應(yīng)用程序分成了三個(gè)核心部件:模型,視圖,控制器。他們各自處理自己的任務(wù)。
模型
模型表示企業(yè)數(shù)據(jù)和業(yè)務(wù)規(guī)則。在MVC的三個(gè)部件中,模型擁有最多的處理任務(wù)。例如它可能用象EJBs和ColdFusion Components這樣的構(gòu)件對象來處理數(shù)據(jù)庫。被模型返回的數(shù)據(jù)是中立的,就是說模型與數(shù)據(jù)格式無關(guān),這樣一個(gè)模型能為多個(gè)視圖提供數(shù)據(jù)。由于應(yīng)用于模型的代碼只需寫一次就可以被多個(gè)視圖重用,所以減少了代碼的重復(fù)性。
視圖
視圖是用戶看到并與之交互的界面。如何處理應(yīng)用程序界面變得越來越有挑戰(zhàn)性。MVC一個(gè)大的好處是他能為你的應(yīng)用程序處理很多不同的視圖。在視圖中其實(shí)沒有真正的處理發(fā)生,不管這些數(shù)據(jù)是聯(lián)機(jī)存儲(chǔ)的還是一個(gè)雇員列表,作為視圖來講,它只是作為一種輸出數(shù)據(jù)并允許用戶操縱的方式。
控制器
控制器接受用戶的輸入并調(diào)用模型和視圖去完成用戶的需求。所以當(dāng)單擊Web頁面中的超鏈接和發(fā)送HTML表單時(shí),控制器本身不輸出任何東西和做任何處理。它只是接收請求并決定調(diào)用哪個(gè)模型構(gòu)件去處理請求,然后用確定用哪個(gè)視圖來顯示模型處理返回的數(shù)據(jù)。
MVC并不適合小型甚至中等規(guī)模的應(yīng)用程序,花費(fèi)大量時(shí)間將MVC應(yīng)用到規(guī)模并不是很大的應(yīng)用程序通常會(huì)得不償失。但是MVC設(shè)計(jì)模式是一個(gè)很好創(chuàng)建軟件的途徑,它所提倡的一些原則,像內(nèi)容和顯示互相分離可能比較好理解。但是如果你要隔離模型、視圖和控制器的構(gòu)件,你可能需要重新思考你的應(yīng)用程序,尤其是應(yīng)用程序的構(gòu)架方面。如果你肯接受MVC,并且有能力應(yīng)付它所帶來的額外的工作和復(fù)雜性,MVC將會(huì)使你的軟件在健壯性,代碼重用和結(jié)構(gòu)方面上一個(gè)新的臺(tái)階。
這里我做了個(gè)比較簡單的程序其中使用了MVC思想:
在這里創(chuàng)建了一個(gè)實(shí)體的類,也就是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;
}
}
然后在此編寫了一個(gè)類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了,這是每個(gè)Web項(xiàng)目都做的一步,如下所示:
<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>
下面我們建立一個(gè)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 運(yùn)行此項(xiàng)目,在瀏覽器中輸入:
http://localhost:8080/JSP_JSTL_Project/jstl
得到網(wǎng)頁為:
posted @
2010-12-11 17:45 龍ぜ?xì)垊?閱讀(1371) |
評(píng)論 (2) |
編輯 收藏
java對cookie的操作其實(shí)不是很難的,主要就是對cookie 的建立和cookie的讀取操作吧,還有對cookie的生命周期的設(shè)置,和cookie的路徑的設(shè)置。。。。
一:首先我們建立一個(gè)有
生命周期的cookie吧,代碼如下:
int seconds=saveTime*24*60*60;//
這里是一天為單位設(shè)置其周期
Cookie cookie=new Cookie("cookiename","cookievalue");
cookie.setMaxAge(sendons);
//設(shè)置路徑,這個(gè)路徑即為該工程下都可以訪問該cookie如果不設(shè)置路徑,那么設(shè)置該路徑cookie路徑及其路徑可以訪問
cookie.setPath("/");
response.addCookie(cookie);
二:建立一個(gè)沒有生命周期的cookie,即隨著瀏覽器的關(guān)閉就消失的cookie,代碼如下:
HttpServletRequeset request;
HttpServletResponse response;
Cookie cookie=new Cookie("cookiename","cookievalue");//
相當(dāng)于一個(gè)Map
response.addCookie(cookie);
三:下面我介紹如何讀取cookie吧,代碼如下:
Cookie[] cookies=request.getCookies();
String[] cooks=null;
String username=null;
String password=null;
if(cookie!=null){
for(Cookie coo:cookies){
String aa=coo.getValue();
cookie=aa.split("==");
if(cooks.length==2){
username=cooks[0];//get the cookie name
password=cooks[1];//get the cookie value
}
}
}
posted @
2010-12-11 16:05 龍ぜ?xì)垊?閱讀(1735) |
評(píng)論 (2) |
編輯 收藏
基于數(shù)據(jù)庫的Java Web
現(xiàn)今所有的 Web都是基于數(shù)據(jù)庫的,可見數(shù)據(jù)庫在Web中的開發(fā)時(shí)如此的重要。然而基本上所有的網(wǎng)站都是要求客戶登陸的時(shí)候都必須事先注冊賬號(hào),這樣才能進(jìn)入網(wǎng)頁,訪問其中的頁面,資源。。開發(fā)基于數(shù)據(jù)庫的Web程序時(shí),涉及到多個(gè)用戶同時(shí)請求與數(shù)據(jù)庫建立"連接"的問題,但多用戶并發(fā)處理目前還是一個(gè)難點(diǎn)。該文在對傳統(tǒng)數(shù)據(jù)連接模式的分析基礎(chǔ)上,采用了一種基于對象的數(shù)據(jù)連接池的設(shè)計(jì)方案。通過連接對象放置預(yù)先建立的若干"連接",根據(jù)一定的策略管理這些"連接",防止"連接"過多內(nèi)存開銷過大,及連接排隊(duì)過長問題。并用JAVA實(shí)現(xiàn)了該方案,在實(shí)際應(yīng)用中提供了一個(gè)高效的連接管理策略,提高了Web數(shù)據(jù)庫應(yīng)用系統(tǒng)的性能。
一:在此我通過一個(gè)實(shí)際的例子談?wù)勎易罱頦eb得心得,首先我們建立一個(gè)javaWeb項(xiàng)目在Myeclipse下。首先建立好數(shù)據(jù)庫連接,即建立一個(gè)Vo對象User類,如下:
package vo;
/*
用戶名稱:<input type="text" name="username"><br>
用戶密碼:<input type="password" name="password"><br>
用戶愛好:<input type="checkbox" name="hobby" value="1">游泳
<input type="checkbox" name="hobby" value="2">足球<br>
用戶性別:<input type="radio" name="gender" value="male">男
<input type="radio" name="gender" value="female">女
<input type="radio" name="gender" value="secret">保密<br>
用戶職位:<select name="position">
<option value="CEO">CEO</option>
<option value="CFO">CFO</option>
<option value="CTO">CTO</option>
</select><br>
用戶簡歷:<textarea rows="5" cols="20" name="resume"></textarea>
<input type="submit" value="注冊">
*/
public class User {
private int id;
private String userName;
private String passWord;
private String hobby;
private String gender;
private String position;
private String resume;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getResume() {
return resume;
}
public void setResume(String resume) {
this.resume = resume;
}
}
二:這樣我們建立好了實(shí)體對象之后,現(xiàn)在我們來建立UserDAO接口和DAOFactory兩個(gè)類如下:
package dao;
import vo.User;
public interface UserDAO {
//建立一個(gè)接口
void save(User user);
}
package factory;
import impl.UserDaoImpl;
import dao.UserDAO;
public class DAOFactory {
public static UserDAO getUserDAOInstance(){
return new UserDaoImpl();
}
}
三:現(xiàn)在我們來建立ConnectionUtil類,這里我才用我們最常用的一種方法來連接數(shù)據(jù)庫Database即:
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class ConnectionUtil {
public Connection openConnection() {
String driver = "";
String url = "";
String user = "";
String password = "";
Properties prop = new Properties(); //實(shí)例化一個(gè)配置文件的對象
Connection conn = null;
try {
// 加載屬性文件
prop.load(this.getClass().getClassLoader().getResourceAsStream(
"DBConfig.properties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
// Class.forName加載驅(qū)動(dòng)
Class.forName(driver);
// DriverManager獲得連接
conn = DriverManager.getConnection(url,
user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
四:是實(shí)現(xiàn)Java程序與數(shù)據(jù)庫的鏈接層建立一個(gè)UserDaoImpl類:
package impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import vo.User;
import dao.UserDAO;
import db.ConnectionUtil;
public class UserDaoImpl implements UserDAO{
//實(shí)現(xiàn)接口UerDAO
public void save(User user) {
//實(shí)現(xiàn)接口類中的方法
ConnectionUtil cu=new ConnectionUtil();//初始化連接的數(shù)據(jù)庫
Connection conn=cu.openConnection();
String sql = "insert into User(username,password,hobby,gender,position,resume) values(?,?,?,?,?,?)";
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUserName());
pstmt.setString(2, user.getPassWord());
pstmt.setString(3, user.getHobby());
pstmt.setString(4, user.getGender());
pstmt.setString(5, user.getPosition());
pstmt.setString(6, user.getResume());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
conn.close();//關(guān)閉連接數(shù)據(jù)庫
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
五:是通過網(wǎng)站往數(shù)據(jù)庫中加載數(shù)據(jù),如下:
package com.bx.Servletform;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDAO;
import factory.DAOFactory;
import vo.User;
public class RegisterServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
String username=request.getParameter("username");
String password=request.getParameter("password");
String[] hobby=request.getParameterValues("hobby");
String gender=request.getParameter("gender");
String resume=request.getParameter("resume");
String position=request.getParameter("position");
User user=new User();
user.setUserName(username);
user.setGender(gender);
user.setPassWord(password);
user.setPosition(position);
user.setResume(resume);
String hobbyStr="";
if(hobby!=null&&hobby.length>0){
for(int i=0;i<hobby.length;i++){
hobbyStr=hobby[i]+":";
}
}
user.setHobby(hobbyStr);
UserDAO udao=DAOFactory.getUserDAOInstance();
udao.save(user);
PrintWriter out=response.getWriter();
out.println("Hello World Servlet james");
System.out.println("username |"+username);
System.out.println("password |"+password);
System.out.println("gender |"+gender);
System.out.println("resume |"+resume);
System.out.println("position |"+position);
if(hobby!=null&& hobby.length>0){
for(int i=0;i<hobby.length;i++){
System.out.println(hobby[i]);
}
}
//實(shí)現(xiàn)頁面的跳轉(zhuǎn)
if(username!=null && username.equals("james")){
request.getRequestDispatcher("/success.html").forward(request, response);
}else{
request.getRequestDispatcher("/failure.jsp").forward(request, response);
}
}
現(xiàn)在我們來配置一下register,jsp吧,如下:
<form action="/Servlet_Form_Project/form" method="post">
<!--form 中有兩個(gè)最為重要的屬性-->
用戶名稱:<input type="text" name="username"><br>
用戶密碼:<input type="password" name="password"><br>
用戶愛好:<input type="checkbox" name="hobby" value="1">游泳
<input type="checkbox" name="hobby" value="2">足球<br>
用戶性別:<input type="radio" name="gender" value="male">男
<input type="radio" name="gender" value="female">女
<input type="radio" name="gender" value="secret">保密<br>
用戶職位:<select name="position">
<option value="CEO">CEO</option>
<option value="CFO">CFO</option>
<option value="CTO">CTO</option>
</select><br>
用戶簡歷:<textarea rows="5" cols="20" name="resume"></textarea><br/>
<input type="submit" value="注冊">
</form>
試圖效果如下:
現(xiàn)在我們來配置一下WEB.xml如下所示:
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.bx.Servletform.RegisterServlet</servlet-class>
<!-- this is servlet -->
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/form</url-pattern>
</servlet-mapping>
在此我們已經(jīng)完成了Java Web與數(shù)據(jù)庫的連接:至此我們可以開始comcat,在瀏覽器中輸入連接的地址即:http://localhost:8080/Servlet_Form_Project/register.jsp
得到頁面為:
這時(shí)候我們可以查看數(shù)據(jù)庫中是否在如了我們輸入的數(shù)據(jù)即:
posted @
2010-12-09 20:55 龍ぜ?xì)垊?閱讀(4394) |
評(píng)論 (2) |
編輯 收藏
一:軟件下載
1.Java
這里我使用的是jdk1.6.0...
2.tomcat
我使用的是tomcat的版本是6.0.29的,安裝版或者是解壓版的都可以使用,只是有一點(diǎn)不同而已。
3.數(shù)據(jù)庫
推薦使用 MySQL, 因?yàn)镸ySQL使用更加的解潔,明了。。
二:軟件安裝
1.雙擊安裝jdk。
裝完后在我的電腦->屬性->高級(jí)->環(huán)境變量->系統(tǒng)變量中添加以下環(huán)境變量:
(假設(shè)你的JDK安裝在c:/jdk)
JDK_HOME=C:\jdk
classpath=.;%JDK_HOME%\lib\dt.jar;%JDK_HOME%\lib\tools.jar
在PATH(原來就已存在)中添加:%JDK_HOME%\bin
這樣jdk環(huán)境配置成功。
2.雙擊安裝你的Tomcat。(建議安裝在一個(gè)盤的根目錄下入D:/tomcat)
注:apache-tomcat-6.0.29這是免安裝版的。。嘿嘿
這樣已經(jīng)完整安裝完Tomcat了。
建議:在PATH中再添加:%JDK_HOME%\bin;%TOMCAT_HOME%\bin
這樣做的目的是在虛擬dos中可以使用tomcat的工具
最后順便把第一步下載回來的三個(gè)jar文件放到tomcat目錄下的common/lib目錄中
3.測試:
打開開始菜單中的tomcat(小貓圖案)的monitor工具,點(diǎn)擊start server,顯示綠色三角形即為啟動(dòng),打開瀏覽器在地址欄輸入:http://localhost:8080/可以看到小貓圖案說明已經(jīng)配置成功。
4.安裝數(shù)據(jù)庫(sqlserver)
windows xp下必須安裝個(gè)人版或開發(fā)版(個(gè)人推薦個(gè)人版)。
一直next就可以(微軟的東西就是方便),這里注意到域帳戶那里選擇本機(jī)帳戶,到驗(yàn)證那里選擇混合驗(yàn)證(這點(diǎn)很重要,若選擇系統(tǒng)認(rèn)證以后在程序中就連接不上數(shù)據(jù)庫),為你的sa用戶輸入一個(gè)密碼(如果練習(xí)用就不用考慮安全性啦,選擇“空密碼”就可以)
一切都準(zhǔn)備好,我們具體的做一個(gè)小程序吧:
1.建立一個(gè)繼承于HttpServlet的類TestServlet,在里面寫HttpServlet中的方法,一般常用的方法有doGet(),doPost(),doPut(),doDelete()其中最常用的有doGet(),doPost()兩個(gè)方法。。
代碼如下:
package com.dr.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet{
public void init(){
System.out.println("hello");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
System.out.println("how are you");
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
String username=request.getParameter("username");
String pws=request.getParameter("password");
System.out.println(username);
System.out.println(pws);
//實(shí)現(xiàn)頁面的跳轉(zhuǎn)
if(username!=null && username.equals("james")){
request.getRequestDispatcher("/successfull.html").forward(request, response);
}else{
request.getRequestDispatcher("/failure.html").forward(request, response);
}
System.out.println("doPost method");
}
}
2.我們應(yīng)該配置web.xml文件:
代碼如下:
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.dr.servlet.TestServlet</servlet-class>
<!-- this is servlet -->
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
3.下面我們配置demo.html
body中的代碼如下:
<form name="f1" id="f1" action="/Servlet_Basic/test" method="post">
<!--其中的method="post"與"get"的區(qū)別別需要清楚,這是非常重要的-->
<table >
<tr><td>賬號(hào)</td> <td><input type="text" name="username" id="username"/></td></tr>
<tr><td>密碼</td> <td><input type="password" name="password" id="password"/></td></tr>
<tr> <td colspan="3" align="center"><input type="submit" value="歡迎光臨" /></td></tr>
</table>
</form>
即為:
這時(shí)候你可以在啟動(dòng)tomcat,然后在internet中輸入http://localhost:8080/Servlet_Basic/demo.html,就啟動(dòng)了剛才得網(wǎng)頁,如下:
posted @
2010-12-08 12:43 龍ぜ?xì)垊?閱讀(1149) |
評(píng)論 (0) |
編輯 收藏
淺談?dòng)肑DBC連接MySQL
在學(xué)習(xí)數(shù)據(jù)庫開發(fā)的實(shí)例,這里淺談一下用JDBC連接數(shù)據(jù)庫MySQL(當(dāng)然也可以連接 SQL Server或者Oracle了,只是我更喜歡開源軟件,同時(shí)也簡單些。。。)
首先正確安裝好MySQL,建立好數(shù)據(jù)庫,下面我們來建立一個(gè)數(shù)據(jù)庫吧。
JDBC連接MySQL
加載節(jié)注冊JDBC驅(qū)動(dòng)程序,
Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
JDBC URL定義驅(qū)動(dòng)程序與數(shù)據(jù)庫之間的鏈接
標(biāo)準(zhǔn)語法:
<protocol(主要通信協(xié)議)>:<subprotocol(次要通訊協(xié)議,驅(qū)動(dòng)程序名稱)>:<data source identifier(數(shù)據(jù)源)>
MySQL JDBC URL的格式:
jdbc:mysql://[hostname][:port]/[dbname][?param1=value1][¶m2=value2]….
例如:
jdbc:mysql://localhost:3306/jdbc_db","root","1234"
常見參數(shù):
user 用戶名
password 密碼
autoReconnect 聯(lián)機(jī)失敗,是否重新聯(lián)機(jī)(true/false)
maxReconnect 嘗試重新聯(lián)機(jī)次數(shù)
initialTimeout 嘗試重新聯(lián)機(jī)間隔
maxRows 傳回最大行數(shù)
useUnicode 是否使用Unicode字體編碼(true/false)
characterEncoding 何種編碼(GB2312/UTF-8/…)
relaxAutocommit 是否自動(dòng)提交(true/false)
capitalizeTypeNames 數(shù)據(jù)定義的名稱以大寫表示
JDBC訪問數(shù)據(jù)庫的步驟:
1.加載數(shù)據(jù)庫驅(qū)動(dòng)
2.獲得數(shù)據(jù)庫連接
3.創(chuàng)建SQL語句
4.執(zhí)行查詢
5.遍歷結(jié)果集
6.關(guān)閉數(shù)據(jù)庫連接
數(shù)據(jù)庫的鏈接一般有三種方法,這里簡單說一種,有小例子如下:
ckage com.bx.jdbc;
port java.sql.Connection;
port java.sql.DriverManager;
port java.util.Properties;
public class ConnectionUtil {
public Connection openConnection() {
String driver = "";
String url = "";
String user = "";
String password = "";
Properties prop = new Properties();
Connection conn = null;
try {
// 加載屬性文件
prop.load(this.getClass().getClassLoader().getResourceAsStream(
"DBConfig.properties"));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
// Class.forName加載驅(qū)動(dòng)
Class.forName(driver);
// DriverManager獲得連接
conn = DriverManager.getConnection(url,user, password);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
執(zhí)行的主函數(shù)如下:
package com.bx.jdbc;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
ConnectionUtil cu = new ConnectionUtil();
// 第三種方法
System.out.println("這是最常用的一種方法:" + cu.openConnection());
}
}
執(zhí)行結(jié)果:
謝謝大家分享,但愿能對您帶來一點(diǎn)幫助,希望能幫提出寶貴的意見。。。
posted @
2010-12-08 09:03 龍ぜ?xì)垊?閱讀(2473) |
評(píng)論 (2) |
編輯 收藏