2005年08月30日

AJAX made simple with DWR

Start using AJAX in your Web application with DWR

AJAX, or Asynchronous JavaScript and XML, describes a Web development technique for creating interactive Web applications using a combination of HTML (or XHTML) and Cascading Style Sheets for presenting information; Document Object Model (DOM); JavaScript, to dynamically display and interact with the information presented; and the XMLHttpRequest object to interchange and manipulate data asynchronously with the Web server.

Many examples on the Internet show all the necessary steps for using XMLHttpRequest to communicate with the server from within an HTML file. When manually writing and maintaining the XMLHttpRequest code, a developer must deal with many potential problems, especially with cross-browser compatibilities like different DOM implementations. This can lead to countless hours spent coding and debugging JavaScript code, which is not known to be developer friendly.

The DWR (Direct Web Remoting) project is an open source solution under the Apache license for the developer who wants to use AJAX and XMLHttpRequest in an easy way. It has a set of JavaScript functions that remove the complexity from calling methods in a java object running on the application server from the HTML page. It handles parameters of different types and helps keep the HTML code readable.

DWR is not intrusive to one’s design, as it does not force any sort of inheritance architecture for objects to be exposed. It fits well in any application that runs in a servlet framework. For the less DHTML-experienced developers, DWR also provides a JavaScript library to help with frequently used DHTML tasks, like populating tables, filling select boxes with items, and changing the content of HTML elements such as <div> and <span>.

The DWR Website is comprehensive and has a fair amount of documentation, which has served as a foundation for this article. Some examples are provided to demonstrate how DWR can be used and what can be accomplished with the library.

This article allows the user to see a step-by-step creation of a Web application that uses DWR. I show you all the details necessary to create the sample application, which you’ll be able to download and deploy in your environment to evaluate how DWR works.

Note: Finding information about AJAX is not difficult; several articles and blog entries on the Web cover the subject, each of which tries to identify and comment about a different aspect of the concept. In Resources, you will find some interesting links to examples and articles to learn more about AJAX.

Sample application
The example application used in this article simulates an apartment rental search engine for the city of Toronto. The user can select a set of search criteria before performing the search. To improve interaction, AJAX is used in two occasions:

  • The application notifies the user of the number of search results that match his selection. This number is updated—using AJAX—as the user selects the amount of desired bedrooms and bathrooms, and the price range. By showing the user the number of results, the user won’t need to hit the search button when no results or too many results match the user’s criteria.
  • The database query that retrieves the units from the database is performed using AJAX. The database search executes when the user presses the Show Results button. Thus, the application seems more responsive, as the whole page doesn’t need to be reloaded to show the results.

Database
The database we use is HSQL, a java SQL database engine with a small footprint, which can be bundled with the Web application with no additional installation and configuration. A SQL file is used to create the in-memory table and add some records when the Web application context is started.

java classes
The application contains two main classes called Apartment and ApartmentDAO. The Apartment.java class is a simple java class with attributes and getter/setter methods. ApartmentDAO.java is the data-access class used to query the database and get information based on the user’s search criteria. The implementation of the ApartmentDAO class is straightforward; it uses straight java Database Connectivity calls to get the total number of units and the list of available units matching the user’s request.

DWR configuration and use
Setting up DWR for use is easy: Copy the DWR jar file to the Web application’s WEB-INF/lib directory, add a servlet declaration to web.xml, and create the DWR configuration file. The DWR distribution only requires the use of a single jar file. You must add the DWR servlet into the application’s deployment descriptor in WEB-INF/web.xml:

    <servlet>
        <servlet-name>dwr-invoker</servlet-name>
        <display-name>DWR Servlet</display-name>
        <description>Direct Web Remoter Servlet</description>
        <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dwr-invoker</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>dwr-invoker</servlet-name>
        <display-name>DWR Servlet</display-name>
        <description>Direct Web Remoter Servlet</description>
        <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dwr-invoker</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>

One optional step is to set up DWR in debug mode—illustrated in the example above—by setting the debug parameter to true in the servlet declaration. With the DWR servlet in debug mode, you can see all the java objects accessible from HTML pages. A page with a list of available objects appears at the WEBAPP/dwr URL, which shows the public methods for the selected class; the listed methods can be called from that page, allowing you to, for the first time, run methods on objects located on the server. The figure below shows what the debug page looks like:



Debug page

Debug page

Now you must let DWR know what objects will receive requests through the XMLHttpRequest object. Accomplish that task by using DWR’s own configuration file called DWR.xml. In the configuration file, you define the objects that DWR will allow you to call from your HTML pages. By design, DWR allows access to all the exposed class’s public methods, but in our example, we only allow access to a few methods. Here’s the configuration file for our example:

