06.Ajax2008. 7. 8. 17:58
반응형

These examples demonstrate JavaScript used together with XML (AJAX).


Examples Using the XMLHttpRequest Object

Load a textfile into an HTML element with XML HTTP
How to use an XMLHttpRequest to retrieve new content in an HTML element.

Load an XML file with XML HTTP
How to send an XMLHttpRequest to retrieve data when the user clicks a button.

Make a HEAD request with XML HTTP
How to send an XMLHttpRequest to retrieve HTML header data.

Make a specified HEAD request with XML HTTP
How to send an XMLHttpRequest to retrieve a specific part of the HTML header data.

Display an XML file as an HTML table
How to display an XML file as an HTML table

Examples Explained


Using XMLHttp when user types in an input field:

Online communication with server while typing input using XML HTTP

Example Explained

Posted by 1010
06.Ajax2008. 7. 8. 17:57
반응형

While responseText returns the HTTP response as a string, responseXML returns the response as XML.

The ResponseXML property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.


AJAX ResponseXML Example

In the following AJAX example we will demonstrate how a web page can fetch information from a database using AJAX technology. The selected data from the database will this time be converted to an XML document, and then we will use the DOM to extract the values to be displayed.


Select a Name in the Box Below

Select a Customer:





AJAX Example Explained

The example above contains an HTML form, several <span> elements to hold the returned data, and a link to a JavaScript:

<html>
<head>
<script src="selectcustomer_xml.js"></script>
</head>
<body>
<form action=""> 
Select a Customer:
<select name="customers" onchange="showCustomer(this.value)">
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<b><span id="companyname"></span></b><br />
<span id="contactname"></span><br />
<span id="address"></span>
<span id="city"></span><br/>
<span id="country"></span>
</body>
</html>

The example above contains an HTML form with a drop down box called "customers".

When the user selects a customer in the dropdown box, a function called "showCustomer()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCustomer() is called.

The JavaScript code is listed below.


The AJAX JavaScript

This is the JavaScript code stored in the file "selectcustomer_xml.js":

