探索与发现

研究java技术

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  83 随笔 :: 0 文章 :: 109 评论 :: 0 Trackbacks

#

只适用于window平台:
假设之前你已经装好了ruby,rails,mysql
1)  启动mysql
    d:\>net start mysql
2)  优化mysql
    d:\>gem install mysql
这会提示出很多版本,确保你选择的是高版本而且是以(mswin32)结尾的产品
3)  创建rails项目
    d:\>rails cookbook
   
进入cookbook目录
    这样子默认使用的是mysql数据库,如果想使用PostgreSQL,
    就要这样子指定它创建项目了d:>rails cookbook --database=postgresql
    d:\>cd cookbook
4)  数据库test创建表languages,我的数据库的用户名是root,密码是root
    我们使用rails创建表
    1:打开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:创建一个migration脚本
  d:\cookbokk>ruby script/generate migration build_db
  打开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:执行d:\cookbook> rake db:migrate
  这时你的数据库表应该创建了

5)有两种方式创建scaffolding
 <第一种方式>
  1)ruby script/generate model language
  2)ruby script/generate controller language
  3)修改这个文件为如下内容app/controllers/language_controller.rb:

    class LanguageController < ApplicationController
    scaffold :languages
    end
										
												
4)启动服务器ruby script/server
5)访问http://localhost:3000/languages