<dwr>
    <allow>
        <convert converter="bean" match="dwr.sample.Apartment"/>
        <create creator="new" javascript="ApartmentDAO" class="dwr.sample.ApartmentDAO">
            <include method="findApartments"/>
            <include method="countApartments"/>
        </create>
    </allow>
</dwr>

<dwr>
    <allow>
        <convert converter="bean" match="dwr.sample.Apartment"/>
        <create creator="new" javascript="ApartmentDAO" class="dwr.sample.ApartmentDAO">
            <include method="findApartments"/>
            <include method="countApartments"/>
        </create>
    </allow>
</dwr>

The above file accomplishes two goals in our example. First, the <convert> tag tells DWR to convert objects of the DWR.sample.Apartment type into JavaScript associative arrays, because, for security reasons, DWR doesn’t convert regular beans by default. Second, the <create> tag makes DWR expose the DWR.sample.ApartmentDAO class to be called from JavaScript; the JavaScript file we use in our pages is defined by the javascript attribute. We must pay attention to the <include> tags, as those identify which methods from the DWR.sample.ApartmentDAO class will be made available.

HTML/JSP code
Once the configuration is done, you can start your Web application, and DWR will be ready to call the methods you need from your HTML/JavaServer Pages (JSP) page, without you creating JavaScript files. In the search.jsp file, we must add references to the JavaScript interface provided by DWR, as well as the DWR engine, by adding three lines to our code:

  <script src='dwr/interface/ApartmentDAO.js'></script>
  <script src='dwr/engine.js'></script>
  <script src='dwr/util.js'></script>

  <script src='dwr/interface/ApartmentDAO.js'></script>
  <script src='dwr/engine.js'></script>
  <script src='dwr/util.js'></script>

The first use of AJAX in the example application can be noticed when the user changes the search criteria; as he can see, as the criteria changes, the number of available apartments is updated. I created two JavaScript functions: The updateTotal() function is called when a value in one of the select boxes changes. The ApartmentDAO.countApartments() function is the most important piece. Most interesting is the first parameter, the loadTotal() function, which identifies the callback method that DWR will use when it receives a response from the server. loadTotal() is then called to display the result on the HTML page’s <div>. Here’s how the JavaScript functions are used in the described interaction scenario:

function updateTotal() {
    $("resultTable").style.display = 'none';
    var bedrooms = document.getElementById("bedrooms").value;
    var bathrooms = document.getElementById("bathrooms").value;
    var price = document.getElementById("price").value;
    ApartmentDAO.countApartments(loadTotal, bedrooms, bathrooms, price);
}

function loadTotal(data) {
    document.getElementById("totalRecords").innerHTML = data;
}

function updateTotal() {
    $("resultTable").style.display = 'none';
    var bedrooms = document.getElementById("bedrooms").value;
    var bathrooms = document.getElementById("bathrooms").value;
    var price = document.getElementById("price").value;
    ApartmentDAO.countApartments(loadTotal, bedrooms, bathrooms, price);
}

function loadTotal(data) {
    document.getElementById("totalRecords").innerHTML = data;
}

Obviously, the user will want to see the list of apartments that satisfy his search. So, when the user is satisfied with the criteria and total apartments available, he presses the Show Results button, which calls the updateResults() JavaScript method:

function updateResults() {
    
    DWRUtil.removeAllRows("apartmentsbody");
    var bedrooms = document.getElementById("bedrooms").value;
    var bathrooms = document.getElementById("bathrooms").value;
    var price = document.getElementById("price").value;
    ApartmentDAO.findApartments(fillTable, bedrooms, bathrooms, price);
    $("resultTable").style.display = '';
}

function fillTable(apartment) {
    DWRUtil.addRows("apartmentsbody", apartment, [ getId, getAddress, getBedrooms, getBathrooms, getPrice ]);
}

function updateResults() {
    
    DWRUtil.removeAllRows("apartmentsbody");
    var bedrooms = document.getElementById("bedrooms").value;
    var bathrooms = document.getElementById("bathrooms").value;
    var price = document.getElementById("price").value;
    ApartmentDAO.findApartments(fillTable, bedrooms, bathrooms, price);
    $("resultTable").style.display = '';
}

function fillTable(apartment) {
    DWRUtil.addRows("apartmentsbody", apartment, [ getId, getAddress, getBedrooms, getBathrooms, getPrice ]);
}

The updateResults() method clears the table area assigned to hold the search results, gets all the necessary parameters from the UI, and passes those parameters to the ApartmentDAO JavaScript object created by DWR. The database query is then performed, and the callback function fillTable() is called, which then parses the object returned by DWR, and prints them to the page.