var xmlHttp
function showCustomer(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }
var url="getcustomer_xml.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged() 
{ 
if (xmlHttp.readyState==4)
{
var xmlDoc=xmlHttp.responseXML.documentElement;
document.getElementById("companyname").innerHTML=
xmlDoc.getElementsByTagName("compname")[0].childNodes[0].nodeValue;
document.getElementById("contactname").innerHTML=
xmlDoc.getElementsByTagName("contname")[0].childNodes[0].nodeValue;
document.getElementById("address").innerHTML=
xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue;
document.getElementById("city").innerHTML=
xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;
document.getElementById("country").innerHTML=
xmlDoc.getElementsByTagName("country")[0].childNodes[0].nodeValue;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

The showCustomer() and GetXmlHttpObject() functions above are the same as in previous chapters. The stateChanged() function is also used earlier in this tutorial, however; this time we return the result as an XML document (with responseXML) and uses the DOM to extract the values we want to be displayed.


The AJAX Server Page

The server page called by the JavaScript, is a simple ASP file called "getcustomer_xml.asp".

The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language. Look at a corresponding example in PHP.

The code runs an SQL query against a database and returns the result as an XML document:

<%
response.expires=-1
response.contenttype="text/xml"
sql="SELECT * FROM CUSTOMERS "
sql=sql & " WHERE CUSTOMERID='" & request.querystring("q") & "'"

on error resume next
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql, conn
if err <> 0 then
response.write(err.description)
set rs=nothing
set conn=nothing
else
response.write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.write("<company>")
response.write("<compname>" &rs.fields("companyname")& "</compname>")
response.write("<contname>" &rs.fields("contactname")& "</contname>")
response.write("<address>" &rs.fields("address")& "</address>")
response.write("<city>" &rs.fields("city")& "</city>")
response.write("<country>" &rs.fields("country")& "</country>")
response.write("</company>")
end if
on error goto 0
%>

Notice the second line in the ASP code above: response.contenttype="text/xml". The ContentType property sets the HTTP content type for the response object. The default value for this property is "text/html". This time we want the content type to be XML.

Then we select data from the database, and builds an XML document with the data.

Posted by 1010
06.Ajax2008. 7. 8. 17:56
반응형

AJAX can be used for interactive communication with a database.


AJAX Database Example

In the AJAX example below we will demonstrate how a web page can fetch information from a database using AJAX technology.


Select a Name in the Box Below

Select a Customer:
Customer info will be listed here.

AJAX Example Explained

The example above contains a simple HTML form and a link to a JavaScript:

<html>
<head>
<script src="selectcustomer.js"></script>
</head>
<body>
<form> 
Select a Customer:
<select name="customers" onchange="showCustomer(this.value)">
<option value="ALFKI">Alfreds Futterkiste
<option value="NORTS ">North/South
<option value="WOLZA">Wolski Zajazd 
</select>
</form>
<p>
<div id="txtHint"><b>Customer info will be listed here.</b></div>
</p>
</body>
</html>

As you can see it is just a simple HTML form with a drop down box called "customers".

The paragraph below the form contains a div called "txtHint". The div is used as a placeholder for info retrieved from the web server.

When the user selects data, a function called "showCustomer()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCustomer is called.

The JavaScript code is listed below.


The AJAX JavaScript

This is the JavaScript code stored in the file "selectcustomer.js":

var xmlHttp

function showCustomer(str)
{ 
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 
var url="getcustomer.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged() 
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}


The AJAX Server Page

The server page called by the JavaScript, is a simple ASP file called "getcustomer.asp".

The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language. Look at a corresponding example in PHP.

The code runs an SQL against a database and returns the result as an HTML table:

<%
response.expires=-1
sql="SELECT * FROM CUSTOMERS WHERE CUSTOMERID="
sql=sql & "'" & request.querystring("q") & "'"

set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open sql, conn

response.write("<table>")
do until rs.EOF
  for each x in rs.Fields
    response.write("<tr><td><b>" & x.name & "</b></td>")
    response.write("<td>" & x.value & "</td></tr>")
  next
  rs.MoveNext
loop

response.write("</table>")
%>
Posted by 1010
06.Ajax2008. 7. 8. 17:56
반응형

AJAX Source Code to Suggest Example

The source code below belongs to the AJAX example on the previous page.

You can copy and paste it, and try it yourself.


The AJAX HTML Page

This is the HTML page. It contains a simple HTML form and a link to a JavaScript.

<html>
<head>
<script src="clienthint.js"></script> 
</head>
<body>
<form> 
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p> 
</body>
</html>

The JavaScript code is listed below.


The AJAX JavaScript

This is the JavaScript code, stored in the file "clienthint.js":

var xmlHttp

function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} 

function stateChanged() 
{ 
if (xmlHttp.readyState==4)
{ 
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}


The AJAX Server Page - ASP and PHP

There is no such thing as an AJAX server. AJAX pages can be served by any internet server.

The server page called by the JavaScript in the example from the previous chapter is a simple ASP file called "gethint.asp".

Below we have listed two examples of the server page code, one written in ASP and one in PHP.


AJAX ASP Example

The code in the "gethint.asp" page is written in VBScript for an Internet Information Server (IIS). It just checks an array of names and returns the corresponding names to the client:

<%
response.expires=-1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
'get the q parameter from URL
q=ucase(request.querystring("q"))
'lookup all hints from array if length of q>0
if len(q)>0 then
  hint=""
  for i=1 to 30
    if q=ucase(mid(a(i),1,len(q))) then
      if hint="" then
        hint=a(i)
      else
        hint=hint & " , " & a(i)
      end if
    end if
  next
end if
'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then 
  response.write("no suggestion")
else
  response.write(hint)
end if
%>


AJAX PHP Example

The code above rewritten in PHP.

Note: To run the entire example in PHP, remember to change the value of the url variable in "clienthint.js" from "gethint.asp" to "gethint.php".

PHP Example

<?php
header("Cache-Control: no-cache, must-revalidate");
 // Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
  $hint="";
  for($i=0; $i<count($a); $i++)
  {
  if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
    {
    if ($hint=="")
      {
      $hint=$a[$i];
      }
    else
      {
      $hint=$hint." , ".$a[$i];
      }
    }
  }
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response
echo $response;
?>
Posted by 1010
06.Ajax2008. 7. 8. 17:53
반응형

Introduction

This document describes a simple approach of implementing AJAX functionality in ASP.NET web applications. Pros and cons of using AJAX are also discussed. The document contains a working JavaScript and C#.NET code demonstrating the suggested solution.

Why AJAX

Most of you already know that AJAX stands for Asynchronous JavaScript and XML. This technology was introduced first by Microsoft (from my best knowledge) back in 1999, and had been known as “DHTML / JavaScript web application with remote calls”. The whole idea of the technology was to allow an internet browser to make an asynchronous HTTP call to remote pages/services, and update a current web page with the received results without refreshing the whole page. By creators’ opinion, this should have improved customers’ experience, making HTTP pages look and feel very similar to Windows applications.

Because the core implementation of this technology was based on internet browser functionality, the usability was very limited at that time. But several years later, the technology has been reborn with new browsers support and massive implementation by such giants as Google, Amazon.com, eBay, etc.

Today, it’s known as AJAX, and considered as a natural part of any dynamic web page with advanced user experience.

Solution Description

The suggested approach provides a very simple, yet effective implementation of the AJAX functionality. It’s very easy to maintain and change, does not require any special skills from developers, and, from our best knowledge, is cross-browser compatible.

Basically, a regular AJAX-like implementation includes two main components: a client HTML page with JavaScript code making an AJAX call and receiving a response, and a remote page that can accept a request and respond with the required information. The JavaScript code on the client page is responsible for instantiating an XmlHttp object, then providing this object with a callback method which will be responsible for processing the received information, and finally, sending a request to the remote page via the XmlHttp object. All this is done by the JavaScript code.

Our approach is intended for use in ASP.NET applications, and considers the following possible scenarios:

  • AJAX calls may be performed on different ASP.NET pages of the web application to different remote pages;
  • A remote page URL may contain dynamically calculated parameters, and it may be more convenient to build a URL string in the code-behind of the ASP.NET page;
  • A remote page may respond with a complex data requiring parsing before updating an HTML page, that once again may be done in the code-behind of the ASP.NET page;
  • A remote page may be either an external third party page, or the web application’s own page or service.

All these considerations are illustrated by the diagram below:

Solution diagram

Implementation

Basic AJAX JavaScript methods

I divided all the JavaScript methods into two parts: calling page specific JavaScript methods, and AJAX JavaScript methods common for all the calling pages. Specific methods include a callback method as well, as it is responsible for updating the page content. Common AJAX methods are responsible for instantiating an XmlHttp object and sending an asynchronous request to the remote page.

Getting an XmlHttp object differs depending on the type of the browser. I distinguish two basic types: a Microsoft browser which is one of the IE family, and a Mozilla browser which is one of Mozilla Firefox, Netscape, or Safari. I tested the code with the Opera browser too, but I would not guarantee that it will always be working well.

Collapse
function GetXmlHttpObject(handler)
{ 
    var objXmlHttp = null;
    if (!window.XMLHttpRequest)
    {
        // Microsoft
        objXmlHttp = GetMSXmlHttp();
        if (objXmlHttp != null)
        {
            objXmlHttp.onreadystatechange = handler;
        }
    } 
    else
    {
        // Mozilla | Netscape | Safari
        objXmlHttp = new XMLHttpRequest();
        if (objXmlHttp != null)
        {
            objXmlHttp.onload = handler;
            objXmlHttp.onerror = handler;
        }
    } 
    return objXmlHttp; 
} 

function GetMSXmlHttp()
{
    var xmlHttp = null;
    var clsids = ["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0",
                 "Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0", 
                 "Msxml2.XMLHTTP.2.6","Microsoft.XMLHTTP.1.0", 
                 "Microsoft.XMLHTTP.1","Microsoft.XMLHTTP"];
    for(var i=0; i<clsids.length && xmlHttp == null; i++) {
        xmlHttp = CreateXmlHttp(clsids[i]);
    }
    return xmlHttp;
}

function CreateXmlHttp(clsid) {
    var xmlHttp = null;
    try {
        xmlHttp = new ActiveXObject(clsid);
        lastclsid = clsid;
        return xmlHttp;
    }
    catch(e) {}
}

According to Umut Alev, the code for the GetMSXmlHttp method can be simplified considering that we do not have to refer MSXML5 as it has been designed only for Office applications. Correspondingly, the simplified revision of the GetMSXmlHttp method may look as follows:

function GetMSXmlHttp() {
    var xmlHttp = null;
    var clsids = ["Msxml2.XMLHTTP.6.0",
                  "Msxml2.XMLHTTP.4.0",
                  "Msxml2.XMLHTTP.3.0"];
    for(var i=0; i<clsids.length && xmlHttp == null; i++) {
        xmlHttp = CreateXmlHttp(clsids[i]);
    }
    return xmlHttp;
}

As you see, GetXmlHttpObject methods accept a handler parameter which is a name of the callback method that should be defined in the page-specific code. Now that we already have an XmlHttp object, we can send an asynchronous request.

function SendXmlHttpRequest(xmlhttp, url) { 
    xmlhttp.open('GET', url, true); 
    xmlhttp.send(null); 
}

I use a GET HTTP method to a given URL, but this can be easily changed by changing the JS code above.

Page-specific methods

Now we have all the methods we need to perform a call to the remote page. In order to do this, we need to pass the callback method name to the GetXmlHttpObject method and then pass the URL string to the SendXmlHttpRequest method.

Collapse
var xmlHttp; 

function ExecuteCall(url)
{ 
    try 
    { 
        xmlHttp = GetXmlHttpObject(CallbackMethod); 
        SendXmlHttpRequest(xmlHttp, url); 
    }
    catch(e){} 
} 
    
//CallbackMethod will fire when the state 
//has changed, i.e. data is received back 
function CallbackMethod() 
{ 
    try
    {
        //readyState of 4 or 'complete' represents 
        //that data has been returned 
        if (xmlHttp.readyState == 4 || 
            xmlHttp.readyState == 'complete')
        {
            var response = xmlHttp.responseText; 
            if (response.length > 0)
            {
                //update page
                document.getElementById("elementId").innerHTML 
                                                   = response; 
            } 
        }
    }
    catch(e){}
}

The CallbackMethod is responsible for updating the page content. In our example, it simply updates the inner HTML of the given HTTP element. But in real life, it can be much more complex.

The last question regarding the calling page implementation is how we call the ExecuteCall JS method. Well, it depends on what the page is doing. In some cases, the ExecuteCall method can be called when the JS event is fired. But if that is not the case, we can register the method as a startup script for the page using the corresponding C# code in the page's code-behind.

Page.RegisterStartupScript("ajaxMethod", 
   String.Format("<script>ExecuteCall('{0}');</script>", url));

We can add this line of code either in the Page_Prerender or Page_Load method of the ASP.NET code-behind file.

Remote Page

Let’s find out what a remote page could look like. If this is an ASP.NET page (what we assume), we are interested in the code-behind only. We can easily remove all the code from the .aspx file: it won’t affect the behavior of the page in any way.

For example, we take a public web service that converts temperature values in Celsius to Fahrenheit and vice versa. The service is available here. If you add this URL as a web reference to your project, Visual Studio will generate a proxy class with the name com.developerdays.ITempConverterservice in your current namespace. Our remote ASP.NET page, let’s name it getTemp.aspx, will accept a query string parameter with the name “temp” which should contain an integer value of a temperature in Celsius to convert. So the target URL to the remote page will look like this: http://localhost/getTemp.aspx?temp=25. And the code-behind for this page is shown below:

private void Page_Load(object sender, EventArgs e)
{
    Response.Clear();
    string temp = Request.QueryString["temp"];
    if (temp != null)
    {
        try
        {
            int tempC = int.Parse(temp);
            string tempF = getTempF(tempC);
            Response.Write(tempF);
        }
        catch
        {
        }
    }
    Response.End();
}

private string getTempF(int tempC)
{
    com.developerdays.ITempConverterservice 
          svc = new ITempConverterservice();
    int tempF = svc.CtoF(tempC);
    return tempF.ToString();
}

According to our convention, we can now build a URL string for the remote page that we will pass to the RegisterStartupScript method in the example above, like this:

int tempC = 25;
string url = String.Format("http://localhost/" + 
             "getTemp.aspx?temp={0}", tempC);

Using the approach with an intermediate ASP.NET page, calling in its turn a remote service, allows simplifying response processing, especially if it requires parsing. In simple cases when the response contains just text, we can pass the remote service URL directly to the JS ExecuteCall method.

Conclusion

This article is aimed to illustrate the simplicity of using the AJAX technology in any ASP.NET application. While AJAX has some drawbacks, it also provides some advantages from the user experience perspective. It’s completely up to the developer whether to use the AJAX technology or not, but I have just demonstrated that in simple cases, it does not take a long time or require any special skills.

Credits

I would like to thank my colleagues Oleg Gorchkov and Chris Page who helped me out with testing and optimizing the approach described in the article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alexander Turlov


Alexander Turlov has been working in IT industry since 1987. His programming experience includes such languages as FORTRAN, Pascal, and Basic, C, C++ and C#. He's been working for different industries like science, manufacturing, retail, utilities, finance, insurance, health care, education and so on. His current area of interests is .NET, C#, and ASP.NET programming. He is working in software development doing architecture, design and development on .NET platform and using Microsoft products such as Visual Studio, SQL Server, P&P Software Factories, and Enterprise Library. He holds a M.Sc. degree in physics and an MCSD.NET certification.

View my profile on LinkedIn

View my blog
Occupation: Architect
Location: Canada Canada

Other popular Ajax and Atlas articles:

Posted by 1010
98..Etc/Log4J2008. 7. 8. 17:39
반응형

A simple Log4J example

By Alvin J. Alexander, devdaily.com

The following class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications. As you can see the configuration is pretty simple.

package com.devdaily.log4jdemo;

import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;

public class Log4JDemo
{
  static final Category log = Category.getInstance(Log4JDemo.class);
  static final String LOG_PROPERTIES_FILE = "lib/Log4J.properties";

  public static void main(String[] args)
  {
    // call our constructor
    new Log4JDemo();
    // Log4J is now loaded; try it
    log.info("leaving the main method of Log4JDemo");
  }

  public Log4JDemo()
  {
    initializeLogger();
    log.info( "Log4JDemo - leaving the constructor ..." );
  }

  private void initializeLogger()
  {
    Properties logProperties = new Properties();

    try
    {
      logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE));
      PropertyConfigurator.configure(logProperties);
      log.info("Logging initialized.");
    }
    catch(IOException e)
    {
      throw new RuntimeException("Unable to load logging property " + LOG_PROPERTIES_FILE);
    }
  }
}