<第二种方式>
1)ruby script/generate scaffold language
2) 启动服务器ruby script/server
3)访问http://localhost:3000/languages
posted @ 2007-03-24 18:40 蜘蛛 阅读(1387) | 评论 (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 蜘蛛 阅读(558) | 评论 (0)编辑 收藏

在WebWork 2.2.x 之后,它将直接内建支持spring ioc了,所以更加简单了,,
做个例子
第一步:在web-inf下建一个webwork.properties文件,
内容为
webwork.objectFactory = spring
第二步:也就是加载applicationContext.xml,可以采取前面前的两种之一,,这里采用后面那种
<listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
第三步:创建要装载的实例,在applicationContext.xml(采用监听的方式,记住默认的位置是在web-inf下面)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans default-autowire="autodetect"> <!--记注一定要加上-->
  <bean id="userManager" singleton="true" class="helloWorld.UserManager"/>
</beans>
第四步:在修改我原来的例子
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类如下
package helloWorld;
public class UserManager {
 public UserManager()
 {
  System.out.println("create instance of UserManger");
 }
 public void sayHello()
 {
  System.out.println("hello zjh");
 }
}
再访问http://localhost:8080/WebWork/index.jsp提交后在tomcat console窗口打印出
hello zjh
after userManager.sayHello()

posted @ 2006-08-03 07:29 蜘蛛 阅读(1381) | 评论 (2)编辑 收藏

把spring集成到web框架很简单,只要在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>
如果为下面这种方式的话,那么就是加载默认的文件
/WEB-INF/applicationContext.xml
这个在
org.springframework.web.context.support.XmlWebApplicationContext类里面定义的,,部分代码:
/** 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获取自己想要的参数的,,

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

通过WebApplicationContext我们就可以通过bean的名字获取它的实例了
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 蜘蛛 阅读(616) | 评论 (0)编辑 收藏

webwork使用 validation验证框架,其采用的是拦截器
看一个例子:
SimpleAction-validation.xml 名字前缀要与类名相同,而且与之在同一目录下
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
<validators>
    <field name="count">
        <field-validator type="required">
            <message>You must enter a value for count.</message>
        </field-validator>
        <field-validator type="int">
            <param name="min">0</param>
            <param name="max">5</param>
            <message>
    count must be between ${min} and ${max}, current value is ${count}.
     </message>
        </field-validator>
    </field>
</validators>
==
package helloWorld;
import com.opensymphony.xwork.ActionSupport;
import com.opensymphony.xwork.ValidationAware;
public class SimpleAction extends ActionSupport implements ValidationAware {
    private int count;
    public void setCount(int count) {
        this.count = count;
    }
    public int getCount() {
        return count;
    }
    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为多个时与servlet里面的filter一样按顺序依次传递,假若失败就为影响后面的程序运行效果.
还有两个jsp页面
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>
运行效果如下
count must be between 0 and 5, current value is 8.

下面为日期类型的验证
<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>

posted @ 2006-08-02 22:10 蜘蛛 阅读(1639) | 评论 (0)编辑 收藏

本地中文化网址

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

在线文档

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

struts 的区别有实现国级化的时候, struts message 只能出现 5 个动态的值

也就像下面的信息

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 是无限制的,像上面的可以写成这样子

<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>
在很多书上都讲上面可行,可是我却报下面的错...换成下面那种方式就ok了

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

一个简单的例子
 
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;
    }
}
实现的action接口里面只有一个方法
 
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的一个加载类
<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:提供对错误信息的支持
action and field specific errors
field errors are automatically supported by views
2:国际化的支持
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同级目录下面,名称也一样)里的greeting=Enter your greeting please相同
上面的set.get其实与struts当中的ActionFrom类似..
<%@ 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="欢迎语句" name="greeting"/>
    <ui:submit value="'Submit'"/>
</table>
</form>
</body>
</html>
这里的greeting要与HelloWorldActio.java里的属性一致
如出现错误会显示在当前页,
Enter your greeting please

如填上内容,就会相应的调用setGreeting()方法的..
<%@ taglib prefix="ww" uri="webwork" %>
<html>
<head>
    <title>First WebWork Example</title>
</head>
<body>
<p><ww:property value="greeting"/></p>
</body>
</html>
把填的内容显示出来
在xwork.xml里的<action>
也相应的变成
<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;
    }

}
需实现ModelDriven这个接口,它也只有一个方法
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>
还有两个页面分别用来添加和显示用的
<%@ 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 蜘蛛 阅读(3265) | 评论 (0)编辑 收藏

//SessionCounter.java\ozdvw
package SessionCount;e?
import javax.servlet.*; L9k0
import javax.servlet.http.*; plT
import java.io.*; w;
import java.util.*; JC;@
©达内科技论坛 -- 达内科技论坛  @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
©达内科技论坛 -- 达内科技论坛  {Ytdk
} ©达内科技论坛 -- 达内科技论坛  ri04&
©达内科技论坛 -- 达内科技论坛  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
} ©达内科技论坛 -- 达内科技论坛  )9lR?P
©达内科技论坛 -- 达内科技论坛  !S
//Clean up resources UxUNe
public void destroy() { :=e2NM
} ©达内科技论坛 -- 达内科技论坛  W'F
©达内科技论坛 -- 达内科技论坛  aHW&x9
public void sessionCreated(HttpSessionEvent httpSessionEvent) { HH
  activeSessions++; DyZpv
} ©达内科技论坛 -- 达内科技论坛  4WJ
©达内科技论坛 -- 达内科技论坛  8)#.
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { \s,_t
  activeSessions--; *z
  System.out.println("test test");$s0T@W
//  System.out.println("---111"); ZF+
} ©达内科技论坛 -- 达内科技论坛  MX
public static int getActiveSessions() { tQ
 return activeSessions; )a4
} ©达内科技论坛 -- 达内科技论坛  y%s
} ©达内科技论坛 -- 达内科技论坛  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
}©达内科技论坛 -- 达内科技论坛  ]M\-
//-->#}q
</script>rs(
<script language="javascript">Ax%Qs3
function removeline(){Q \@
if(event.clientX<0&&event.clientY<0).45
{©达内科技论坛 -- 达内科技论坛  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);[
}©达内科技论坛 -- 达内科技论坛  ad6+
}©达内科技论坛 -- 达内科技论坛  1`maF
</script>0.
©达内科技论坛 -- 达内科技论坛  9
<body onUnload="MM_callJS('removeline()')">I=QwN
在线:<%= SessionCounter.getActiveSessions() %> Abd\
</body>.
</html>YZmy
////////////////////////////////6K6(k
///////////////////////////////HoW?y
remove.jspZ{>=
/////©达内科技论坛 -- 达内科技论坛  ]|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)判断浏览器是关闭还是刷新 ,因为刷新也会调用onunload&&
©达内科技论坛 -- 达内科技论坛  c07F
document.all.WebBrowser.ExecWB(45,1);是无提示的关闭浏览器!Q!*pf
classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 |0gLI
这个是调用不弹出对话框的方法,实际是调用系统的方法如下 ]9M
document.all.WebBrowser.ExecWB(45,1); f:
因为在javascript当中不能调用java方法,所以选择另外写一个jsp文件用于调用,;?(5yi
invalidate()方法,(?A|`K
©达内科技论坛 -- 达内科技论坛  xv
现在这个结果是正确的,因为我把private static int activeSessions = 1; //这里改成了1,本来照理应该设为0的,可以我运行第一次http://localhost:8080/servlet/count.jsp的时候得到的是0,所以我才把它改成1的,dKOp0
那们老师或同学知道的话,麻烦告诉怎么为事,为什么在第一次创建session时不能触发事件sessionCreated()Rw

现在这个结果是正确的,因为我把private static int activeSessions = 1; //这里改成了1,本来照理应该设为0的,可以我运行第一次http://localhost:8080/servlet/count.jsp的时候得到的是0,所以我才把它改成1的, h(
,为什么在第一次创建session时不能触发事件sessionCreated()g?

session是个双向机制,第一次访问的时候,是从客户端发起的,浏览器不知道这个网页是否需要session,所以浏览器不会创建sessionId,当这个请求到达服务器的时候,没有sessionId,d}--5
©达内科技论坛 -- 达内科技论坛  r0_/S
SessionCounter 是被嵌在jsp里的,所以第一次显示的时候,得到jsp页面的session创建是在jsp页面滞后,也就是说SessionCounter是滞后于jsp页面的.xKTZrv
©达内科技论坛 -- 达内科技论坛  V@)
顺便说一句,extends HttpServlet 是多余的。]&

在页面里页设置一个退出按钮.调用quit.jsp=
它的内容是:h>
我们用一个quit.jsp来处理用户退出系统的操作,quit.jsp负责注销session,及时释放资源。>D6T
©达内科技论坛 -- 达内科技论坛  uj&B
  ·注销session。Z5K&
©达内科技论坛 -- 达内科技论坛  ##
  ·关闭浏览器窗口。@Q(
©达内科技论坛 -- 达内科技论坛  TP^wA
  其代码如下所示:"
©达内科技论坛 -- 达内科技论坛  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?
©达内科技论坛 -- 达内科技论坛  3-L-
  其中第3行负责注销session,原先放入session的对象将解绑定,等待垃圾回收以释放资源。对于本例而言,session中有一个名为ses_userBean的userBean对象(它是在switch.jsp中放入session的),调用session.invalidate()后,userBean从session中解绑定,它的valueUnbound()方法会被触发调用,然后再等待垃圾回收。A/cr
©达内科技论坛 -- 达内科技论坛  +Nb
  第5~8行是一段javascript脚本程序,负责关闭窗口,如果网页不是通过脚本程序打开的(window.open()),调用window.close()脚本关闭窗口前,必须先将window.opener对象置为null,如第6行所示,否则浏览器会弹出一个确定关闭的对话框,笔者发现这个问题困扰了不少的Web程序员,故特别指出。s `|*)

posted @ 2006-07-31 19:42 蜘蛛 阅读(6914) | 评论 (8)编辑 收藏

to robbin
ibatis的网站
www.ibatis.com上面可以找到很好的文档,再加上有非常不错的例子,所以使用是相当的简单。
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
环境下的tomcat + apache配置(绝对实践操作版)

ibatis大体上可以分为两个部分:SQL Maps + Data Access Objects
我现在的项目中都用到了,它提供的jpetstore就使用了db layer,可以参考它的实现方式。
不过我觉得jpetstore的db layer实现方式还不是太好,至少它的业务逻辑层和dao层没有明显区分,在实现比较

大的项目的时候造成了程序的混乱,如果没有一个良好的模式来实现db layer 的时候,确实会造成效率的低下,

有了良好的架构,速度确实很快(特别是SQL Maps + Data Access Objects 都使用的情况)
BO层的设计已经不是什么新鲜的了,但我觉得它确实可以很好的和DaoManager结合起来,通过DaoManager->SQL

map->jdbc
它的两个核心的配置文件:dao.xml+SqlMapConfig.xml
通过灵活的配置文件的组合可以实现数据库不同的访问组合
比如:一个dao.xml可以对应多个SqlMapConfig.xml
一个dao.xml可对应一个数据库,多个dao.xml就可以访问多个数据库了(它的petstore就提供了演示distributed

功能的样例是oracle+ms sql)
它的SqlMapConfig.xml中可配置sql-map resource,就是配置你具体的sql语句的xml文件。
它的sqlMap提供很多方法来访问数据库,直接返回你想要的结果

***************************
DAO中的一个供分页查询的方法
***************************
......

SqlMap sqlMap = getSqlMapFromLocalTransaction();//取到当前sqlmap对象
List list=sqlMap.executeQueryForList("你的MappedStatement文件中sql语句的名称", object("你可以通过这

个object传一些查询条件"),skipResults,maxResults);

...

有了良好的设计模式,它可以和struts完美结合在一起,无论是效率还是清晰型上,都非常令人满意的

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)允许你去创建简单的组件,为你访问你的数据,而不用去实现具体的实现细节。使用

DAOS你能动态配置不同的持久层机制。
注意:DAO框架与sqlmaps框架是完全的分离开和互不依赖性,所以你可以单独使用,或一起来用都没有关系.

下面是一些重要的daos api
DaoManager(Facade模式):负责配置DAO框架实例(经过dao.xml),在其它api当中充当facade.
DaoTransaction(Marker Interface):通用的接口,为了去使用事物(连接),通用的实现将包装jdbc的连接对象

.
DaoException(RuntimeException运行期异常):所有的方法和类全部抛出dao api专有的异常。
Dao(Marker Interface):一个标记接口供所有的dao去实现,这个接口必须为所有的dao类去实现。这个接口没有

声名任何方法被实现,只是充当一个标记(例如:一些DaoFactory去辩别不同的类);
-----------------------------------
jdbc事务控制实现
sqlmap:通过sqlmaps框架和它的事物管理服务去实现,包括不同的DataSource和事物管理配置
hibernate:提供简单容易的和hibernate,它的事物工具(SessionFactory,Session,Transaction)整合
jdbc:通过jdbc api,使用它的基本的dataSource和Connction接口去管理事物
jta:管理分部式事物,需要被管理的datasource,这样子可以通过jndi访问.
external:允许事物被外部控制

dao.xml为配置文件(http://www.ibatis.com/dtd/dao-2.dtd)
DaoManager负责配置dao框架。DaoManager类可以为框架解析特定的xml文件,而提供出有用的信息供框架使用。

那么配置文件(xml文件)需要指定下面的内容:
1)dao的上下文
2)事物为每一个上下文件的实现
3)TransactionManager配置属性
4)Dao为每一个实现的dao接口
一个Dao上下文是一组相关的配置信息和Dao实现。通常一个上下文关联到一个数据源(datasource)或一个文件。
dao配置文件(通常被叫做dao.xml,但不是必须的),为下面的结构
<!DOCTYPE daoConfig
PUBLIC "-//iBATIS.com//DTD DAO Configuration 2.0//EN"
"http://www.ibatis.com/dtd/dao-2.dtd">
<
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>
一个dao.xml里可以有多个context,通常一个上下文指定一个特定的dataSource
为了去管理多样的配置(因为有不同的环境),你可以使用可选的元素<properties).
这个允许使用占用符,例如:
driver=org.postgresql.Driver
url=jdbc:postgresql://localhost:5432/test
这时你可以在dao.xml里用占用符取代具体的值,例如上面的可以改写成下面的
<property name="JDBC.Driver" value="${driver}"/>
<property name="JDBC.ConnectionURL" value="${url}"/>
在上下文当中,第一个context里同使用的是jdbc事物控制,所以在指定的property元素也要使用jdbc,不同的事

物管理实现会需要不同的properties,

事物管理实现(Transaction Manager Implementation and Configuration)是一个组件会管理pool(事物对象)

,一事物管理通常只是包装特定的DataSource,简单的事物通常包装一特定的实现类如jdbc连接实现

jdbc Transaction Manager:利用提供的datasource api提供连接池服务
有三种datasource是支持的(simple,dbcp,jndi),simple是实现了ibatis的SimpleDataSource。dbcp使用了

jakarta dbcp datasource,最后,jndi是实现了查找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.实种实现总是需要通过jndi去获得datasource和一个UserTransaction实例也

是通过jndi访问的,因些需要在服务器配置一下,不过这使得配置dao框架十分简单了。下面是一个简单的配置
<transactionManager type="JTA">
<property name="DBJndiContext" value="java:comp/env/jdbc/MyDataSource"/>
<property name="UserTransaction" value="java:comp/env/UserTransaction"/>
</transactionManager>

sqlmap管理事物:通过dao框架包装sql maps事物服务,所有的你都要指定一个sql maps配置文件。下面是一个简

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

hibernate管理事物:同样的,通过dao框架包装hibernate事物服务,基本上properties在配置文件当中和

hibernate.properties文件是一样的,另外,持久化类(你可能通过添加到hibernate配置文件当中去的)要

以"class."开头,下面是一个例子:
<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框架控制。这个执行基本是没有行为,因些不需要properties,如果你使用一个

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

dao实现模板:你可能要问我怎么使用上面的事物,好了每一种事物类型都要相应的dao模板与之对应。例如:

jta,jdbc模板提供简单的访问jdbc连接对象。相似的sqlmap模板提供访问简单的SqlMapExecutor实例,而

hibernate template提供访问Session object.
使用dao template完全是可选的,但99%的时间里,是不可不选择的/

更多的模板请看下面的.
DaoManager编程:iBATIS dao框架有许多的目的.第一个,它试图持久层的细节.这包括所有的接口,实现和异

常细节(在你的持久层解决方案当中).
例如:如果你使用jdbc,dao框架将为你隐藏类如DataSource,Connection和SQLException.类似的,如果你使用

Hibernate orm,dao框架会为你隐藏类如Configuration,SessionFactory,Session和HibernateException.所有的

这些细节都会隐藏到了dao接口层.甚至在显示层的许多的datasource也会被隐藏.
第二个目的是:简化持久层编程模型,使在同一时间保持一致.不同的持久层解决方案有不同的编程语义和行为.
dao框架试图隐藏更多,允许在你的应用service和domain层,写出一致的风格.

DaoManager类负责dao框架的配置文件(通过dao.xml),另外,DaoManage扮演着中心门面的角色,它特殊之处是,还提

供方法允许你访问事物和dao实例.

读取配置文件:
使用DaoManagerBuilder类的静态方法buildDaoManager()方法读取dao.xml文件,buildDaoManager()方法需要一个

Reader实例作为参数.
例如:
Reader reader = new FileReader(C:/myapp/dao.xml);
DaoManager daoManager = DaoManagerBuilder.buildDaoManager(reader);

如在web应用环境当中(或其它),一般配置文件都会从classpath当中去加载的.我们可以使用

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

Context和DaoManager
DaoManager实例是从dao.xml文件建立的.当你需要一个dao实例时,你可以通过DaoManager,和事物控制也会从它此

处提供的.因些不需直接访问context和事物管理..
你的dao知道它怎么去做.类似的,需要看你的daos怎么工作的,事物会恰当的开始和提交的.而且,事物仅在你的dao

被调用时才启动.

获取dao实例
一旦你得到了DaoManager实例,你就可以根据dao名字,利用DaoManager的getDao方法获取该dao实例了,如:
ProductDao productDao = (ProductDao) daoManager.getDao (ProductDao.class);

DaoManager提供了处理事务的方法.这些方法允许你划分事务,和避免传递事务对象(eg:jdbc Connction)到你的所

有的daos当中去.例如:
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();
}
调用startTransaction()只是让DaoManager知道,你将要启动编程控制事务.
dao实例化时才启动事务的,甚至事务仅仅是contexts需要的时候.
commitTransaction()提交事务,endTransaction()需要在try{}catch(){}里面的,,
如果发现了异常,那么就会回滚.

自动提交事务
像jdbc的setAutoCommit(true)一样,不过也有不同之处,你可以使用多个update作为一个事务,你不需要指定提交

的行为方式,只要你不调用startTransaction()就行了
Product product = productDao.getProduct (5); // Transaction 1
product.setDescription (“New description.”);
productDao.updateProduct(product); // Transaction 2
product = productDao.getProduct (5); // Transaction 3
注意了,这里没有异常的事件发生的,如发生异常,就会回滚,和释放连接资源的.

实现自己的dao接口:
dao接口非常的简单,因为它没有声名任何的方法,只是一个marker interface,所以实现的只是你自己的接口罢了,

在你的接口当中没有限制你要定的任何方法,抛出的异常是运行期的DaoException类型的异常.
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
在上面也提到了,每一种模板都对应一种特殊的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
}
注意:在上面的例子里只有一些个构造器,参数为DaoManager,它是在初始化实例时通过DaoManagerBuilder自动注

入参数进去..第一个需要DaoManager作为构造器的参数,也就迫使它的子类都要一个带参(DaoManager)的构造器,

当你使用模板时,构造器是必须的,你不需要提供其它的构造器了..你的daos仅仅需要DaoManagerBuilder去实例化

它.

考虑dao的设计方式:
推荐使用一个继承dao接口的接口,另一个为一个继承dao接口的抽象类(封闭一些异常,事务等等)..
实际上你只需要一个就行了,另外你也可以选择下面这种方式..
你可以使用BaseJdbcDao(abstract)继承dao接口,需让ProductDao不要去断承dao接口,让ProductJdbcDao去实现

ProductDao和继承BaseJdbcDao就可以了,让Product接口仍然与dao分离开来....
在上面的例子当中可以将BaseJdbcDao继承JdbcDaoTemplate(它已经实现了dao接口)


现在做一个例子:
create table test
(
id int auto_increment;
name varchar(20)
);

建一个对应的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;
}
}

建一个配置数据库的配置文件
config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
    PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
    "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<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"
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<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("插入时出异常");
   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());
 }

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

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

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

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

-------
写一个运行dao的
<!DOCTYPE daoConfig
PUBLIC "-//iBATIS.com//DTD DAO Configuration 2.0//EN"
"http://www.ibatis.com/dtd/dao-2.dtd">
<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"
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<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要放在项目的bin目录下面,否则就会出错
还有在dao.xml里的  <transactionManager type="SQLMAP">
     <property name="SqlMapConfigResource" value="zhai/config.xml"/>
    </transactionManager>
也是一个道理呀

posted @ 2006-07-24 00:48 蜘蛛 阅读(4085) | 评论 (4)编辑 收藏

对于面向接口编程的项目免不了要一反射相接触,动态得到实例:
public interface a {
 public void sayHello();
}
---------------------------
第一种情况是当
aImpl实现类为默认的构造方法:
根据类名aImpl动态得到实例
Class c=Class.forName("aImpl");
a instance=(a)c.newInstance();
a.sayHello();
------------
第二种情况当
aImpl为带参数的构造方法时:
Class o=Class.forName("aImpl");//aImpl为要实例化的例名,可以从配置文件当中获取
   Constructor cous = null;
   cous=o.getConstructor(new Class[]{String.class});//构造器的参数类型
   a ao=(a) cous.newInstance(new Object[]{"xxx"});//"xxx为传入的参数值
   ao.sayHello();
第三种就是构造器为私有的时候,我们通过方法获取实例getInstance()(自己定的)
Class o=Class.forName("aImpl");
   Method method=o.getMethod("getInstance",new Class[]{String.class});
//getInstance为返回为aImpl实例的方法名
    a ao=(a) method.invoke(null,new Object[]{"xxx"});//注意了前面的参数为null,是有
//条件的,就是要求getInstance为static类型的,我想大家都会这样设计的
       ao.sayHello();
做连接池的话,一种方式就是使用动态代理类,当Connection调用close()方法时,我们可以利用方法拦截器,在调用close方法的时候把连接放到缓存里面去,供以后再次利用..
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 蜘蛛 阅读(3339) | 评论 (1)编辑 收藏

因为项目当中用到分页,界面用了jstl,本想用jstl给我分页的,测试代码如下

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ 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}">上一页</A>
  <A href="http://localhost:8080/jstl/test.jsp?cpage=${cpage}">当前页</A>
  <A href="http://localhost:8080/jstl/test.jsp?cpage=${cpage+1}">下一页</A>
 <hr>
</body>
</html>
本以为这样子比起用oracle里的rownum(如果更换数据库还得改代码),来的要好,因为我这里的是
 <sql:query var="rs" startRow="${ipage*(cpage-1)}" maxRows="${ipage}">
 select * from test
 </sql:query>
可是我看了他的源代码,竟然它利用缓存,每次调用
<sql:query startRow="" maxRows="">它都会把select * from test的数据全部一次性查出得到一个result,再根据startRow,再调用result.next(),startRow次后才正式帮我们工作..

看来还是原始的方式速度要快一些..
.......进化出来的产物不一定先进
posted @ 2006-07-15 10:50 蜘蛛 阅读(3115) | 评论 (5)编辑 收藏

仅列出标题
共9页: 上一页 1 2 3 4 5 6 7 8 9 下一页