Security concern
To keep the example brief, the ApartmentDAO class was kept as simple as possible, but such a class will usually have a set of methods to manipulate data, such as insert(), update(), and delete(). DWR exposes all public methods to any calling HTML page. For security reasons, it’s not wise to expose your data-access layer methods in such a way. A developer could create a facade to centralize the communication between the calling JavaScript function and lower-level business components, thus limiting the exposed functionality.

Conclusion
This article’s example only gets you started using AJAX with DWR in your own projects. DWR helps you keep focused on how to improve your application’s interaction model, removing the burden that comes with coding and debugging JavaScript code. The most interesting challenge of using AJAX is defining where and how to improve usability. DWR helps you focus totally on how to make your application more user-friendly by handling the communication between the Webpage and your java objects.

I would like to thank Mircea Oancea and Marcos Pereira for reviewing this article and giving valuable feedback.


About the author
Cloves Carneiro Jr. is software engineer working for Extend Media, Toronto, Canada. He is a Sun Certified Programmer and Sun Certified Web Component Developer. He has worked with java since 1999 and specializes in server-side java applications.

2005年08月25日
 

Smack is an Open Source XMPP (Jabber) client library for instant messaging and presence.

Key Advantages:

  • Extremely simple to use, yet powerful API. Sending a text message to a user can be accomplished in three lines of code:
    XMPPConnection con
        = new XMPPConnection("jabber.org");
    con.login("mtucker", "password");
    con.createChat("jsmith@jivesoftware.com")
        .sendMessage("Howdy!");
    
  • Doesn’t force you to code at the packet level, as other libraries do. Smack provides intelligent higher level constructs such as the Chat and GroupChat classes, which let you program more efficiently.
  • Does not require that you’re familiar with the XMPP XML format, or even that you’re familiar with XML.
  • Open Source under the Apache License, which means you can incorporate Smack into your commercial or non-commercial applications.

Jabber Software Foundation Logo

Jabber :: About :: Overview

Jabber

1. Rapid and indistinct speech
2. To talk in a noisy, excited, or declamatory manner
3. A streaming XML technology mainly used for instant messaging

Jabber is best known as "the Linux of instant messaging" — an open, secure, ad-free alternative to consumer IM services like AIM, ICQ, MSN, and Yahoo (see the IM quickstart). Under the hood, Jabber is a set of streaming XML protocols and technologies that enable any two entities on the Internet to exchange messages, presence, and other structured information in close to real time. Jabber technologies offer several key advantages:

  • Open — the Jabber protocols are free, open, public, and easily understandable; in addition, multiple implementations exist for clients, servers, components, and code libraries.

  • Standard — the Internet Engineering Task Force (IETF) has formalized the core XML streaming protocols as an approved instant messaging and presence technology under the name of XMPP, and the XMPP specifications have been published as RFC 3920 and RFC 3921.

  • Proven — the first Jabber technologies were developed by Jeremie Miller in 1998 and are now quite stable; hundreds of developers are working on Jabber technologies, there are tens of thousands of Jabber servers running on the Internet today, and millions of people use Jabber for IM.

  • Decentralized — the architecture of the Jabber network is similar to email; as a result, anyone can run their own Jabber server, enabling individuals and organizations to take control of their IM experience.

  • Secure — any Jabber server may be isolated from the public Jabber network (e.g., on a company intranet), and robust security using SASL and TLS has been built into the core XMPP specifications.

  • Extensible — using the power of XML namespaces, anyone can build custom functionality on top of the core protocols; to maintain interoperability, common extensions are managed by the Jabber Software Foundation.

  • Flexible — Jabber applications beyond IM include network management, content syndication, collaboration tools, file sharing, gaming, and remote systems monitoring.

  • Diverse — a wide range of companies and open-source projects use the Jabber protocols to build and deploy real-time applications and services; you will never get "locked in" when you use Jabber technologies.

To learn more or get started, you can:

Last Updated: 2005-01-26

java/J2EE中文问题终极解决之道