After a few class level fields are created, the action begins with the main method, which first calls the constructor for this class. The constructor then calls the initializeLogger method. This method actually does the work of loading the Log4J properties file. It then calls the configure method of the PropertyConfigurator class.

Once this is done I call the info method of the log object several times. Notice that I could have also called other methods like logger.warn(), log.debug(), log.error(), or log.fatal(), but to keep it simple I'm just showing log.info().

The Log4J Properties File

Before I leave this quick tip I also need to show the Log4J properties file that I'm using. My file is named Log4J.properties, and for the purpose of this demonstration I'm keeping it in a sub-directory of my project named lib. Here are the contents:

# STDOUT appender
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%d %p [%t] %C{1} - %m\n

# use the STDOUT appender. set the level to INFO.
log4j.category.com.devdaily.log4jdemo.Log4JDemo=INFO, STDOUT


Posted by 1010
98..Etc/Log4J2008. 7. 8. 17:37
반응형
Posted by 1010
06.Ajax2008. 7. 8. 17:21
반응형

http://code.google.com/apis/ajaxsearch/samples.html


Google AJAX Search API Samples

Simple Hello World

This sample application is the canonical "Hello World" of Google AJAX Search API. This simple application instantiates the search control in read-only mode.

Custom Search EnginesNew!

