探索與發(fā)現(xiàn)

          研究java技術(shù)

            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            83 隨筆 :: 0 文章 :: 109 評(píng)論 :: 0 Trackbacks

          #

          只適用于window平臺(tái):
          假設(shè)之前你已經(jīng)裝好了ruby,rails,mysql
          1)? 啟動(dòng)mysql
          ??? d:\>net start mysql
          2)? 優(yōu)化mysql
          ??? d:\>gem install mysql
          這會(huì)提示出很多版本,確保你選擇的是高版本而且是以(mswin32)結(jié)尾的產(chǎn)品
          3)? 創(chuàng)建rails項(xiàng)目
          ??? d:\>rails cookbook
          ???
          進(jìn)入cookbook目錄
          ??? 這樣子默認(rèn)使用的是mysql數(shù)據(jù)庫(kù),如果想使用PostgreSQL,
          ??? 就要這樣子指定它創(chuàng)建項(xiàng)目了d:>rails cookbook --database=postgresql
          ??? d:\>cd cookbook
          4)? 數(shù)據(jù)庫(kù)test創(chuàng)建表languages,我的數(shù)據(jù)庫(kù)的用戶(hù)名是root,密碼是root
          ??? 我們使用rails創(chuàng)建表
          ??? 1:打開(kāi)cookbook\config\database.yml修改為
          ??? development:
          ? adapter: mysql
          ? database: test
          ? username: root
          ? password: root
          ? host: localhost

          # Warning: The database defined as 'test' will be erased and
          # re-generated from your development database when you run 'rake'.
          # Do not set this db to the same as development or production.
          test:
          ? adapter: mysql
          ? database: cookbook_test
          ? username: root
          ? password: root
          ? host: localhost

          production:
          ? adapter: mysql
          ? database: cookbook_production
          ? username: root
          ? password: root
          ? host: localhost
          2:創(chuàng)建一個(gè)migration腳本
          ? d:\cookbokk>ruby script/generate migration build_db
          ? 打開(kāi)db/migrate/001_build_db.rb
          ? 修改如下:
          ? class BuildDb < ActiveRecord::Migration
          ? def self.up
          ??? create_table :languages,:force=>true do |t|
          ????????????????????? t.column :name,:string
          ????????????????????? t.column :description,:string
          ??? end
          ? end

          ? def self.down
          ??? drop_table :languages
          ? end
          end
          3:執(zhí)行d:\cookbook> rake db:migrate
          ? 這時(shí)你的數(shù)據(jù)庫(kù)表應(yīng)該創(chuàng)建了

          5)有兩種方式創(chuàng)建scaffolding
          ?<第一種方式>
          ? 1)ruby script/generate model language
          ? 2)ruby script/generate controller language
          ? 3)修改這個(gè)文件為如下內(nèi)容app/controllers/language_controller.rb:

          ??? class LanguageController < ApplicationController
          ??? scaffold :languages
          ??? end
          										
          												
          4)啟動(dòng)服務(wù)器ruby script/server
          5)訪問(wèn)http://localhost:3000/languages

          <第二種方式>
          1)ruby script/generate scaffold language
          2) 啟動(dòng)服務(wù)器ruby script/server
          3)訪問(wèn)http://localhost:3000/languages
          posted @ 2007-03-24 18:40 蜘蛛 閱讀(1397) | 評(píng)論 (0)編輯 收藏

          Tiles support


          For better struts/tiles support, myfaces has an integrated JspTilesViewHandler (since release 1.0.6 bate). The main advantage of the ViewHandler is, that tiles-definitions can be sourced out into xml files (up to now using tiles and myfaces you had to definie the layout within jsp-pages).

          Have a look at the tiles-webapp example.

          Steps to implement a myfaces-tiles application:


          1) configure the JspTilesViewHandler in your faces-config:
          <application>
          ???<view-handler>net.sourceforge.myfaces.application.jsp.JspTilesViewHandlerImpl</view-handler>
          </application>

          2) add the following lines to your web.xml
          <context-param>
          ???<param-name>tiles-definitions</param-name>
          ???<param-value>/WEB-INF/tiles.xml</param-value>
          </context-param>

          3) define your layout in a tiles-definition file (sample from the tiles-webapp).

          When rendering the view, the JspTilesViewHandlerImpl will take the given viewId and compute a tileId by
          • substituting any extension by ".tiles"
          • appending ".tiles" if path-mapping is used
          Next the ViewHanlder looks up in the tile-definitions for the corresponding definition.
          (eg. for viewId = /page1.jsp the lookup would be /page1.tiles)

          By the way, the JspTilesViewHandlerImpl is part of the myfaces-components. So someone could use it with Sun's RI too.
          ==================================================================
          <!DOCTYPE tiles-definitions PUBLIC
          ?"-//Apache?Software?Foundation//DTD?Tiles?Configuration//EN"
          ?"http://jakarta.apache.org/struts/dtds/tiles-config.dtd">

          <tiles-definitions>
          ???<definition?name="layout.example"?path="/template/template.jsp"?>
          ???????<put?name="header"?value="/common/header.jsp"?/>
          ???????<put?name="menu"?value="/common/navigation.jsp"?/>
          ???</definition>

          ???<definition?name="/page1.tiles"?extends="layout.example"?>
          ???????<put?name="body"?value="/page1.jsp"?/>
          ???</definition>

          ???<definition?name="/page2.tiles"?extends="layout.example"?>
          ???????<put?name="body"?value="/page2.jsp"?/>
          ???</definition>

          </tiles-definitions>


          http://www.marinschek.com/myfaces/tiki/tiki-index.php?page=Features
          posted @ 2006-09-25 05:39 蜘蛛 閱讀(582) | 評(píng)論 (0)編輯 收藏

          在WebWork 2.2.x 之后,它將直接內(nèi)建支持spring ioc了,所以更加簡(jiǎn)單了,,
          做個(gè)例子
          第一步:在web-inf下建一個(gè)webwork.properties文件,
          內(nèi)容為
          webwork.objectFactory = spring
          第二步:也就是加載applicationContext.xml,可以采取前面前的兩種之一,,這里采用后面那種
          <listener>
          ??<listener-class>
          ???org.springframework.web.context.ContextLoaderListener
          ??</listener-class>
          ?</listener>
          第三步:創(chuàng)建要裝載的實(shí)例,在applicationContext.xml(采用監(jiān)聽(tīng)的方式,記住默認(rèn)的位置是在web-inf下面)
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "

          <beans default-autowire="autodetect"> <!--記注一定要加上-->
          ? <bean id="userManager" singleton="true" class="helloWorld.UserManager"/>
          </beans>
          第四步:在修改我原來(lái)的例子
          HelloWorldAction.java

          package helloWorld;
          import com.opensymphony.xwork.ActionSupport;
          public class HelloWorldAction extends ActionSupport{

          ??? String greeting;
          ??? UserManager userManager;
          ??? public void setGreeting(String greeting) {
          ??????? this.greeting = greeting;
          ??? }

          ??? public String getGreeting() {
          ??????? return greeting;
          ??? }
          ??? public UserManager getUserManager() {
          ??return userManager;
          ?}

          ?public void setUserManager(UserManager userManager) {
          ??this.userManager = userManager;
          ?}

          ?public String execute() throws Exception {
          ??userManager.sayHello();
          ??System.out.println("after userManager.sayHello()");
          ??????? if (greeting.equals("") || greeting == null) {
          ??????????? addFieldError("greeting", getText("greeting"));
          ??????????? return ERROR;
          ??????? }
          ??????? return SUCCESS;
          ??? }
          }
          而UserManager.java類(lèi)如下
          package helloWorld;
          public class UserManager {
          ?public UserManager()
          ?{
          ? System.out.println("create instance of UserManger");
          ?}
          ?public void sayHello()
          ?{
          ? System.out.println("hello zjh");
          ?}
          }
          再訪問(wèn)
          http://localhost:8080/WebWork/index.jsp提交后在tomcat console窗口打印出
          hello zjh
          after userManager.sayHello()

          posted @ 2006-08-03 07:29 蜘蛛 閱讀(1399) | 評(píng)論 (2)編輯 收藏

          把spring集成到web框架很簡(jiǎn)單,只要在web.xml里面加上
          <context-param>
          ??? <param-name>contextConfigLocation</param-name>
          ??? <param-value>/WEB-INF/applicationContext*.xml</param-value>
          </context-param>
          或者
          <listener>
          ??? <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
          </listener>
          如果為下面這種方式的話(huà),那么就是加載默認(rèn)的文件
          /WEB-INF/applicationContext.xml
          這個(gè)在
          org.springframework.web.context.support.XmlWebApplicationContext類(lèi)里面定義的,,部分代碼:
          /** Default config location for the root context */
          ?public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";

          ?/** Default prefix for building a config location for a namespace */
          ?public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

          ?/** Default suffix for building a config location for a namespace */
          ?public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";


          Once the context files are loaded, Spring creates a WebApplicationContext object based on the bean definitions and puts it into the ServletContext.
          這樣我們就可以直接用ServletContext獲取自己想要的參數(shù)的,,

          All Java web frameworks are built on top of the Servlet API, so you can use the following code to get the ApplicationContext that Spring created.

          WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

          通過(guò)WebApplicationContext我們就可以通過(guò)bean的名字獲取它的實(shí)例了
          The WebApplicationContextUtils class is for convenience, so you don't have to remember the name of the ServletContext attribute. Its getWebApplicationContext() method will return null if an object doesn't exist under the WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE key. Rather than risk getting NullPointerExceptions in your application, it's better to use the getRequiredWebApplicationContext() method. This method throws an Exception when the ApplicationContext is missing.

          Once you have a reference to the WebApplicationContext, you can retrieve beans by their name or type. Most developers retrieve beans by name, then cast them to one of their implemented interfaces.

          Fortunately, most of the frameworks in this section have simpler ways of looking up beans. Not only do they make it easy to get beans from the BeanFactory, but they also allow you to use dependency injection on their controllers. Each framework section has more detail on its specific integration strategies.

          posted @ 2006-08-02 23:41 蜘蛛 閱讀(630) | 評(píng)論 (0)編輯 收藏

          webwork使用 validation驗(yàn)證框架,其采用的是攔截器
          看一個(gè)例子:
          ??? public String doExecute() throws Exception {
          ???return SUCCESS;
          ??? }
          }
          ------
          在xwork.xml里面添加
          <interceptors>
          ?<interceptor name="validator" class="com.opensymphony.xwork.validator.ValidationInterceptor"/>
          ?</interceptors>
          <action name="validation" class="helloWorld.SimpleAction">
          ???<result name="success" type="dispatcher">
          ????<param name="location">/simple_result.jsp</param>
          ???</result>
          ???<result name="error" type="dispatcher">
          ????<param name="location">/simple.jsp</param>
          ???</result>
          ???<!-- If you don't override execute(), you must do this: -->
          ???<result name="input" type="dispatcher">
          ????<param name="location">/simple.jsp</param>
          ???</result>
          ???<interceptor-ref name="validator" />
          ???<interceptor-ref name="debugStack" />
          ???<interceptor-ref name="defaultStack" />
          ???
          ??</action>
          注意interceptor為多個(gè)時(shí)與servlet里面的filter一樣按順序依次傳遞,假若失敗就為影響后面的程序運(yùn)行效果.
          還有兩個(gè)jsp頁(yè)面
          simple_result.jsp
          <%@ taglib prefix="ww" uri="webwork"%>
          <html>
          ?<head>
          ??<title>WebWork Validation Example</title>
          ?</head>
          ?<body>
          ??<p>
          ???The count is
          ???<ww:property value="count" />
          ??</p>
          ??</form>
          ?</body>
          </html>
          --
          simple.jsp
          <%@ taglib prefix="ui" uri="webwork" %>
          <html>
          <head>
          ??? <title>WebWork Validation Example</title>
          </head>
          <body>
          <form action="validation.action" method="post">
          <table>
          ???? <ui:textfield label="Set the counter" name="count"/>
          ??? <ui:submit value="'Submit'"/>
          </table>
          </form>
          </body>
          </html>
          運(yùn)行效果如下
          count must be between 0 and 5, current value is 8.

          下面為日期類(lèi)型的驗(yàn)證
          <field-validator type="date">
          <param name="min">12/22/2002</param>
          ? <param name="max">12/25/2002</param>
          ? <message>The date must be between 12-22-2002 and 12-25-2002.</message>
          </field-validator>
          </field>
          <field name="foo">
          <field-validator type="int">
          <param name="min">0</param>
          <param name="max">100</param>
          <message key="foo.range">Could not find foo.range!</message>
          </field-validator>
          </field>
          </validators>


          本地中文化網(wǎng)址

          http://wiki.javascud.org/display/ww2cndoc/Home

          在線(xiàn)文檔

          http://www.opensymphony.com/webwork/wikidocs

          struts 的區(qū)別有實(shí)現(xiàn)國(guó)級(jí)化的時(shí)候, struts message 只能出現(xiàn) 5 個(gè)動(dòng)態(tài)的值

          也就像下面的信息

          Your {0} ticket(s) for flight {1} have been booked.

          The total cost is {2}. Your confirmation number is {3}.

          Your flight leaves at {4} and arrives at {5}

          需要分成兩段才能完成

          <bean:message key="confirmation.msg1"

          arg0="count" arg1="flightNumber" arg2="cost"/>

          <bean:message key="confirmation.msg2"

          arg0="confirmation" arg1="departure" arg2="arrival"/>

          webwork 是無(wú)限制的,像上面的可以寫(xiě)成這樣子

          <ww:text name="confirmation.msg">

          <ww:param value="count"/>

          <ww:param value="flightNumber"/>

          <ww:param value="cost"/>

          <ww:param value="confirmation"/>

          <ww:param value="departure"/>

          <ww:param value="arrival"/>

          </ww:text>

          還有在web.xml里同指定webwork的tld所在位置

          <taglib>

          <taglib-uri>webwork</taglib-uri>

          <taglib-location>
          /WEB-INF/lib/webwork-2.1.7.jar

          </taglib-location>

          </taglib>
          在很多書(shū)上都講上面可行,可是我卻報(bào)下面的錯(cuò)...換成下面那種方式就ok了

          org.apache.jasper.JasperException: Unable to initialize TldLocationsCache: null
          也可以指定webwork.tld所在的位置也可以,,如
          /WEB-INF/webwork.tld(webwork.tld拷到這下面來(lái)).

          一個(gè)簡(jiǎn)單的例子
          ?
          import com.opensymphony.xwork.Action;
          public class HelloWorldAction implements Action{
          ??? String greeting;
          ??? public String getGreeting() {
          ??????? return greeting;
          ??? }
          ??? public String execute() throws Exception {
          ??????? greeting = "Hello World!";
          ??????? return SUCCESS;
          ??? }
          }
          實(shí)現(xiàn)的action接口里面只有一個(gè)方法
          ?
          interface Action {
          String execute() throws Exception;
          }
          greetings.jsp
          <%@ taglib prefix="ww" uri="webwork" %>
          <html>
          <head>
          ??? <title>First WebWork Example</title>
          </head>
          <body>
          <p><ww:property value="greeting"/></p>
          </body>
          </html>
          xwork.xml 放到就用的classpath下面(也就web-inf/classes下面)
          <action name="hello" class="HelloWorldAction">
          <result name="success" type="dispatcher">
          <param name="location">/greetings.jsp</param>
          </result>
          <interceptor-ref name="debugStack"/>
          <interceptor-ref name="defaultStack"/>
          </action>
          還有在web.xml里面加上webwork的一個(gè)加載類(lèi)
          <servlet>
          ??????? <servlet-name>action</servlet-name>
          ??????? <servlet-class>com.opensymphony.webwork.dispatcher.ServletDispatcher</servlet-class>
          ??? </servlet>
          ??? <servlet-mapping>
          ??????? <servlet-name>action</servlet-name>
          ??????? <url-pattern>*.action</url-pattern>
          ??? </servlet-mapping>
          ActionSupport
          1:提供對(duì)錯(cuò)誤信息的支持
          ? action and field specific errors
          ? field errors are automatically supported by views
          2:國(guó)際化的支持
          ? 1 resource bundle per action
          ? pervasive UI support for retrieving messages
          ?--------------------------------------------------------------------------------
          ActionSupport Example:
          import com.opensymphony.xwork.ActionSupport;
          public class HelloWorldAction extends ActionSupport{
          ??? String greeting;
          ??? public void setGreeting(String greeting) {
          ??????? this.greeting = greeting;
          ??? }
          ??? public String getGreeting() {
          ??????? return greeting;
          ??? }
          ??? public String execute() throws Exception {
          ??????? if (greeting.equals("") || greeting == null) {
          ??????????? addFieldError("greeting", getText("greeting"));
          ??????????? return ERROR;
          ??????? }
          ??????? return SUCCESS;
          ??? }
          }
          這里的getText("greeting")的greeting要與HelloWorldAction.properties(放在與HelloWorldAction.class同級(jí)目錄下面,名稱(chēng)也一樣)里的greeting=Enter your greeting please相同
          上面的set.get其實(shí)與struts當(dāng)中的ActionFrom類(lèi)似..
          <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
          <%@ taglib prefix="ui" uri="webwork" %>
          <html>
          <head>
          ??? <title>First WebWork Example</title>
          </head>
          <body>
          <form action="hello.action" method="post">
          <table>
          ??? <ui:textfield label="歡迎語(yǔ)句" name="greeting"/>
          ??? <ui:submit value="'Submit'"/>
          </table>
          </form>
          </body>
          </html>
          這里的greeting要與HelloWorldActio.java里的屬性一致
          如出現(xiàn)錯(cuò)誤會(huì)顯示在當(dāng)前頁(yè),
          Enter your greeting please

          如填上內(nèi)容,就會(huì)相應(yīng)的調(diào)用setGreeting()方法的..
          <%@ taglib prefix="ww" uri="webwork" %>
          <html>
          <head>
          ??? <title>First WebWork Example</title>
          </head>
          <body>
          <p><ww:property value="greeting"/></p>
          </body>
          </html>
          把填的內(nèi)容顯示出來(lái)
          在xwork.xml里的<action>
          也相應(yīng)的變成
          <action name="hello" class="helloWorld.HelloWorldAction">
          ???<result name="success" type="dispatcher">
          ????<param name="location">/greetings.jsp</param>
          ???</result>
          ???<result name="error" type="dispatcher">
          ????????? <param name="location">/index.jsp</param>
          ??????????? </result>
          ??</action>
          ------------------------------------------------------------
          ?
          Model-Driven Actions vs. Field-Driven Actions
          ?
          2 types of Actions possible:
          (1)Field-Drivern上面的例子就是
          (2)ModelDriven
          package helloWorld;
          public class Pet {
          ??? private long id;
          ?private String name;
          ??? public long getId() {
          ??????? return id;
          ??? }
          ??? public void setId(long id) {
          ??????? this.id = id;
          ??? }
          ??? public String getName() {
          ??????? return name;
          ??? }
          ??? public void setName(String name) {
          ??????? this.name = name;
          ??? }
          }
          --
          package helloWorld;
          import com.opensymphony.xwork.*;
          public class AddPetAction extends ActionSupport implements ModelDriven{
          ?Pet pet = new Pet();
          ??? public Object getModel() {
          ??????? return pet;
          ??? }
          ??? protected void doValidation() {
          ??????? if (pet.getId() == 0) {
          ??????????? addFieldError("id", "Please enter in an id number for you new Pet.");
          ??????? }
          ??? }
          ??? public String doExecute() throws Exception {
          ??????? if (hasErrors())
          ??????????? return ERROR;
          ??????? return SUCCESS;
          ??? }

          }
          需實(shí)現(xiàn)ModelDriven這個(gè)接口,它也只有一個(gè)方法
          public Object getModel();
          ?在xwork.xml加上
          <action name="addpet" class="helloWorld.AddPetAction">
          ???<result name="success" type="dispatcher">
          ????<param name="location">/petadded.jsp</param>
          ???</result>
          ???<result name="error" type="dispatcher">
          ????<param name="location">/addpet.jsp</param>
          ???</result>
          ???<interceptor-ref name="debugStack" />
          ???<interceptor-ref name="defaultStack" />
          ??</action>
          還有兩個(gè)頁(yè)面分別用來(lái)添加和顯示用的
          <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
          <%@ taglib prefix="ui" uri="webwork" %>
          <html>
          <head>
          ??? <title>First WebWork Example</title>
          </head>
          <body>
          <form action="addpet.action" method="post">
          <table>
          ??? <ui:textfield label="Pet ID Number" name="id"/>
          ??? <ui:textfield label="Name of Pet" name="name"/>
          ??? <ui:submit value="'Submit'"/>
          </table>
          </form>
          </body>
          </html>
          -------petadded.jsp
          <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
          <%@ taglib prefix="ww" uri="webwork" %>
          <html>
          <head>
          ??? <title>First WebWork Example</title>
          </head>
          <body>
          <p>Added a pet with the following properties:</p>
          <ul>
          ??? <li>ID: <ww:property value="id"/></li>
          ??? <li>Name: <ww:property value="name"/></li>
          </ul>
          </form>
          </body>
          </html>
          posted @ 2006-08-02 19:02 蜘蛛 閱讀(3277) | 評(píng)論 (0)編輯 收藏

          //SessionCounter.java\ozdvw
          package SessionCount;e?
          import javax.servlet.*; L9k0
          import javax.servlet.http.*; plT
          import java.io.*; w;
          import java.util.*; JC;@
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  @b!Q5
          public class SessionCounter extends HttpServlet ?implements HttpSessionListener { 2#
          private static final String CONTENT_TYPE = "text/html; charset=GBK"; bd35
          private static int activeSessions = 1; xZi"Yx
          //Initialize global variables +iRX;1
          public void init() throws ServletException { n3
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  {Ytdk
          } ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  ri04&
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  C
          //Process the HTTP Get request @8Ob%
          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { zH
          ? response.setContentType(CONTENT_TYPE); EPjJ
          ? HttpSession session=request.getSession(); ]g
          } ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  )9lR?P
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  !S
          //Clean up resources UxUNe
          public void destroy() { :=e2NM
          } ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  W'F
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  aHW&x9
          public void sessionCreated(HttpSessionEvent httpSessionEvent) { HH
          ? activeSessions++; DyZpv
          } ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  4WJ
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  8)#.
          public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { \s,_t
          ? activeSessions--; *z
          ? System.out.println("test test");$s0T@W
          // ?System.out.println("---111"); ZF+
          } ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  MX
          public static int getActiveSessions() { tQ
          ?return activeSessions; )a4
          } ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  y%s
          } ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  n-=u*
          ////$E
          ////1^[
          //count.jsp?
          <%@ page import="SessionCount.SessionCounter"%> r-cXS
          <%@ page language="java" ?contentType="text/html; charset=gb2312"{Z
          ? ?pageEncoding="gb2312"%>~|Q"eP
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">, l
          <html>z>
          <head>&5)~
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">%G*M?
          <title>Insert title here</title>ij7z
          </head>$i:
          <script language="javascript" type="text/javascript">?.k
          <!--#*>}
          function MM_callJS(jsStr) { //v2.0mnu)IK
          ?return eval(jsStr)-A
          }?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  ]M\-
          //-->#}q
          </script>rs(
          <script language="javascript">Ax%Qs3
          function removeline(){Q \@
          if(event.clientX<0&&event.clientY<0).45
          {?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  y!Rw%u
          document.write('<iframe width="100" height="100" src="remove.jsp"></iframe><OBJECT classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height=0 ?id=WebBrowser width=0></OBJECT>');Dgo!x
          document.all.WebBrowser.ExecWB(45,1);[
          }?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  ad6+
          }?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  1`maF
          </script>0.
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  9
          <body onUnload="MM_callJS('removeline()')">I=QwN
          在線(xiàn):<%= SessionCounter.getActiveSessions() %> Abd\
          </body>.
          </html>YZmy
          ////////////////////////////////6K6(k
          ///////////////////////////////HoW?y
          remove.jspZ{>=
          /////?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  ]|65(
          <%@ page language="java" contentType="text/html; charset=gb2312"!
          ? ?pageEncoding="gb2312"%>4"cD
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">|r<G
          <html>8
          <head>m.
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">$#9
          <title>Insert title here</title>H/hoe0
          </head>z_g_
          <body>?=9
          <%session.invalidate();%>i
          </body>-r
          </html>Lw;7{.
          ///////////////////////////}PiE
          /////////////////////////////[
          web.htmlP&
          ^^^^^^^^^^^^加上Bz2J
          <listener> y+
          ? <listener-class>SessionCount.SessionCounter</listener-class> q1d{
          </listener> h1
          if(event.clientX<0&&event.clientY<0)判斷瀏覽器是關(guān)閉還是刷新 ,因?yàn)樗⑿乱矔?huì)調(diào)用onunload&&
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  c07F
          document.all.WebBrowser.ExecWB(45,1);是無(wú)提示的關(guān)閉瀏覽器!Q!*pf
          classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 |0gLI
          這個(gè)是調(diào)用不彈出對(duì)話(huà)框的方法,實(shí)際是調(diào)用系統(tǒng)的方法如下 ]9M
          document.all.WebBrowser.ExecWB(45,1); f:
          因?yàn)樵趈avascript當(dāng)中不能調(diào)用java方法,所以選擇另外寫(xiě)一個(gè)jsp文件用于調(diào)用,;?(5yi
          invalidate()方法,(?A|`K
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  xv
          現(xiàn)在這個(gè)結(jié)果是正確的,因?yàn)槲野裵rivate static int activeSessions = 1; //這里改成了1,本來(lái)照理應(yīng)該設(shè)為0的,可以我運(yùn)行第一次http://localhost:8080/servlet/count.jsp的時(shí)候得到的是0,所以我才把它改成1的,dKOp0
          那們老師或同學(xué)知道的話(huà),麻煩告訴怎么為事,為什么在第一次創(chuàng)建session時(shí)不能觸發(fā)事件sessionCreated()Rw

          現(xiàn)在這個(gè)結(jié)果是正確的,因?yàn)槲野裵rivate static int activeSessions = 1; //這里改成了1,本來(lái)照理應(yīng)該設(shè)為0的,可以我運(yùn)行第一次http://localhost:8080/servlet/count.jsp的時(shí)候得到的是0,所以我才把它改成1的, h(
          ,為什么在第一次創(chuàng)建session時(shí)不能觸發(fā)事件sessionCreated()g?

          session是個(gè)雙向機(jī)制,第一次訪問(wèn)的時(shí)候,是從客戶(hù)端發(fā)起的,瀏覽器不知道這個(gè)網(wǎng)頁(yè)是否需要session,所以瀏覽器不會(huì)創(chuàng)建sessionId,當(dāng)這個(gè)請(qǐng)求到達(dá)服務(wù)器的時(shí)候,沒(méi)有sessionId,d}--5
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  r0_/S
          SessionCounter 是被嵌在jsp里的,所以第一次顯示的時(shí)候,得到j(luò)sp頁(yè)面的session創(chuàng)建是在jsp頁(yè)面滯后,也就是說(shuō)SessionCounter是滯后于jsp頁(yè)面的.xKTZrv
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  V@)
          順便說(shuō)一句,extends HttpServlet 是多余的。]&

          在頁(yè)面里頁(yè)設(shè)置一個(gè)退出按鈕.調(diào)用quit.jsp=
          它的內(nèi)容是:h>
          我們用一個(gè)quit.jsp來(lái)處理用戶(hù)退出系統(tǒng)的操作,quit.jsp負(fù)責(zé)注銷(xiāo)session,及時(shí)釋放資源。>D6T
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  uj&B
            ·注銷(xiāo)session。Z5K&
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  ##
            ·關(guān)閉瀏覽器窗口。@Q(
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  TP^wA
            其代碼如下所示:"
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  IWeVHc
          1. <%@ page contentType="text/html; charset=GBK" %>z
          2. <%E
          3.  session.invalidate();F"[}H
          4. %>A
          5. <script language="javascript" >4_
          6.  window.opener = null;`ngL
          7.  window.close();M|j%
          8. </script> OnZH?
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  3-L-
            其中第3行負(fù)責(zé)注銷(xiāo)session,原先放入session的對(duì)象將解綁定,等待垃圾回收以釋放資源。對(duì)于本例而言,session中有一個(gè)名為ses_userBean的userBean對(duì)象(它是在switch.jsp中放入session的),調(diào)用session.invalidate()后,userBean從session中解綁定,它的valueUnbound()方法會(huì)被觸發(fā)調(diào)用,然后再等待垃圾回收。A/cr
          ?達(dá)內(nèi)科技論壇 -- 達(dá)內(nèi)科技論壇  +Nb
            第5~8行是一段javascript腳本程序,負(fù)責(zé)關(guān)閉窗口,如果網(wǎng)頁(yè)不是通過(guò)腳本程序打開(kāi)的(window.open()),調(diào)用window.close()腳本關(guān)閉窗口前,必須先將window.opener對(duì)象置為null,如第6行所示,否則瀏覽器會(huì)彈出一個(gè)確定關(guān)閉的對(duì)話(huà)框,筆者發(fā)現(xiàn)這個(gè)問(wèn)題困擾了不少的Web程序員,故特別指出。s `|*)

          posted @ 2006-07-31 19:42 蜘蛛 閱讀(6948) | 評(píng)論 (8)編輯 收藏

          to robbin
          ibatis的網(wǎng)站
          www.ibatis.com上面可以找到很好的文檔,再加上有非常不錯(cuò)的例子,所以使用是相當(dāng)?shù)暮?jiǎn)單。
          sourceforge上面的討論
          http://swik.net/DAO
          http://www.learntechnology.net/struts-ibatis.do
          http://www.nabble.com/iBATIS-f360.html
          http://www.cjsdn.net/post/page?bid=20&sty=3&tpg=2&s=73&age=0
          https://sourceforge.net/forum/forum.php?forum_id=206693
          http://www.cjsdn.net/post/view?bid=11&id=172565&sty=1&tpg=1&age=0Windows
          環(huán)境下的tomcat + apache配置(絕對(duì)實(shí)踐操作版)

          ibatis大體上可以分為兩個(gè)部分:SQL Maps + Data Access Objects
          我現(xiàn)在的項(xiàng)目中都用到了,它提供的jpetstore就使用了db layer,可以參考它的實(shí)現(xiàn)方式。
          不過(guò)我覺(jué)得jpetstore的db layer實(shí)現(xiàn)方式還不是太好,至少它的業(yè)務(wù)邏輯層和dao層沒(méi)有明顯區(qū)分,在實(shí)現(xiàn)比較

          大的項(xiàng)目的時(shí)候造成了程序的混亂,如果沒(méi)有一個(gè)良好的模式來(lái)實(shí)現(xiàn)db layer 的時(shí)候,確實(shí)會(huì)造成效率的低下,

          有了良好的架構(gòu),速度確實(shí)很快(特別是SQL Maps + Data Access Objects 都使用的情況)
          BO層的設(shè)計(jì)已經(jīng)不是什么新鮮的了,但我覺(jué)得它確實(shí)可以很好的和DaoManager結(jié)合起來(lái),通過(guò)DaoManager->SQL

          map->jdbc
          它的兩個(gè)核心的配置文件:dao.xml+SqlMapConfig.xml
          通過(guò)靈活的配置文件的組合可以實(shí)現(xiàn)數(shù)據(jù)庫(kù)不同的訪問(wèn)組合
          比如:一個(gè)dao.xml可以對(duì)應(yīng)多個(gè)SqlMapConfig.xml
          一個(gè)dao.xml可對(duì)應(yīng)一個(gè)數(shù)據(jù)庫(kù),多個(gè)dao.xml就可以訪問(wèn)多個(gè)數(shù)據(jù)庫(kù)了(它的petstore就提供了演示distributed

          功能的樣例是oracle+ms sql)
          它的SqlMapConfig.xml中可配置sql-map resource,就是配置你具體的sql語(yǔ)句的xml文件。
          它的sqlMap提供很多方法來(lái)訪問(wèn)數(shù)據(jù)庫(kù),直接返回你想要的結(jié)果

          ***************************
          DAO中的一個(gè)供分頁(yè)查詢(xún)的方法
          ***************************
          ......

          SqlMap sqlMap = getSqlMapFromLocalTransaction();//取到當(dāng)前sqlmap對(duì)象
          List list=sqlMap.executeQueryForList("你的MappedStatement文件中sql語(yǔ)句的名稱(chēng)", object("你可以通過(guò)這

          個(gè)object傳一些查詢(xún)條件"),skipResults,maxResults);

          ...

          有了良好的設(shè)計(jì)模式,它可以和struts完美結(jié)合在一起,無(wú)論是效率還是清晰型上,都非常令人滿(mǎn)意的

          public void saveUser(User user)
          ??? {
          ??????? if (user.getId() == null)
          ??????? {
          ??????????????? Long id = (Long) getSqlMapClientTemplate().insert("addUser", user);
          ??????????? logger.info("new User id set to: " + id);
          ??????? } else {
          ??????????? getSqlMapClientTemplate().update("updateUser", user);
          ??????? }
          ???????
          ??? }???

          domain is the central business tier. service package is more like a web package, just a way to

          expose these services remotely, so that users could use the web interfaces, or the webservice

          interfaces(like amazon's webservices).


          //TestA.javapublic class TestA{public static void main(String[] args){TestA a=new TestA

          ();System.out.println(a.getClass().getClassLoader());TestB b=new TestB();b.print

          ();}}//TestB.javapublic class TestB{public void print(){System.out.println(this.getClass

          ().getClassLoader());}}

          DAO(data access objects)允許你去創(chuàng)建簡(jiǎn)單的組件,為你訪問(wèn)你的數(shù)據(jù),而不用去實(shí)現(xiàn)具體的實(shí)現(xiàn)細(xì)節(jié)。使用

          DAOS你能動(dòng)態(tài)配置不同的持久層機(jī)制。
          注意:DAO框架與sqlmaps框架是完全的分離開(kāi)和互不依賴(lài)性,所以你可以單獨(dú)使用,或一起來(lái)用都沒(méi)有關(guān)系.

          下面是一些重要的daos api
          DaoManager(Facade模式):負(fù)責(zé)配置DAO框架實(shí)例(經(jīng)過(guò)dao.xml),在其它api當(dāng)中充當(dāng)facade.
          DaoTransaction(Marker Interface):通用的接口,為了去使用事物(連接),通用的實(shí)現(xiàn)將包裝jdbc的連接對(duì)象

          .
          DaoException(RuntimeException運(yùn)行期異常):所有的方法和類(lèi)全部拋出dao api專(zhuān)有的異常。
          Dao(Marker Interface):一個(gè)標(biāo)記接口供所有的dao去實(shí)現(xiàn),這個(gè)接口必須為所有的dao類(lèi)去實(shí)現(xiàn)。這個(gè)接口沒(méi)有

          聲名任何方法被實(shí)現(xiàn),只是充當(dāng)一個(gè)標(biāo)記(例如:一些DaoFactory去辯別不同的類(lèi));
          -----------------------------------
          jdbc事務(wù)控制實(shí)現(xiàn)
          sqlmap:通過(guò)sqlmaps框架和它的事物管理服務(wù)去實(shí)現(xiàn),包括不同的DataSource和事物管理配置
          hibernate:提供簡(jiǎn)單容易的和hibernate,它的事物工具(SessionFactory,Session,Transaction)整合
          jdbc:通過(guò)jdbc api,使用它的基本的dataSource和Connction接口去管理事物
          jta:管理分部式事物,需要被管理的datasource,這樣子可以通過(guò)jndi訪問(wèn).
          external:允許事物被外部控制

          dao.xml為配置文件(http://www.ibatis.com/dtd/dao-2.dtd)
          DaoManager負(fù)責(zé)配置dao框架。DaoManager類(lèi)可以為框架解析特定的xml文件,而提供出有用的信息供框架使用。

          那么配置文件(xml文件)需要指定下面的內(nèi)容:
          1)dao的上下文
          2)事物為每一個(gè)上下文件的實(shí)現(xiàn)
          3)TransactionManager配置屬性
          4)Dao為每一個(gè)實(shí)現(xiàn)的dao接口
          一個(gè)Dao上下文是一組相關(guān)的配置信息和Dao實(shí)現(xiàn)。通常一個(gè)上下文關(guān)聯(lián)到一個(gè)數(shù)據(jù)源(datasource)或一個(gè)文件。
          dao配置文件(通常被叫做dao.xml,但不是必須的),為下面的結(jié)構(gòu)
          <!DOCTYPE daoConfig
          PUBLIC "-//iBATIS.com//DTD DAO Configuration 2.0//EN"
          "<
          daoConfig>
          <properties resource="com/domain/properties/MyProperties.properties"/>
          <!-- Example JDBC DAO Configuration -->
          <context>
          <transactionManager type="JDBC">
          <property name="DataSource" value="SIMPLE"/>
          <property name="JDBC.Driver" value="${driver}"/>
          <property name="JDBC.ConnectionURL" value="${url}"/>
          <property name="JDBC.Username" value="${username}"/>
          <property name="JDBC.Password" value="${password}"/>
          <property name="JDBC.DefaultAutoCommit" value="true" />
          <property name="Pool.MaximumActiveConnections" value="10"/>
          <property name="Pool.MaximumIdleConnections" value="5"/>
          <property name="Pool.MaximumCheckoutTime" value="120000"/>
          </transactionManager>
          <dao interface="com.domain.dao.OrderDao"
          implementation="com.domain.dao.jdbc.JdbcOrderDao"/>
          <dao interface="com.domain.dao.LineItemDao"
          implementation="com.domain.dao.jdbc.JdbcLineItemDao"/>
          <dao interface="com.domain.dao.CustomerDao"
          implementation="com.domain.dao.jdbc.JdbcCustomerDao"/>
          </context>
          <!-- Example SQL Maps DAO Configuration -->
          <context>
          <transactionManager type="SQLMAP">
          <property name="SqlMapConfigResource" value="com/domain/dao/sqlmap/SqlMapConfig.xml"/>
          </transactionManager>
          <dao interface="com.domain.dao.PersonDao"
          implementation="com.domain.dao.sqlmap.SqlMapPersonDao"/>
          <dao interface="com.domain.dao.BusinessDao"
          implementation="com.domain.dao.sqlmap.SqlMapBusinessDao"/>
          <dao interface="com.domain.dao.AccountDao"
          implementation="com.domain.dao.sqlmap.SqlMapAccountDao"/>
          </context>
          </daoConfig>
          一個(gè)dao.xml里可以有多個(gè)context,通常一個(gè)上下文指定一個(gè)特定的dataSource
          為了去管理多樣的配置(因?yàn)橛胁煌沫h(huán)境),你可以使用可選的元素<properties).
          這個(gè)允許使用占用符,例如:
          driver=org.postgresql.Driver
          url=jdbc:postgresql://localhost:5432/test
          這時(shí)你可以在dao.xml里用占用符取代具體的值,例如上面的可以改寫(xiě)成下面的
          <property name="JDBC.Driver" value="${driver}"/>
          <property name="JDBC.ConnectionURL" value="${url}"/>
          在上下文當(dāng)中,第一個(gè)context里同使用的是jdbc事物控制,所以在指定的property元素也要使用jdbc,不同的事

          物管理實(shí)現(xiàn)會(huì)需要不同的properties,

          事物管理實(shí)現(xiàn)(Transaction Manager Implementation and Configuration)是一個(gè)組件會(huì)管理pool(事物對(duì)象)

          ,一事物管理通常只是包裝特定的DataSource,簡(jiǎn)單的事物通常包裝一特定的實(shí)現(xiàn)類(lèi)如jdbc連接實(shí)現(xiàn)

          jdbc Transaction Manager:利用提供的datasource api提供連接池服務(wù)
          有三種datasource是支持的(simple,dbcp,jndi),simple是實(shí)現(xiàn)了ibatis的SimpleDataSource。dbcp使用了

          jakarta dbcp datasource,最后,jndi是實(shí)現(xiàn)了查找datasource是從jndi上去查
          下面是不同的配置方法
          <!-- Example iBATIS SimpleDataSource JDBC Transaction Manager -->
          <transactionManager type="JDBC">
          <property name="DataSource" value="SIMPLE"/>
          <property name="JDBC.Driver" value="${driver}"/>
          <property name="JDBC.ConnectionURL" value="${url}"/>
          <property name="JDBC.Username" value="${username}"/>
          <property name="JDBC.Password" value="${password}"/>
          <property name="JDBC.DefaultAutoCommit" value="true" />
          <!-- The following are optional -->
          <property name="Pool.MaximumActiveConnections" value="10"/>
          <property name="Pool.MaximumIdleConnections" value="5"/>
          <property name="Pool.MaximumCheckoutTime" value="120000"/>
          <property name="Pool.TimeToWait" value="10000"/>
          <property name="Pool.PingQuery" value="select * from dual"/>
          <property name="Pool.PingEnabled" value="false"/>
          <property name="Pool.PingConnectionsOlderThan" value="0"/>
          <property name="Pool.PingConnectionsNotUsedFor" value="0"/>
          </transactionManager>

          <!-- Example Jakarta DBCP JDBC Transaction Manager -->
          <transactionManager type="JDBC">
          <property name="DataSource" value="DBCP"/>
          <property name="JDBC.Driver" value="${driver}"/>
          <property name="JDBC.ConnectionURL" value="${url}"/>
          <property name="JDBC.Username" value="${username}"/>
          <property name="JDBC.Password" value="${password}"/>
          <property name="JDBC.DefaultAutoCommit" value="true" />
          <!-- The following are optional -->
          <property name="Pool.MaximumActiveConnections" value="10"/>
          <property name="Pool.MaximumIdleConnections" value="5"/>
          <property name="Pool.MaximumWait" value="60000"/>
          <!-- Use of the validation query can be problematic. If you have difficulty, try without it. -->
          <property name="Pool.ValidationQuery" value="select 1 from ACCOUNT"/>
          <property name="Pool.LogAbandoned" value="false"/>
          <property name="Pool.RemoveAbandoned" value="false"/>
          <property name="Pool.RemoveAbandonedTimeout" value="50000"/>
          </transactionManager>


          <!-- Example JNDI DataSource JDBC Transaction Manager -->
          <transactionManager type="JDBC">
          <property name="DataSource" value="JNDI"/>
          <property name="DBJndiContext" value="java:comp/env/jdbc/MyDataSource"/>
          </transactionManager>

          jta管理事物:它使用的是jta api.實(shí)種實(shí)現(xiàn)總是需要通過(guò)jndi去獲得datasource和一個(gè)UserTransaction實(shí)例也

          是通過(guò)jndi訪問(wèn)的,因些需要在服務(wù)器配置一下,不過(guò)這使得配置dao框架十分簡(jiǎn)單了。下面是一個(gè)簡(jiǎn)單的配置
          <transactionManager type="JTA">
          <property name="DBJndiContext" value="java:comp/env/jdbc/MyDataSource"/>
          <property name="UserTransaction" value="java:comp/env/UserTransaction"/>
          </transactionManager>

          sqlmap管理事物:通過(guò)dao框架包裝sql maps事物服務(wù),所有的你都要指定一個(gè)sql maps配置文件。下面是一個(gè)簡(jiǎn)

          單的配置
          <transactionManager type="SQLMAP">
          <property name="SqlMapConfigResource" value="com/domain/dao/sqlmap/SqlMapConfig.xml"/>
          </transactionManager>

          hibernate管理事物:同樣的,通過(guò)dao框架包裝hibernate事物服務(wù),基本上properties在配置文件當(dāng)中和

          hibernate.properties文件是一樣的,另外,持久化類(lèi)(你可能通過(guò)添加到hibernate配置文件當(dāng)中去的)要

          以"class."開(kāi)頭,下面是一個(gè)例子:
          <transactionManager type="HIBERNATE">
          <property name="hibernate.dialect" value="net.sf.hibernate.dialect.PostgreSQLDialect"/>
          <property name="hibernate.connection.driver_class" value="${driver}"/>
          <property name="hibernate.connection.url" value="${url}"/>
          <property name="hibernate.connection.username" value="${username}"/>
          <property name="hibernate.connection.password" value="${password}"/>
          <property name="class.1" value="com.domain.Person"/>
          <property name="class.2" value="com.domain.Business"/>
          <property name="class.3" value="com.domain.Account"/>
          </transactionManager>

          external 管理事物:允許使用dao框架控制。這個(gè)執(zhí)行基本是沒(méi)有行為,因些不需要properties,如果你使用一個(gè)

          flat file,你可以使用external事物管理,
          <transactionManager type="EXTERNAL"/>

          dao實(shí)現(xiàn)模板:你可能要問(wèn)我怎么使用上面的事物,好了每一種事物類(lèi)型都要相應(yīng)的dao模板與之對(duì)應(yīng)。例如:

          jta,jdbc模板提供簡(jiǎn)單的訪問(wèn)jdbc連接對(duì)象。相似的sqlmap模板提供訪問(wèn)簡(jiǎn)單的SqlMapExecutor實(shí)例,而

          hibernate template提供訪問(wèn)Session object.
          使用dao template完全是可選的,但99%的時(shí)間里,是不可不選擇的/

          更多的模板請(qǐng)看下面的.
          DaoManager編程:iBATIS dao框架有許多的目的.第一個(gè),它試圖持久層的細(xì)節(jié).這包括所有的接口,實(shí)現(xiàn)和異

          常細(xì)節(jié)(在你的持久層解決方案當(dāng)中).
          例如:如果你使用jdbc,dao框架將為你隱藏類(lèi)如DataSource,Connection和SQLException.類(lèi)似的,如果你使用

          Hibernate orm,dao框架會(huì)為你隱藏類(lèi)如Configuration,SessionFactory,Session和HibernateException.所有的

          這些細(xì)節(jié)都會(huì)隱藏到了dao接口層.甚至在顯示層的許多的datasource也會(huì)被隱藏.
          第二個(gè)目的是:簡(jiǎn)化持久層編程模型,使在同一時(shí)間保持一致.不同的持久層解決方案有不同的編程語(yǔ)義和行為.
          dao框架試圖隱藏更多,允許在你的應(yīng)用service和domain層,寫(xiě)出一致的風(fēng)格.

          DaoManager類(lèi)負(fù)責(zé)dao框架的配置文件(通過(guò)dao.xml),另外,DaoManage扮演著中心門(mén)面的角色,它特殊之處是,還提

          供方法允許你訪問(wèn)事物和dao實(shí)例.

          讀取配置文件:
          使用DaoManagerBuilder類(lèi)的靜態(tài)方法buildDaoManager()方法讀取dao.xml文件,buildDaoManager()方法需要一個(gè)

          Reader實(shí)例作為參數(shù).
          例如:
          Reader reader = new FileReader(C:/myapp/dao.xml);
          DaoManager daoManager = DaoManagerBuilder.buildDaoManager(reader);

          如在web應(yīng)用環(huán)境當(dāng)中(或其它),一般配置文件都會(huì)從classpath當(dāng)中去加載的.我們可以使用

          com.ibatis.common.resources.Resources類(lèi)
          Reader reader = Resources.getResourceAsReader(“com/domain/config/dao.xml”);
          DaoManager daoManager = DaoManagerBuilder.buildDaoManager(reader);

          Context和DaoManager
          DaoManager實(shí)例是從dao.xml文件建立的.當(dāng)你需要一個(gè)dao實(shí)例時(shí),你可以通過(guò)DaoManager,和事物控制也會(huì)從它此

          處提供的.因些不需直接訪問(wèn)context和事物管理..
          你的dao知道它怎么去做.類(lèi)似的,需要看你的daos怎么工作的,事物會(huì)恰當(dāng)?shù)拈_(kāi)始和提交的.而且,事物僅在你的dao

          被調(diào)用時(shí)才啟動(dòng).

          獲取dao實(shí)例
          一旦你得到了DaoManager實(shí)例,你就可以根據(jù)dao名字,利用DaoManager的getDao方法獲取該dao實(shí)例了,如:
          ProductDao productDao = (ProductDao) daoManager.getDao (ProductDao.class);

          DaoManager提供了處理事務(wù)的方法.這些方法允許你劃分事務(wù),和避免傳遞事務(wù)對(duì)象(eg:jdbc Connction)到你的所

          有的daos當(dāng)中去.例如:
          ProductDao productDao = (ProductDao) daoManager.getDao (ProductDao.class);
          try {
          daoManager.startTransaction();
          Product product = productDao.getProduct (5);
          product.setDescription (“New description.”);
          productDao.updateProduct(product);
          daoManager.commitTransaction();
          } finally {
          daoManager.endTransaction();
          }
          調(diào)用startTransaction()只是讓DaoManager知道,你將要啟動(dòng)編程控制事務(wù).
          dao實(shí)例化時(shí)才啟動(dòng)事務(wù)的,甚至事務(wù)僅僅是contexts需要的時(shí)候.
          commitTransaction()提交事務(wù),endTransaction()需要在try{}catch(){}里面的,,
          如果發(fā)現(xiàn)了異常,那么就會(huì)回滾.

          自動(dòng)提交事務(wù)
          像jdbc的setAutoCommit(true)一樣,不過(guò)也有不同之處,你可以使用多個(gè)update作為一個(gè)事務(wù),你不需要指定提交

          的行為方式,只要你不調(diào)用startTransaction()就行了
          Product product = productDao.getProduct (5); // Transaction 1
          product.setDescription (“New description.”);
          productDao.updateProduct(product); // Transaction 2
          product = productDao.getProduct (5); // Transaction 3
          注意了,這里沒(méi)有異常的事件發(fā)生的,如發(fā)生異常,就會(huì)回滾,和釋放連接資源的.

          實(shí)現(xiàn)自己的dao接口:
          dao接口非常的簡(jiǎn)單,因?yàn)樗鼪](méi)有聲名任何的方法,只是一個(gè)marker interface,所以實(shí)現(xiàn)的只是你自己的接口罷了,

          在你的接口當(dāng)中沒(méi)有限制你要定的任何方法,拋出的異常是運(yùn)行期的DaoException類(lèi)型的異常.
          An example of a good Dao interface is:
          public interface ProductDao extends Dao {
          // Updates
          public int updateProduct (Product product); // DAO Framework code may throw DaoException
          public int insertProduct (Product product);
          public int deleteProduct (int productId);
          /
          / Queries
          public Product getProduct (int productId);
          public List getProductListByProductDescription (String description);
          }

          Templates和Implementations
          在上面也提到了,每一種模板都對(duì)應(yīng)一種特殊的Transaction Manager.
          每一種模板提供了一種便利的方法去交互.
          template Class?????? Transaction Manager??????? Convenience Method
          JdbcDaoTemplate????? JDBC?????????????????????? Connection getConnection()
          JtaDaoTemplate?????? JTA??????????????????????? Connection getConnection();
          SqlMapDaoTemplate??? SQLMAP???????????????????? SqlMapExecutor getSqlMapExecutor()
          HibernateDaoTemplate? HIBERNATE??????????? ?Session getSession()

          The following is an example implementation using the SqlMapDaoTemplate:
          public class SqlMapProductDao implements ProductDao extends SqlMapDaoTemplate {
          public SqlMapProductDao (DaoManager daoManager) {
          super (daoManager);
          }
          /
          * Insert method */
          public int updateProduct (Product product) {
          try {
          getSqlMapExecutor().insert (“insertProduct”, product);
          } catch (SQLException e) {
          throw new DaoException (“Error inserting product. Cause: “ + e, e);
          }
          }
          /
          / … assume remaining methods to save space
          }
          注意:在上面的例子里只有一些個(gè)構(gòu)造器,參數(shù)為DaoManager,它是在初始化實(shí)例時(shí)通過(guò)DaoManagerBuilder自動(dòng)注

          入?yún)?shù)進(jìn)去..第一個(gè)需要DaoManager作為構(gòu)造器的參數(shù),也就迫使它的子類(lèi)都要一個(gè)帶參(DaoManager)的構(gòu)造器,

          當(dāng)你使用模板時(shí),構(gòu)造器是必須的,你不需要提供其它的構(gòu)造器了..你的daos僅僅需要DaoManagerBuilder去實(shí)例化

          它.

          考慮dao的設(shè)計(jì)方式:
          推薦使用一個(gè)繼承dao接口的接口,另一個(gè)為一個(gè)繼承dao接口的抽象類(lèi)(封閉一些異常,事務(wù)等等)..
          實(shí)際上你只需要一個(gè)就行了,另外你也可以選擇下面這種方式..
          你可以使用BaseJdbcDao(abstract)繼承dao接口,需讓ProductDao不要去斷承dao接口,讓ProductJdbcDao去實(shí)現(xiàn)

          ProductDao和繼承BaseJdbcDao就可以了,讓Product接口仍然與dao分離開(kāi)來(lái)....
          在上面的例子當(dāng)中可以將BaseJdbcDao繼承JdbcDaoTemplate(它已經(jīng)實(shí)現(xiàn)了dao接口)


          現(xiàn)在做一個(gè)例子:
          create table test
          (
          id int auto_increment;
          name varchar(20)
          );

          建一個(gè)對(duì)應(yīng)的vo
          package zhai;

          public class test {
          ?int id;
          ?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è)配置數(shù)據(jù)庫(kù)的配置文件
          config.xml
          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE sqlMapConfig
          ??? PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
          ??? "
          <sqlMapConfig>
          ? <transactionManager type="JDBC">
          ??? <dataSource type="SIMPLE">
          ????? <property value="com.mysql.jdbc.Driver" name="JDBC.Driver"/>
          ????? <property value="jdbc:mysql://localhost:3306/test" name="JDBC.ConnectionURL"/>
          ????? <property value="root" name="JDBC.Username"/>
          ????? <property value="root" name="JDBC.Password"/>
          ??? </dataSource>
          ? </transactionManager>
          ? <sqlMap url="file:C:\Test\sql.xml"/>
          </sqlMapConfig>


          --
          sql.xml

          --------
          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
          ??? "

          <sqlMap namespace="test">
          ? <typeAlias alias="test" type="test.test"/>
          ? <select id="getByName" resultClass="test" parameterClass="string">
          ??? SELECT
          ???? ID,
          ???? NAME
          ??? FROM TEST
          ??? WHERE NAME = #name#
          ? </select>
          </sqlMap>

          ----------------
          ------------------
          package zhai;

          public interface MyDao {
          ? public void MyInsert(test t);
          }
          ==================
          package zhai;

          import java.sql.SQLException;

          import com.ibatis.dao.client.DaoManager;
          import com.ibatis.dao.client.template.SqlMapDaoTemplate;

          public class TestDao extends SqlMapDaoTemplate implements MyDao{

          ?public TestDao(DaoManager arg0) {
          ??super(arg0);
          ??// TODO Auto-generated constructor stub
          ?}

          ?public void MyInsert(test t) {
          ??try {
          ???getSqlMapExecutor().insert ("insertTest",t);
          ??} catch (SQLException e) {
          ???System.out.println("插入時(shí)出異常");
          ???e.printStackTrace();
          ??}
          ?}

          }

          ============
          package zhai;
          import java.io.*;

          import com.ibatis.sqlmap.client.*;
          public class TestDemo {

          ?public static void main(String[] args) throws Exception {
          ??Reader reader=new FileReader("C:\\Test\\config.xml");
          ???? SqlMapClient sqlmap=SqlMapClientBuilder.buildSqlMapClient(reader);
          ???? test emp = (test) sqlmap.queryForObject("getById", new Integer(1));
          ??????? System.out.println("歡迎你="+emp.getName());
          ?}

          }
          -------------------------------------------------

          -------------------------------------------------

          -------------------------------------------------

          -------------------------------------------------

          -------
          寫(xiě)一個(gè)運(yùn)行dao的
          <!DOCTYPE daoConfig
          PUBLIC "-//iBATIS.com//DTD DAO Configuration 2.0//EN"
          "
          <daoConfig>
          <!-- Example JDBC DAO Configuration -->
          <context>
          ??? <transactionManager type="SQLMAP">
          ???? <property name="SqlMapConfigResource" value="zhai/config.xml"/>
          ??? </transactionManager>
          <dao interface="zhai.MyDao" implementation="zhai.TestDao"/>
          </context>
          </daoConfig>
          ----------------------
          --------------------
          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
          ??? "

          <sqlMap namespace="test">
          ? <typeAlias alias="test" type="zhai.test"/>
          ? <select id="getById" resultClass="test" parameterClass="int">
          ??? SELECT
          ???? ID,
          ???? NAME
          ??? FROM TEST
          ??? WHERE ID = #id#
          ? </select>
          ? <insert id="insertTest" parameterClass="test">
          ??? insert into TEST (NAME) values (#name#)
          ? </insert>
          ?
          </sqlMap>
          --------------------------------------------------------------------------------------------------

          ---------------------------------------------
          package zhai;
          import java.io.*;

          import com.ibatis.dao.client.DaoManager;
          import com.ibatis.dao.client.DaoManagerBuilder;
          import com.ibatis.sqlmap.client.*;
          public class TestDemo {

          ?public static void main(String[] args) throws Exception {
          ??????????????? //Reader reader = Resources.getResourceAsReader("zhai/dao.xml");
          ??Reader reader=new FileReader("C:\\Test\\dao.xml");
          ??DaoManager daoManager = DaoManagerBuilder.buildDaoManager(reader);
          ??MyDao testdao = (MyDao) daoManager.getDao(MyDao.class);
          ??test t=new test();
          ??t.setName("test");
          ??testdao.MyInsert(t);
          ?}

          }


          注意了如果你用的是
          Reader reader = Resources.getResourceAsReader("zhai/dao.xml");
          那么你就得注意事了,dao.xml要放在項(xiàng)目的bin目錄下面,否則就會(huì)出錯(cuò)
          還有在dao.xml里的? <transactionManager type="SQLMAP">
          ???? <property name="SqlMapConfigResource" value="zhai/config.xml"/>
          ??? </transactionManager>
          也是一個(gè)道理呀


          對(duì)于面向接口編程的項(xiàng)目免不了要一反射相接觸,動(dòng)態(tài)得到實(shí)例:
          public interface a {
          ?public void sayHello();
          }
          ---------------------------
          第一種情況是當(dāng)
          aImpl實(shí)現(xiàn)類(lèi)為默認(rèn)的構(gòu)造方法:
          根據(jù)類(lèi)名aImpl動(dòng)態(tài)得到實(shí)例
          Class c=Class.forName("aImpl");
          a instance=(a)c.newInstance();
          a.sayHello();
          ------------
          第二種情況當(dāng)
          aImpl為帶參數(shù)的構(gòu)造方法時(shí):
          Class o=Class.forName("aImpl");//aImpl為要實(shí)例化的例名,可以從配置文件當(dāng)中獲取
          ???Constructor cous = null;
          ???cous=o.getConstructor(new Class[]{String.class});//構(gòu)造器的參數(shù)類(lèi)型
          ???a ao=(a) cous.newInstance(new Object[]{"xxx"});//"xxx為傳入的參數(shù)值
          ???ao.sayHello();
          第三種就是構(gòu)造器為私有的時(shí)候,我們通過(guò)方法獲取實(shí)例getInstance()(自己定的)
          Class o=Class.forName("aImpl");
          ???Method method=o.getMethod("getInstance",new Class[]{String.class});
          //getInstance為返回為aImpl實(shí)例的方法名
          ??? a ao=(a) method.invoke(null,new Object[]{"xxx"});//注意了前面的參數(shù)為null,是有
          //條件的,就是要求getInstance為static類(lèi)型的,我想大家都會(huì)這樣設(shè)計(jì)的
          ?????? ao.sayHello();
          做連接池的話(huà),一種方式就是使用動(dòng)態(tài)代理類(lèi),當(dāng)Connection調(diào)用close()方法時(shí),我們可以利用方法攔截器,在調(diào)用close方法的時(shí)候把連接放到緩存里面去,供以后再次利用..
          a ao=(a)Proxy.newProxyInstance(aImpl.class.getClassLoader(),aImpl.class.getInterfaces(),
          ?????new InvocationHandler()
          ?????{

          ??????public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          ???????Object re=null;
          ???????System.out.println("before--------"+method.getName());
          //在這里我們添加自己的一些處理方法,如把連接放到緩存去撒!
          ???????//re=method.invoke(new aImpl(),args);
          ???????return re;
          ??????}
          ????
          ?????});
          ???ao.sayHello();

          posted @ 2006-07-15 22:00 蜘蛛 閱讀(3354) | 評(píng)論 (1)編輯 收藏

          因?yàn)轫?xiàng)目當(dāng)中用到分頁(yè),界面用了jstl,本想用jstl給我分頁(yè)的,測(cè)試代碼如下

          <%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ page contentType="text/html; charset=gbk"%>
          <html>
          <body>
          ?<c:set value="8" var="ipage"/>
          ?<c:set value="${param.cpage}" var="cpage" scope="request"/>
          ?<c:if test="${empty sessionScope.allCount}">
          ?<sql:query var="rso">select * from test</sql:query>
          ?<c:set value="${rso.rowCount}" var="allCount" scope="session"/>
          ? </c:if>
          ?<sql:query var="rs" startRow="${ipage*(cpage-1)}" maxRows="${ipage}">
          ?select * from test
          ?</sql:query>
          ?<c:set value="${(allCount+ipage-1)/ipage}" var="allpage"/>
          ?<fmt:parseNumber value="${allpage}" integerOnly="true" var="allpage"/>
          ?xxx<c:out value="${allpage}"/><br>
          ?<c:forEach items="${rs.rows}" var="item">
          ?<c:out value="${item.name}"/>
          ?<c:out value="${item.password}"/><br>
          ?</c:forEach>
          ?? <c:if test="${cpage<=1}">
          ??? <c:set value="${cpage+1}" var="cpage"/>
          ?? </c:if>
          ?? <c:if test="${cpage>allpage}">
          ??? <c:set value="${allpage}" var="cpage"/>
          ?? </c:if>
          ? <A href="
          http://localhost:8080/jstl/test.jsp?cpage=${cpage-1}">上一頁(yè)</A>
          ? <A href="http://localhost:8080/jstl/test.jsp?cpage=${cpage}">當(dāng)前頁(yè)</A>
          ? <A href="http://localhost:8080/jstl/test.jsp?cpage=${cpage+1}">下一頁(yè)</A>
          ?<hr>
          </body>
          </html>
          本以為這樣子比起用oracle里的rownum(如果更換數(shù)據(jù)庫(kù)還得改代碼),來(lái)的要好,因?yàn)槲疫@里的是
          ?<sql:query var="rs" startRow="${ipage*(cpage-1)}" maxRows="${ipage}">
          ?select * from test
          ?</sql:query>
          可是我看了他的源代碼,竟然它利用緩存,每次調(diào)用
          <sql:query startRow="" maxRows="">它都會(huì)把select * from test的數(shù)據(jù)全部一次性查出得到一個(gè)result,再根據(jù)startRow,再調(diào)用result.next(),startRow次后才正式幫我們工作..

          看來(lái)還是原始的方式速度要快一些..
          .......進(jìn)化出來(lái)的產(chǎn)物不一定先進(jìn)
          posted @ 2006-07-15 10:50 蜘蛛 閱讀(3126) | 評(píng)論 (5)編輯 收藏

          僅列出標(biāo)題
          共9頁(yè): 上一頁(yè) 1 2 3 4 5 6 7 8 9 下一頁(yè) 
          主站蜘蛛池模板: 和静县| 淮北市| 南漳县| 平利县| 康保县| 二连浩特市| 固安县| 昆明市| 九台市| 蚌埠市| 堆龙德庆县| 临西县| 孝昌县| 江源县| 金乡县| 襄城县| 独山县| 潞西市| 章丘市| 和平县| 砀山县| 松江区| 衡阳市| 怀化市| 吴堡县| 毕节市| 黄石市| 郎溪县| 光山县| 田林县| 光泽县| 淮安市| 馆陶县| 香港 | 星子县| 秦安县| 灵山县| 葵青区| 安化县| 英超| 青阳县|