板桥里人 http://www.jdon.com 2005/06/29

  Java中文问题一直困扰着很多初学者,如果了解了Java系统的中文问题原理,我们就可以对中文问题能够采取根本的解决之道。

  最古老的解决方案是使用String的字节码转换,这种方案问题是不方便,我们需要破坏对象封装性,进行字节码转换。

  还有一种方式是对J2EE容器进行编码设置,如果J2EE应用系统脱离该容器,则会发生乱码,而且指定容器配置不符合J2EE应用和容器分离的原则。

  在Java内部运算中,涉及到的所有字符串都会被转化为UTF-8编码来进行运算。那么,在被Java转化之前,字符串是什么样的字符集? Java总是根据操作系统的默认编码字符集来决定字符串的初始编码,而且Java系统的输入和输出的都是采取操作系统的默认编码。

  因此,如果能统一Java系统的输入、输出和操作系统3者的编码字符集合,将能够使Java系统正确处理和显示汉字。这是处理Java系统汉字的一个原则,但是在实际项目中,能够正确抓住和控制住Java系统的输入和输出部分是比较难的。J2EE中,由于涉及到外部浏览器和数据库等,所以中文问题乱码显得非常突出。

  J2EE应用程序是运行在J2EE容器中。在这个系统中,输入途径有很多种:一种是通过页面表单打包成请求(request)发往服务器的;第二种是通过数据库读入;还有第3种输入比较复杂,JSP在第一次运行时总是被编译成Servlet,JSP中常常包含中文字符,那么编译使用javac时,Java将根据默认的操作系统编码作为初始编码。除非特别指定,如在Jbuilder/eclipse中可以指定默认的字符集。

  输出途径也有几种:第一种是JSP页面的输出。由于JSP页面已经被编译成Servlet,那么在输出时,也将根据操作系统的默认编码来选择输出编码,除非指定输出编码方式;还有输出途径是数据库,将字符串输出到数据库。

  由此看来,一个J2EE系统的输入输出是非常复杂,而且是动态变化的,而Java是跨平台运行的,在实际编译和运行中,都可能涉及到不同的操作系统,如果任由Java自由根据操作系统来决定输入输出的编码字符集,这将不可控制地出现乱码。

  正是由于Java的跨平台特性,使得字符集问题必须由具体系统来统一解决,所以在一个Java应用系统中,解决中文乱码的根本办法是明确指定整个应用系统统一字符集。

  指定统一字符集时,到底是指定ISO8859_1 、GBK还是UTF-8呢?

  (1)如统一指定为ISO8859_1,因为目前大多数软件都是西方人编制的,他们默认的字符集就是ISO8859_1,包括操作系统Linux和数据库MySQL等。这样,如果指定Jive统一编码为ISO8859_1,那么就有下面3个环节必须把握:

  开发和编译代码时指定字符集为ISO8859_1。

  运行操作系统的默认编码必须是ISO8859_1,如Linux。

  在JSP头部声明:<%@ page contentType="text/html;charset=ISO8859_1" %>。

  (2)如果统一指定为GBK中文字符集,上述3个环节同样需要做到,不同的是只能运行在默认编码为GBK的操作系统,如中文Windows。

  统一编码为ISO8859_1和GBK虽然带来编制代码的方便,但是各自只能在相应的操作系统上运行。但是也破坏了Java跨平台运行的优越性,只在一定范围内行得通。例如,为了使得GBK编码在linux上运行,设置Linux编码为GBK。

  那么有没有一种除了应用系统以外不需要进行任何附加设置的中文编码根本解决方案呢?

  将Java/J2EE系统的统一编码定义为UTF-8。UTF-8编码是一种兼容所有语言的编码方式,惟一比较麻烦的就是要找到应用系统的所有出入口,然后使用UTF-8去“结扎”它。

  一个J2EE应用系统需要做下列几步工作:

  1. 开发和编译代码时指定字符集为UTF-8。JBuilder和Eclipse都可以在项目属性中设置。
  2. 使用过滤器,如果所有请求都经过一个Servlet控制分配器,那么使用Servlet的filter执行语句,将所有来自浏览器的请求(request)转换为UTF-8,因为浏览器发过来的请求包根据浏览器所在的操作系统编码,可能是各种形式编码。关键一句:
    request.setCharacterEncoding("UTF-8")。
    网上有此filter的源码,Jdon框架源码中com.jdon.util.SetCharacterEncodingFilter
    需要配置web.xml 激活该Filter。
  3. 在JSP头部声明:<%@ page contentType="text/html;charset= UTF-8" %>。
  4. 在Jsp的html代码中,声明UTF-8:
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. 设定数据库连接方式是UTF-8。例如连接MYSQL时配置URL如下:
    jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8
    一般数据库都可以通过管理设置设定UTF-8
  6. 其他和外界交互时能够设定编码时就设定UTF-8,例如读取文件,操作XML等。

     笔者以前在Jsp/Servlet时就采取这个原则,后来使用Struts、Tapestry、EJB、Hibernate、Jdon等框架时,从未被乱码困扰过,可以说适合各种架构。希望本方案供更多初学者分享,减少Java/J2EE的第一个拦路虎,也避免因为采取一些临时解决方案,导致中文问题一直出现在新的技术架构中。

  相关J2EE中文问题解决的源码系统可参考:按这里

  欢迎进入讨论 也欢迎提出例外案例