This sample demonstrates how to use Google Custom Search Engines in conjunction with the Google AJAX Search API. The sample integrates four custom search engines along with blog, video, and news search.

Video Bar SolutionNew!

This sample demonstrates the brand new GSvideoBar() solution. This is a very light weight solution that allows you to place a dynamic video bar vertically or horizontally on your page or blog. You can have multiple Video Bars on a page, all sharing a common video player. The Video Bar also composes nicely with the Video Search Control Solution. Take a look, and be sure to also visit our AJAX Search API Playground blog where we have integrated the Video Bar into the template.

Google AJAX Search API in TypePad

This sample demonstrates the use of the Google AJAX Search API including core web and blog search, the video search solution, and the map search control solution, all hosted in a TypePad blog. The sample includes links to the TypePad module templates and instructions for applying this to your own TypePad based blog.

Google AJAX Search API in Blogger

Identical to the TypePad based solution, but designed for Blogger

Video Search Control Solution

This sample demonstrates the brand new GSvideoSearchControl() solution. This solution allows you to easily embed a rich video search control on your site, blog, etc. The control lets you search, tag, and play videos without leaving the page. The page is very easy to integrate into your applications and can be integrated in just a few lines of code. Feel free to copy and clone the solution to meet your needs, or use it as it stands.