原文地址:http://www.jdon.com/idea/chinesejava.htm

2005年08月22日

原文:http://www.cnblogs.com/hw/articles/68242.html 

下载Middlegen-Hibernatehttp://prdownloads.sourceforge.net/hibernate/

下载ant  http://archive.apache.org/dist/ant/

分别解压

 

设置环境变量中的path ant解压后目录的bin目录添加进去(别忘了和前一个项用;分隔)

 

jtds驱动复制到Middlegen-Hibernate的解压后的目录的lib目录中

 

Middlegen-Hibernate的目录的config\database中打开mssql.xml

改成

   <property name="database.driver.file"           value="${lib.dir}/jtds-0.8.1.jar"/>

   
<property name="database.driver"                value="net.sourceforge.jtds.jdbc.Driver"/>

   
<property name="database.url"                   value="jdbc:jtds:sqlserver://192.168.3.3/pubs"/>

   
<property name="database.userid"                value="sa"/>

   
<property name="database.password"              value="capinfo"/>

   
<property name="database.schema"                value="dbo"/>

   
<property name="database.catalog"               value="pubs"/>

  

 

后两个分别是登陆身份和数据库,必须填写,并且database.url后边也要有数据库名称

 

Middlegen-Hibernate的根目录下,修改build.xml

 

<!DOCTYPE project [

<!ENTITY database SYSTEM

"file:./config/database/hsqldb.xml">

]>

改成file:./config/database/mssql.xml

是配制数据库的,用的什么数据库改成什么文件

 

 

<property name="name" value="airline"/>

工程名称,现在还没体现到有用:)也先改了吧

<property name="name" value="HibernateSample"/>

 

 

<property name="build.gen-src.dir"

value="${build.dir}/gen-src"/>

输出路径,改成

<property name="build.gen-src.dir"              value="C:\temp"/>

 

 

<hibernate

destination="${build.gen-src.dir}"

package="${name}.hibernate"

genXDocletTags="false"

genIntergratedCompositeKeys="false"

javaTypeMapper=

"middlegen.plugins.hibernate.HibernateJavaTypeMapper"

/>

生成的包(package)是什么,改成

<hibernate

            destination="${build.gen-src.dir}"

            package="xxxx.xxxx.xxxx"

            genXDocletTags="true"

            genIntergratedCompositeKeys="false"

            javaTypeMapper="middlegen.plugins.hibernate.HibernateJavaTypeMapper"

         />

别人对genXDocletTags是这么写的:这里还有一个属性genXDocletTags,如果设置为true,则生成的代码将包含xdoclet tag,这为以后在开发过程中借助xdoclet进行映射调整提供了帮助

 

配制完成,在cmd下,进入Middlegen-Hibernate根目录  输入ant,等着界面出来吧

 

界面出来能看见所选的数据库中的所有表,表的主键,表关系,点表,主键,字段,在下边会有不同的反应



 

1 Domain Class Name

对应POJO 的类名

2 Key Generator

主键产生器

一般而言,利用uuid.hex方式生成主键将提供最好的性能和数据库平台适

应性。

5 Persister

自定义持久类实现类类名

7 Dynamic Update

如果选定,则生成Update SQL 时不包含未发生变动的字段属性,这样可

以在一定程度上提升SQL执行效能。

9.10分别是LifecyleValidatable接口

别的目前认为没什么用~~~

 

点击字段,还可以编辑字段

1 Hibernate mapping specialty

映射类型:

Key :主键

Property :属性

2 java property name

字段对应的java 属性名

3 java Type

字段对应的java 数据类型

4 Column updateable

生成Update SQL时是否包含本字段。

5 Column insertable

生成Insert SQL时是否包含本字段。

都弄好了之后点左上角的Generate 按钮,将生成所选择数据库中所有表的映射文件,是所有表!!!

2005年08月21日
  1. 论文投稿,10-15家杂志社。8.21-8.22 
  2. 毕业设计小结,准备ppt,23日晚发言。8:21-8:23
  3. 搭建编码平台,struts+hibernate+jboss。8:21-8:28
  4. HMX系统升级8.21-8.31
  5. 研究生信息管理系统二期8.21-9.5

关于毕业设计小结,时间是20分钟,第一部分是技术介绍,介绍PDM系统设计需要的技术和思想,第二部分是具体的系统业务逻辑设计,时间各为15分钟。严格控制时间。