Map Search Solution

This sample uses the brand new GSmapSearchControl() solution to show you how to add a a simple geo-oriented search control anywhere on your site with just a few lines of code. Feel free to copy and clone the solution to meet your needs, or use it as it stands. The sample linked to above demonstrates how to use it. If you can write this, new GSmapSearchControl(container, "1000 NE Multnomah, Portland, OR");, then you can easily add a nice little local search control to your site.

Phone List

This sample demonstrates how to build a "Phone List" of favorite restaurants, etc, using the Google Ajax Search API.

Blog Comment Form

This sample application demonstrates how you can incorporate the AJAX Search API in user composition. In this case, users can clip Google search results to their comments on a blog post.

My Favorite Places

This sample application shows how to to use the Google AJAX Search API to create a collection of favorite places. From a programming perspective, it demonstrates the use of a custom input element and direct use of GSearch objects.

Searchers and Options

This sample application demonstrates many of the programmable options of the Search Control, allowing you to select various searchers, drawing modes, etc.

Locale Selection

This sample application demonstrates the Google AJAX Search API running its UI in a variety of languages.

My Favorite Places #2

This sample application builds on the original My Favorite Places sample and is designed to demonstrate search result and search control dynamic styling, controlling the location of clipped search results, etc. Before diving into this sample, if would be a good idea to become familiar with the previous samples.

Wish List

Similar to the Lead Manager sample, this sample demonstrates building more complex lists, something like a "what I want for christmas list, or what I want for my birthday." This sample deomstrates search result clipping as well as site restricted search.

Video Search + Social Networks

This sample demonstrates how video search might integrate into social networking applications. Note the use of search result clipping to add a little video into a message as well as the ability to remember a search result into a stack of favorites.

Posted by 1010
01.JAVA/Java2008. 7. 8. 17:16
반응형
Code sample
Java IDL Code Samples
 
IDL Code Samples

Java IDL is a CORBA-compliant technology for distributed objects that lets objects interact regardless of whether they are written in the Java programming language or another language.

CORBA Hello World Example File Transfer Example Portable Object Adapter Example Servlets Example
Posted by 1010
반응형
http://hanho9.cafe24.com/google_sh.html

h 는 도움말 입니다.

ls 명령어도 먹겠죠.(?)
Posted by 1010