Wednesday, January 20, 2010
Java Coding Standards
Use a global error page.
Always link to Actions, never to server pages.
Use the action attributes tag to avoid embedding Action extension.
Use s:url to reference HTML assets.
Use s:include to include pages
If an image, or other swatch of markup, is being used by multiple pages,
remove it to its own server page and include it where necessary.
Extend the UI tags as needed.
Consider using the message resources for page titles, control labels, and so
forth, even if the application is not being localized.
It is often useful to seperate the concern of what message to display from the concern of where to display it.
o Use the XML framework to validate input.
o Use Java script code using JS file only (by including .js file)
Struts tags prefix should be ‘s’ only e.g.
Use predefined CSS file for style and apply to textfield, label, dropdown, button, table and so on.
Follow specified format of message in java script for alert/confirm/prompt messages.
Use TILES for menu, header and footer. (These jsps are will be created by team)
Use DISPLAY TAG for listing purpose (Example: Policy Master listing based on search criteria such as policy no, premium range and so on). Usage of the display tag will be explained.
Use configured parameters in display tag (such as no of records per page, no of pages per list…etc) from property files.
Use comments to make clear idea of coding. Especially for looping and logical flow.
Give jsp name as per standard and naming conventions.
Specify tabIndex for each and every input component in top to bottom order. (As customer will always use TAB to jump to next component.
Use labels using property file.
Avoid the usage of the scriplets inside the jsp pages.
Choose the right include mechanism
Use custom tags
Use the JSTL Expression Language
Don’t:
1. Include any menu, header or footer JSP.
2. Write Java script code within JSP file.
3. Use style in JSP.
4. Put unnecessary alert/confirm/prompt message in java script.
5. Comments for each and every LOC.
6. Use labels as hard code value.(As our application support i18n)
7. Mix business logic with presentation
1.2 Java Script Guidelines
Use window.location.href= 'url' instead of window.navigate('url')
Do following steps to disable href links.
Write common disableAnchor (ojb, boolean) function in common Java script file.
function disableAnchor(objId, disable)
{
var obj = document.getElementById(objId);
if(obj != null)
{
if(disable)
{
var href = obj.getAttribute("href");
var onclick = obj.getAttribute("onclick");
//First we store previous value in a new attribute
if(href && href != "" && href != null)
{
obj.setAttribute('href_bak', href);
}
if(onclick != null)
{
obj.setAttribute('onclick_back', onclick);
obj.setAttribute('onclick', "void(0);");
}
obj.removeAttribute('href');
//obj.style.color="gray"; // any color
}
else
{
var hrefBack = obj.getAttribute("href_bak");
var onclickBack = obj.getAttribute("onclick_back");
if(onclickBack !=null )
{
obj.setAttribute('onclick', onclickBack);
obj.removeAttribute('onclick_back');
}
if(hrefBack !=null )
{
obj.setAttribute('href', hrefBack);
obj.removeAttribute('href_bak');
//obj.style.color="blue"; // any color
}
}
}
}
Call this function from java scripts wherever want to enable or disable href links. See below example below.
E.g
Script
disableAnchor(“Okbutton”,true); // Disable Link
disableAnchor(“Okbutton”,false); // Enable Link
JSP or HTML
Ok
1.3 Java Best Practices
Strings
1. Create strings as literals instead of creating String objects using 'new' key word whenever possible.
2. Use String.intern() method if you want to add number of equal objects whenever you create String objects using 'new' key word.
3. + Operator gives best performance for String concatenation if Strings resolve at compile time.
4. StringBuffer with proper initial size gives best performance for String concatenation if Strings resolve at run time.
5. Assign null values to String literals when no longer needed.
Using Final Keyword
1. Use the final keyword when the method must not be overridden.
2. Declare Constanta as static final.
3. Avoid Finalizers.
4. Declare method arguments as final if they are not modified in the method.
Serialization
1. Use 'transient' key word for unnecessary variables that need not be read from/written into streams.
2. When you write RMI, EJB or any other technologies that uses built in Serialization to pass objects through network, use 'transient' key word for unnescessary variables.
3. Class (static) variables ignores by Serialization process like 'transient' variables.
IO
1. Reading and writing data using default behavior of some streams that is byte by byte read/write causes slow performance.
2. Buffered input streams and buffered output streams increase performance.
3. Custom buffering increases performance significantly.
Object Creation
1. Avoid creating objects in a loop.
2. Use String literals instead of String objects (created using the 'new' keyword) if the content is same.
3. Make used objects eligible for garbage collection.
4. Do not keep inheritance chains long.
5. Accessing local variables is faster than accessing class variables
6. Use lazy evaluation, lazy object creation whenever possible.
Handling loops
1. Use integer as loop index variable.
2. Use System.arraycopy() to copy arrays.
3. Avoid method calls in loops.
4. It is efficient to access variables in a loop when compared to accessing array elements.
5. Compare the termination condition in a loop with zero if you use non-JIT or Hotspot VMs.
6. Avoid using method calls to check for termination condition in a loop
7. When using short circuit operators place the expression which is likely to evaluate to false on extreme left if the expression contains &&.
8. When using short circuit operators place the expression which is likely to evaluate to true on extreme left if the expression contains only ||.
9. Do not use exception handling inside loops
Exceptions Handling
1. Be specific while handling the exception in your catch block.
2. Be specific while throwing exception in your throws clause.
3. Do not use Exception Handling to control programming flow.
4. Very little overhead is imposed by using exception handling mechanism unless an exception occurs or thrown a new exception object explicitly.
5. Always use the finally block to release the resources to prevent resource leaks.
6. Handle exceptions locally wherever possible.
7. Do not use Exception handling in loops.
Collection
Lists:
1. Use ArrayList with proper initialization if you don't want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
2. Use Vector with proper initialization if you want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
3. Use LinkedList if you don't want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
4. Use synchronized LinkedList if you want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
5. Use ListIterator than Iterator and Enumeration for List types
Sets:
1. Use HashSet for maintaining unique objects if you don't want thread safe for the collection for all basic (add/remove/access) operations otherwise use synchronized HashSet for thread safe.
2. Use TreeSet for ordered and sorted set of unique objects for non-thread safe collection otherwise use synchronized TreeSet for thread safe
Maps:
1. Use HashMap for non-thread safe map collection otherwise use Hashtable for thread safe collection.
2. Use TreeMap for non-thread safe ordered map collection otherwise use synchronized TreeMap for thread safe.
JDBC
1. Use Type two drivers for two tiered applications to communicate from java client to database that gives better performance than Type1 driver.
2. Use Type four drivers for applet to database communication that is two tiered applications and three tiered applications when compared to other drivers.
3. Use Type one driver if you don't have a driver for your database. This is a rare situation because all major databases support drivers or you will get a driver from third party vendors.
4. Use Type three driver to communicate between client and proxy server ( weblogic, websphere etc) for three tiered applications that gives better performance when compared to Type 1 &2 drivers.
5. Pass database specific properties like defaultPrefetch if your database supports any of them.
6. Get database connection from connection pool rather than getting it directly
7. Use batch transactions.
8. Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
9. Your database server may not support all isolation levels, be aware of your database server features.
10. Use PreparedStatement when you execute the same statement more than once.
11. Use CallableStatement when you want result from multiple and complex statements for a single request.
12. Use batch update facility available in Statements.
13. Use batch retrieval facility available in Statements or ResultSet.
14. Set up proper direction for processing rows.
15. Use proper getXXX() methods.
16. Close ResultSet, Statement and Connection whenever you finish your work with them.
17. Write precise SQL queries.
18. Cache read-only and read-mostly tables data.
19. Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc.
HTTP Session Handling Best Practices
1. Create sessions sparingly. Session creation is not free. If a session is not required, do not create one.
2. Use javax.servlet.http.HttpSession.invalidate () to release sessions when they are no longer needed.
3. Keep session size small, to reduce response times. If possible, keep session size below seven KB.
4. Use the directive <%page session="false"%> in JSP files to prevent the Enterprise Server from automatically creating sessions when they are not necessary.
5. Avoid large object graphs in an HttpSession. They force serialization and add computational overhead. Generally, do not store large objects as HttpSession variables.
6. Don’t cache transaction data in HttpSession. Access to data in an HttpSession is not transactional. Do not use it as a cache of transactional data, which is better kept in the database and accessed using entity beans. Transactions will rollback upon failures to their original state. However, stale and inaccurate data may remain in HttpSession objects. The Enterprise Server provides “read-only” bean-managed persistence entity beans for cached access to read-only data.
Using Patterns in J2EE
1. Use ServiceLocator pattern to reduce expensive JNDI lookup process.
2. Use MessageFacade/ServiceActivator pattern to avoid large method execution process.
3. Use ValueObject pattern to avoid fine grained method calls over network.
Use ValueObjectFactory/ValueObjectAssembler pattern to avoid multiple network calls for a single client request.
1.4 Struts best practices
Configuration
• Use namespaces to organize your application into logical "modules" or units of work.
• Place each namespace into its own struts configuration file
• Try to keep the Actions classes for the namespace in a common package
• Store the struts configuration for that namespace with the Actions
If you are using JSPs, try to name the JSP folder after the Action package.
If you using templates, bundle the templates with the Actions.
Remember, if the namespace needs to change, you do not need to change packages or JSP folders.
• Use Exception handlers
Local or global as needed
Configure a global handler for Throwable
• Use global result handlers for common results
Error
Login
• Define a base class constants for common Result names
Action
• Validate all input fields — always on the server-side, and optionally on the clientside.
• Consider using Model Driven or POJOs if a business object layer contains most properties
• Do not use Model Driven if the business objects are not well designed or obtained through factory methods
• Write thread-safe Interceptors.
• Use a base support Action class means Extend ActionSupport
• Use SessionAware and ApplicationAware to avoid referring to servlet resources directly
• Do not embed business logic in action classes.
• Avoid chaining "business" actions.
Bad: MoveAction = CopyAction -> DeleteAction
Good: Extend your facade.
• Prefer BeanUtils copyValues to move data from Action properties to a
Business object.
• Consider using a JavaBean helper to encapsulate data and messages
Returned from the Model.
Servlet & JSP
The life cycle of a servlet can be categorized into four parts:
1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute
2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.
The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.
Servlet Context
ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application.
Web application initialization:
1. First of all the web container reads the deployment descriptor file and then creates a name/value pair for each
2. After creating the name/value pair it creates a new instance of ServletContext.
3. Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters.
4. The servlet and jsp which are part of the same web application can have the access of the ServletContext.
The Context init parameters are available to the entire web application not just to the single servlet like servlet init parameters.
How can we do the mapping of the Context init parameters in web.xml
JSP ARCHITECTURE
JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.
javax.servlet.jsp package defines two interfaces:
• JSPPage
• HttpJspPage
These interfaces defines the three methods for the compiled JSP page. These methods are:
• jspInit()
• jspDestroy()
• _jspService(HttpServletRequest request,HttpServletResponse response)
In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.
Directives :
Listing some of them to start off :
1) Page
Syntax : < %@ page Language=”Java” extends=”
Attributes:
a. Language = “Java”
b. Import = “Class”
c. Buffersize = “”
d. Scope = “REQUEST/PAGE/SESSION/APPLICATION”
e. And etc….
Page directive is aimed to define certain attribute of a JSP page for e.g. Language of the page in which the page content should be written , which class to be imported so that it can be used within the JSP page.
2) Include
Syntax: <%@ include file=”
Attributes:
a. file = “
This directive is to include the a HTML, JSP or Sevlet file into a JSP file. This is a static inclusion of file i.e. it will be included into the JSP file at the time of compilation and once the JSP file is compiled any changes in the included the file will not the reflected.
Declarations:
Syntax: <%! Declare all the variables here %>
Scriplets:
Syntax: <% All your scripts will come here %>
Expressions:
Syntax: <%= expression evaluation and display the variable %>
Standard Action:
Syntax:
Include
This inclusion of file is dynamic and the specified file is included in the JSP file at run-time i.e. out put of the included file is inserted into the JSP file.
Forward
This will redirect to the different page without notifying browser.
And many more.
Custom Tags:
taglib
Syntax: <%@ taglib uri=”
Attributes:
a. uri = “
b. prefix = “
prefix is alias name for the tag library name
Implicit Objects:
Implicit Objects in JSP are objects that are automatically available in JSP. Implicit Objects are Java objects that the JSP Container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.
There are many implicit objects available. Some of them are:
request: The class or the interface name of the object request is http.httpservletrequest. The object request is of type Javax.servlet.http.httpservletrequest. This denotes the data included with the HTTP Request. The client first makes a request that is then passed to the server. The requested object is used to take the value from client’s web browser and pass it to the server. This is performed using HTTP request like headers, cookies and arguments.
response: This denotes the HTTP Response data. The result or the information from a request is denoted by this object. This is in contrast to the request object. The class or the interface name of the object response is http.HttpServletResponse. The object response is of type Javax.servlet.http. >httpservletresponse. Generally, the object response is used with cookies. The response object is also used with HTTP Headers.
Session: This denotes the data associated with a specific session of user. The class or the interface name of the object Session is http.HttpSession. The object Session is of type Javax.servlet.http.httpsession. The previous two objects, request and response, are used to pass information from web browser to server and from server to web browser respectively. The Session Object provides the connection or association between the client and the server. The main use of Session Objects is for maintaining states when there are multiple page requests. This will be explained in further detail in following sections.
Out: This denotes the Output stream in the context of page. The class or the interface name of the Out object is jsp.JspWriter. The Out object is written: Javax.servlet.jsp.JspWriter
PageContext: This is used to access page attributes and also to access all the namespaces associated with a JSP page. The class or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext
Application: This is used to share the data with all application pages. The class or the interface name of the Application object is ServletContext. The Application object is written: Javax.servlet.http.ServletContext
Config: This is used to get information regarding the Servlet configuration, stored in the Config object. The class or the interface name of the Config object is ServletConfig. The object Config is written Javax.servlet.http.ServletConfig
Page: The Page object denotes the JSP page, used for calling any instance of a Page's servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object
Java Beans
Java Beans are reusable components. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a class.
JSP’s provide three basic tags for working with Beans.
•
bean name = the name that refers to the bean.
Bean class = name of the java class that defines the bean.
•
id = the name of the bean as specified in the useBean tag.
property = name of the property to be passed to the bean.
value = value of that particular property .
An variant for this tag is the property attribute can be replaced by an “ * ”. What this does is that it accepts all the form parameters and thus reduces the need for writing multiple setProperty tags. The only consideration is that the form parameter names should be the same as that of the bean property names.
•
Here the property is the name of the property whose value is to be obtained from the bean.
BEAN SCOPES :
These defines the range and lifespan of the bean.
The different options are :
o Page scope :
Any object whose scope is the page will disappear as soon as the current page finishes generating. The object with a page scope may be modified as often as desired within the particular page but the changes are lost as soon as the page exists.
By default all beans have page scope.
o Request scope :
Any objects created in the request scope will be available as long as the request object is. For example if the JSP page uses an jsp:forward tag, then the bean should be applicable in the forwarded JSP also, if the scope defined is of Request scope.
o The Session scope :
In JSP terms, the data associated with the user has session scope. A session does not correspond directly to the user; rather, it corresponds with a particular period of time the user spends at a site. Typically, this period is defined as all the visits a user makes to a site between starting and existing his browser.
Objective 5) JSP implicit objects
What are Implicit Objects?
When writing Servlets the available objects are fairly obvious as they are the parameters to methods, thus if you are overriding the doPost method you will have a signature of
public void doPost(HttpServletRequest request,
HttpServletResponse response)
When writing JSP pages the implicit objects are created automatically for you within the service method . You just have to know what the implicit objects are, but as most of them match closely to those available in Servlet methods they are not too difficult to memorise. You will have come across one of the implicit objects already with the out object which allows you to send information to the output stream.
Note that the implicit variables are only available within the jspService method and thus are not available within any declarations. Thus for example the following code will cause a compile time error.
<%! public void amethod(){ out.print("Hello"); } %>
The request and response implicit objects
The request implicit object is an instance of HttpServletRequest, and response is an instance of HttpServletResponse objects. They are available in a similar way to the request and response object passed to the doGet and doPost methods in servlets.
A typical use for the request is to get the details of HTTP query string such as query names and parameters.
<%= request.getQueryString() %>
Will display the query string after the name of the jsp file itself. Thus if this code is within a file called hello.jsp and is called with the url as follows
http://localhost:8080/chap03/hello.jsp?thisisthequerystring
The output will include thisisthequerystring as part of the page.
The response can be used for the same purposes as the HttpServletResponse in a servlet, such as adding cookies or headers.
The request and response objects are the same as the parameters to doPost and represent instances of HttpServletRequest and HttpServletResponse respectively.
The out implicit object
The out implicit object has a type of jsp.JspWriter. The out object can be used in a similar way to System.out is used in plain ordinary Java programs, i.e.
<% out.print("Hello World"); %>
The parameters of out are sent to the output stream, which generally means they end up visible in the browser requesting the JSP page.
session
The session implicit object is an instance of
javax.servlet.http.HttpSession
The session concept is a way of allowing multiple requests from the same client to be group together as part of a single “conversation”. This is a way of getting around the basic architectural limitation within HTTP in that it was designed as a stateless protocol, i.e. web servers “forget” about each client as soon as a request has finished execution. The default way of logically linking multiple requests from the same client is by generating a cookie that stores a value unique to the client. After the first request establishes a session, each subsequent request reads that cookie and can thus identify the unique client.
With the session object you do not need the type of code required in a Servlet whereby you have to call the getSession method to access an existing session or start a new one. Typical uses of the session object are for getting and setting attributes. Thus you can add a new attribute to the session with code like the following.
<% session.setAttribute("username","marcusgreen"); %>
config
The config implicit object is an instance of
javax.servlet.ServletConfig
And represents the parameters set up within the deployment descriptor. To set up the configuration a servlet is configured within web.xml , but instead of creating a
The config object can be used to retrieve parameters using its
getInitParameter(String param)
method.
The config object can be used to retrieve the ServletContext object through its getServletContext method. Thus the following code retrieves information about the currently executing server, and in my own setup it generates the output.
Apache Tomcat/5.5.9
<% ServletContext ct = config.getServletContext(); out.print(ct.getServerInfo()); %>
application
The application implicit object is an instance of javax.servlet.ServletContext. It refers to the overall web application environment that the JSP belongs to. According to the API docs
“Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.”
In Apache Tomcat a web application will be contained in an individual directory under the webapps directory. A typical use of the application object is to get access to the application wide initialisation parameters. Because the application and config objects have similar and slightly confusing uses the following code shows how they can be used along with a deployment descriptor (WEB.XML) that sets up the appropriate initialisation parameters for them.
The file index.jsp
<% /*for parameters declared at the application level . *i.e. under the WEB-APP tag of the deployment descriptor */ out.print(application.getInitParameter("myparam")); /*for a specific resource within an application *identified as a servlet in the deployment descriptor */ out.print(config.getInitParameter("myparam2")); %>
The deployment descriptor (WEB.XML)
MyServlet
/index.jsp
MyServlet
/index.jsp
The page implicit object
The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method. Thus in the Servlet generated by tomcat the page object is created as
Object page = this;
Because page is of type Object it is of less direct use than simply accessing the implicit this object. To access any of the methods of the servlet through page it must be first cast to type Servlet. Thus the two following lines of code are equivalent.
<% this.log("log message"); %>
<% ((HttpServlet)page).log("anothermessage"); %>
As you probably will not be using the page object in your own code the main thing to remember for the exam is that it is not the same as the pageContext object and that it is of type Object.
The pageContext implicit object
The pageContext object has a type of javax.servlet.jsp.PageContext and according to the API documents
“A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically “http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/PageContext.html
So it can be seen as a convenience object for tasks such as transferring requests to other web resources. Much of its functionality appears to be for the convenience of generating the servlet from the JSP, thus the following example of a servlet generated from the Tomcat container shows how PageContext is used to populate other implicit objects.
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
A typical use of the pageContext is to to include another resource or forward to another resource. Thus the following would forward from the current page to menu.jsp
<% pageContext.forward("menu.jsp"); %>
The exception implicit object
The exception implicit object is of type
java.lang.Throwable
This object is only available to pages that have isErrorPage set to true with the directive
<%@ page isErrorPage='true' %>
The exception object refers to the exception triggered by the page that uses this page as an exception handler
The following code demonstrates the use of the exception implicit object. The first page uses the errorPage directive to set up the JSP page to use when an error occurs, and the second page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the error.
First page
<%@page errorPage="ErrorPage.jsp" %>
<% int i=10; /*Divide by zero, generates an error */ out.print(i/0); %>
ErrorPage.jsp
<%@ page isErrorPage='true' %>
<% out.print("
Here is the error message
");out.print(exception.getMessage());
%>
Declarative handling of exceptions
It is also possible to map HTTP error codes and or Java exception types to an error page in the deployment descriptor. This is done at the web application level by using the
java.sql.SQLException
/errorpage.jsp
The following tags would re-direct all HTTP 404 errors to the /errorpage.jsp page
Difference between include directive & include action in JSP
include directive - <%@ include file="fileName" %> - as is the case with all other directives in a JSP page, this include directive is also processed at the time when the JSP page is translated into its equivalent servlet. This directive simply causes the contents of the specified file to be pasted into the JSP page at the place where the page contains this directive. Irrespective of whether the included resource is a static resource or a JSP page - only the contents of the file are pasted (and not the processed results). This directive is normally used for including static resources only - like, banner, header, footer, etc. for the obvious reason.
One common issue with include directive (if it's used to include another JSP) is that the main JSP (which calls this directive to include another JSP) doesn't get re-compiled in the case when the included JSP changes but not the main JSP. Reason being, a JSP is re-compiled only if the contents of the JSP changes. Now in this case, the main JSP (after inclusion) remains the same. Once the include directive has been processed during the translation phase, the main JSP is unaware that part of its contents have come from another file. The entire translated file is treated as a single unit. Any changes to the main JSP will initiate the translation phase and then compilation phase again and hence the specified is included again. So, any modification in the included JSP will not get reflected unless the main JSP is also changed.
include action -
Remember that we can specify only a relative URL i.e., a resource which is in the same context as the calling JSP page. Since the resource is called by passing both the request and response objects, hence the called JSP can access any beans defined in the request using the
Difference between include directive & include action
• The most evident difference is that include directive is processed at the translation time while the include action is processed at the run time.
• include directive don't require a relative file path (it can be either relative or absolute) whereas the include action requires the page name to be relative to the context of the calling JSP.
• include action always includes the contents of the specified file irrespective of whether the specified file is a static resource or a dynamic resource whereas include action executed a specified dynamic resource and only the result gets included in the response of the calling JSP. In case of static resource even the include action just includes the contents only as in that case the resource can't be executed.
• include directive does not ask for any parameters to be passed, which is quite obvious because include directive doesn't execute the specified resource whereas we may specify additional parameters which may be used while execution of the specified resource in case of include action.
• include directive can't access the objects created in the request scope (in fact, it doesn't need to access any again because it's not going to execute the resource) whereas the include action can access the objects created with the request scope.
JSP’s offer a unique feature of “Tag Libraries”. Simply put, these are custom defined JSP tags. They are basically meant for componentizing presentation level logic. They are very similar to beans except the fact that Beans are used to separate Business logic.
Every tag is mapped to a particular class file which is executed whenever the tag is encountered in an JSP file.
The general syntax :
<%@ taglib uri=“ - - - - - ” prefix = “ - - - ” %>
The parent of the tag is the JSP tag within which it is nested, if there isn’t one, its set to null.
There are two things to remember while using TAGLIB’s :
The Class file should be created and it should be deployed in the Servlet folder of the web server. The class file should implement the Tag and BodyTag interfaces.
The mapping of a particular tag to a particular class file should be done in the taglib.tld file.
The tag is then ready to be used in the JSP file !!
The taglib file forms the central description for the tag library :
This file is an XML document that defines the tag’s operation.
It maps the tag name on the page to the implementing class.
It defines inputs to the class.
It references the helper class that provides details of any output variables set by the tag class.
This Tag and Bodytag have some methods, these all methods are callback methods.
Tag methods: doStartTag()
doEndTag()
Body Tag : doAfterBody()
Let’s have small example to display Hello World :
1. First we write simple jsp file
<% @ taglib uri=”/taglib.tld” prefix=”nt” %>
2. It will look for file specified in uri attribute,that file will be
empty
3. Next this will look for Helloworld .class file will be
Package mytags;
Import javax.servlet.jsp.*;
Import javax.servlet.jsp.tagtext.*;
Public class Helloworld implements Tag {
private PageContext pagecontext;
private Tag parent;
public int doStartTag() throws JSPException {
return SKIP_BODY;
}
public int doEndTag () throws JSPException {
try{
pageContext.getOut().write(“Hello World”);
} catch(java.io.Exception ex) {
throw new JSPException(“IO Exception”);
}
return EVAL_PAGE;
}
public void release (){}
public void setPageContext(pageContext p) {
pageContext=p;
}
public void setParent(Tag t) {
parent = t;
}
public void getParent() {
return parent;
}
}
Flow of programme:
Here in first .jsp file we are writing tag.But name and properties of this tag we are writing in .tld file. And whatever task that tag is going to perform is written in .class file which has been called by .tld file.
So by using taglib we can create our own defined tags.
Writing Servlet Filters
by Kief Morris kief@kief.com
Filters are an under-appreciated feature of the Java servlet platform, ideal for writing components that can be added transparently to any web application. A filter is like a lightweight servlet that doesn't generate its own content, instead it plugs into the request handling process and executes in addition to the normal page processing.
Filters might record information about requests, convert content to a different format, or even redirect access to a different page. Filters can be applied to any resources served by a servlet engine, whether it's flat HTML, graphics, a JSP page, servlet , or whatever. They can be added to an existing web application without either the filter or the application being aware of one another. Filters are essentially a server plug-in that works with any servlet container compliant with version 2.3 or later of the servlet specification.
A filter implements the interface javax.servlet.Filter, and configured in the web application web.xml file, where the URL's it will process are defined. For each request, the servlet container decides which filters to apply, and adds those filters to a chain in the same order they appear in web.xml. Each filter has its Filter.doFilter() method called, and triggers the invocation of the next filter in the chain or the loading of the final resource (HTML page, servlet, or whatever).
Writing a simple filter
To write a filter, we create a class implementing the Filter interface, which requires three methods: init(), doFilter(), and destroy(). init() and destroy() are called when the filter is first initialized and when it is destroyed, respectively, to allow configuration and cleanup. For the moment we'll ignore these and focus on doFilter(), which is the meat of the filter.
Filter.doFilter()
The servlet container calls the filter's doFilter() method and passes request and response objects for the current request. These are the same objects as a servlet gets, but since there is no HttpFilter, the parameters are defined as javax.servlet.ServletRequest and javax.servlet.ServletResponse, rather than the javax.servlet.http subclasses. This means that if you want to access methods available only on the HTTP versions of the request and response classes, you will need to cast the objects. To be a Good Programmer, you should first test that they actually are the HTTP versions, in case future generations want to use your filter in a non-HTTP servlet environment. Some of the code later in this article shows examples of this.
The third parameter to doFilter() is a FilterChain object, which is used to invoke the next filter in the chain. This is done by calling FilterChain.doFilter() and passing it the request and response objects. If the current filter is the last filter in the chain, the destination resource will be accessed, that is, the HTML page or other static file will be read in, or else a servlet or JSP page will be invoked. After FilterChain.doFilter() returns, the filter can do more processing if it chooses; at this point, the response object should have more fields populated, than it did beforehand, such as the content-type header having been set.
TimerFilter is a simple filter which does nothing more than time how long it takes to process the request after the filter, based directly on the Apache Foundation's Tomcat 4.0 server's ExampleFilter. If this filter is placed as the last filter in the chain, it times the servlet execution or page access itself. Here is the doFilter() method:
public final class TimerFilter implements Filter
{
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
long startTime = System.currentTimeMillis();
chain.doFilter(request, response);
long stopTime = System.currentTimeMillis();
System.out.println("Time to execute request: " + (stopTime - startTime) +
" milliseconds");
}
...
To compile a Filter you will need to link it with the servlet API classes, which include the interface definitions and other classes used by the filter. These classes are almost certainly available with your servlet container; typically named servlet.jar. If you download the sample source code for this article you can use Ant to compile the code; see the README.txt file for help on configuring the build.
Deploying a filter
To add a filter to a web application, you must first put the compiled filter class in the web application's classpath, which is normally done by putting it under WEB-INF/classes or in a jar file in WEB-INF/lib. The filter is then added to the WEB-INF/web.xml configuration file in much the same way a servlet is, in that there are two configuration blocks. The first defines the filter and gives it a name, and the second defines the circumstances in which the filter is invoked.
The
The filter class is defined with a
filter-name The name which will be used to identify the filter elsewhere in the web.xml file.
filter-class The classname, including package, of the filter. This name will be used by the servlet container to load the filter class.
init-param Initialization parameters to pass to the filter. We'll discuss these shortly.
description Long description for the filter, this may be used by configuration tools also.
icon Optional paths to image files for GUI configuration tools to use to represent the filter.
display-name Optional descriptive text for the filter, mainly useful for configuration tools.
The only required elements are the name and class; the icon and display-name are pointless unless you're using a tool which uses them. Here is the configuration for the TimerFilter.
This filter times the execution of the request after
the filter itself, and prints the execution time to
the standard output.
Note that the same filter class can be defined in multiple
XML and Webservices
• XML stands for EXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to carry data, not to display data
• XML tags are not predefined. You must define your own tags
• XML is designed to be self-descriptive
• XML was designed to transport and store data, with focus on what data is.
• HTML was designed to display data, with focus on how data looks.
What is an XML Element?
An XML element is everything from (including) the element's start tag to (including) the element's end tag.
An element can contain other elements, simple text or a mixture of both. Elements can also have attributes
Attributes provide additional information about elements.
XML Attributes Must be Quoted
Attribute values must always be enclosed in quotes, but either single or double quotes can be used. For a person's sex, the person tag can be written like this:
or like this:
XML Elements vs. Attributes
Take a look at these examples:
In the first example sex is an attribute. In the last, sex is an element. Both examples provide the same information.
There are no rules about when to use attributes and when to use elements. Attributes are handy in HTML. In XML my advice is to avoid them. Use elements instead
Avoid XML Attributes?
Some of the problems with using attributes are:
• attributes cannot contain multiple values (elements can)
• attributes cannot contain tree structures (elements can)
• attributes are not easily expandable (for future changes)
Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not relevant to the data.
With XSLT you can transform an XML document into HTML.
The XMLHttpRequest Object
With an XMLHttpRequest you can communicate with your server from inside a web page
What is the XMLHttpRequest Object?
The XMLHttpRequest object is the developer’s dream, because you can:
• Update a web page with new data without reloading the page
• Request and receive new data from a server after the page has loaded
• Communicate with a server in the background
Creating an XMLHttpRequest Object
Creating an XMLHttpRequest object is done with one single line of JavaScript.
In all modern browsers:
var xmlhttp=new XMLHttpRequest()
In older Microsoft browsers (IE 5 and 6):
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
In the next chapter, we will use the XMLHttpRequest object to retrieve XML information from a server.
The XMLHttpRequest object is supported in all modern browsers
XML Parser
Most browsers have a built-in XML parser to read and manipulate XML.
The parser converts XML into a JavaScript accessible object (the XML DOM).
________________________________________
XML Parser
The XML DOM contains methods (functions) to traverse XML trees, access, insert, and delete nodes.
However, before an XML document can be accessed and manipulated, it must be loaded into an XML DOM object.
An XML parser reads XML, and converts it into an XML DOM object that can be accessed with JavaScript.
Most browsers have a built-in XML parser.
________________________________________
Load an XML Document
The following JavaScript fragment loads an XML document ("books.xml"):
Example
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // Internet Explorer 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","books.xml",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;
XML DOM
________________________________________
The DOM (Document Object Model) defines a standard way for accessing and manipulating documents.
________________________________________
The XML DOM
The XML DOM (XML Document Object Model) defines a standard way for accessing and manipulating XML documents.
The DOM views XML documents as a tree-structure. All elements can be accessed through the DOM tree. Their content (text and attributes) can be modified or deleted, and new elements can be created. The elements, their text, and their attributes are all known as nodes.
In the examples below we use the following DOM reference to get the text from the
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue
• xmlDoc - the XML document created by the parser.
• getElementsByTagName("to")[0] - the first
• childNodes[0] - the first child of the
• nodeValue - the value of the node (the text itself)
You can learn more about the XML DOM in our XML DOM tutorial.
________________________________________
The HTML DOM
The HTML DOM (HTML Document Object Model) defines a standard way for accessing and manipulating HTML documents.
All HTML elements can be accessed through the HTML DOM.
In the examples below we use the following DOM reference to change the text of the HTML element where id="to":
document.getElementById("to").innerHTML=
• document - the HTML document
• getElementById("to") - the HTML element where id="to"
• innerHTML - the inner text of the HTML element
You can learn more about the HTML DOM in our HTML DOM tutorial.
________________________________________
Load an XML File - A Cross browser Example
The following code loads an XML document ("note.xml") into the XML parser:
Example
W3Schools Internal Note
To:
From:
Message:
XML Namespaces provide a method to avoid element name conflicts.
Solving the Name Conflict Using a Prefix
Uniform Resource Identifier (URI)
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.
The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. Another, not so common type of URI is the Universal Resource Name (URN).
All text in an XML document will be parsed by the parser.
But text inside a CDATA section will be ignored by the parser
PCDATA - Parsed Character Data
XML parsers normally parse all the text in an XML document.
CDATA - (Unparsed) Character Data
The term CDATA is used about text data that should not be parsed by the XML parser.
Characters like "<" and "&" are illegal in XML elements.
"<" will generate an error because the parser interprets it as the start of a new element.
"&" will generate an error because the parser interprets it as the start of an character entity.
Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA.
Everything inside a CDATA section is ignored by the parser.
A CDATA section starts with "":
In the example above, everything inside the CDATA section is ignored by the parser.
Notes on CDATA sections:
A CDATA section cannot contain the string "]]>". Nested CDATA sections are not allowed.
The "]]>" that marks the end of the CDATA section cannot contain spaces or line breaks.
Introduction to DTD
Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal elements and attributes.
A DTD can be declared inline inside an XML document, or as an external reference.
________________________________________
Internal DTD Declaration
If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the following syntax:
External DTD Declaration
If the DTD is declared in an external file, it should be wrapped in a DOCTYPE definition with the following syntax:
Why Use a DTD?
With a DTD, each of your XML files can carry a description of its own format.
With a DTD, independent groups of people can agree to use a standard DTD for interchanging data.
Your application can use a standard DTD to verify that the data you receive from the outside world is valid.
You can also use a DTD to verify your own data.
What is an XML Schema?
The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a DTD.
An XML Schema:
• defines elements that can appear in a document
• defines attributes that can appear in a document
• defines which elements are child elements
• defines the order of child elements
• defines the number of child elements
• defines whether an element is empty or can include text
• defines data types for elements and attributes
• defines default and fixed values for elements and attributes
________________________________________
XML Schemas are the Successors of DTDs
We think that very soon XML Schemas will be used in most Web applications as a replacement for DTDs. Here are some reasons:
• XML Schemas are extensible to future additions
• XML Schemas are richer and more powerful than DTDs
• XML Schemas are written in XML
• XML Schemas support data types
• XML Schemas support namespaces
What are Web Services?
• Web services are application components
• Web services communicate using open protocols
• Web services are self-contained and self-describing
• Web services can be discovered using UDDI
• Web services can be used by other applications
• XML is the basis for Web services
________________________________________
How Does it Work?
The basic Web services platform is XML + HTTP.
XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions.
The HTTP protocol is the most used Internet protocol.
Web services platform elements:
• SOAP (Simple Object Access Protocol)
• UDDI (Universal Description, Discovery and Integration)
• WSDL (Web Services Description Language)
We will explain these topics later in the tutorial.
Web Services have three basic platform elements: SOAP, WSDL and UDDI.
________________________________________
What is SOAP?
SOAP is an XML-based protocol to let applications exchange information over HTTP.
Or more simple: SOAP is a protocol for accessing a Web Service.
• SOAP stands for Simple Object Access Protocol
• SOAP is a communication protocol
• SOAP is a format for sending messages
• SOAP is designed to communicate via Internet
• SOAP is platform independent
• SOAP is language independent
• SOAP is based on XML
• SOAP is simple and extensible
• SOAP allows you to get around firewalls
• SOAP is a W3C standard
Read more about SOAP on our Home page.
________________________________________
What is WSDL?
WSDL is an XML-based language for locating and describing Web services.
• WSDL stands for Web Services Description Language
• WSDL is based on XML
• WSDL is used to describe Web services
• WSDL is used to locate Web services
• WSDL is a W3C standard
Read more about WSDL on our Home page.
________________________________________
What is UDDI?
UDDI is a directory service where companies can register and search for Web services.
• UDDI stands for Universal Description, Discovery and Integration
• UDDI is a directory for storing information about web services
• UDDI is a directory of web service interfaces described by WSDL
• UDDI communicates via SOAP
What is WSDL?
• WSDL stands for Web Services Description Language
• WSDL is written in XML
• WSDL is an XML document
• WSDL is used to describe Web services
• WSDL is also used to locate Web services
• WSDL is a W3C recommendation
________________________________________
WSDL Describes Web Services
WSDL stands for Web Services Description Language.
WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes.
A WSDL document is just a simple XML document.
It contains set of definitions to describe a web service.
________________________________________
The WSDL Document Structure
A WSDL document describes a web service using these major elements:
Element Defines
A WSDL document can also contain other elements, like extension elements, and a service element that makes it possible to group together the definitions of several web services in one single WSDL document.
________________________________________
WSDL Ports
The
It describes a web service, the operations that can be performed, and the messages that are involved.
The
________________________________________
WSDL Messages
The
Each message can consist of one or more parts. The parts can be compared to the parameters of a function call in a traditional programming language.
________________________________________
WSDL Types
The
For maximum platform neutrality, WSDL uses XML Schema syntax to define data types.
________________________________________
WSDL Bindings
The
A WSDL port describes the interfaces (legal operations) exposed by a web service.
________________________________________
WSDL Ports
The
It defines a web service, the operations that can be performed, and the messages that are involved.
The binding element has two attributes - name and type.
The name attribute (you can use any name you want) defines the name of the binding, and the type attribute points to the port for the binding, in this case the "glossaryTerms" port.
The soap:binding element has two attributes - style and transport.
The style attribute can be "rpc" or "document". In this case we use document. The transport attribute defines the SOAP protocol to use. In this case we use HTTP.
The operation element defines each operation that the port exposes.
For each operation the corresponding SOAP action has to be defined. You must also specify how the input and output are encoded. In this case we use "literal".
What is SOAP?
• SOAP stands for Simple Object Access Protocol
• SOAP is a communication protocol
• SOAP is for communication between applications
• SOAP is a format for sending messages
• SOAP communicates via Internet
• SOAP is platform independent
• SOAP is language independent
• SOAP is based on XML
• SOAP is simple and extensible
• SOAP allows you to get around firewalls
• SOAP is a W3C recommendation
________________________________________
Why SOAP?
It is important for application development to allow Internet communication between programs.
Today's applications communicate using Remote Procedure Calls (RPC) between objects like DCOM and CORBA, but HTTP was not designed for this. RPC represents a compatibility and security problem; firewalls and proxy servers will normally block this kind of traffic.
A better way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this.
SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.
________________________________________
XSL Languages
It Started with XSL
XSL stands for EXtensible Stylesheet Language.
The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML-based Stylesheet Language.
________________________________________
CSS = Style Sheets for HTML
HTML uses predefined tags, and the meaning of each tag is well understood.
The tag in HTML defines a table - and a browser knows how to display it.
Adding styles to HTML elements are simple. Telling a browser to display an element in a special font or color, is easy with CSS.
________________________________________
XSL = Style Sheets for XML
XML does not use predefined tags (we can use any tag-names we like), and therefore the meaning of each tag is not well understood.
A tag could mean an HTML table, a piece of furniture, or something else - and a browser does not know how to display it.
XSL describes how the XML document should be displayed!
________________________________________
XSL - More Than a Style Sheet Language
XSL consists of three parts:
• XSLT - a language for transforming XML documents
• XPath - a language for navigating in XML documents
• XSL-FO - a language for formatting XML documents
What is XSLT?
• XSLT stands for XSL Transformations
• XSLT is the most important part of XSL
• XSLT transforms an XML document into another XML document
• XSLT uses XPath to navigate in XML documents
• XHTML elements must be properly nested
• XHTML elements must always be closed
• XHTML elements must be in lowercase
• XHTML documents must have one root element
Some More XHTML Syntax Rules
• Attribute names must be in lower case
• Attribute values must be quoted
• Attribute minimization is forbidden
• The id attribute replaces the name attribute
• The XHTML DTD defines mandatory elements
AJAX
Asynchronous JavaScript and XML or Ajax for short is new web development technique used for the development of most interactive website. Ajax helps you in making your web application more interactive by retrieving small amount of data from web server and then showing it on your application. You can do all these things without refreshing your page.
Usually in all the web applications, the user enters the data into the form and then clicks on the submit button to submit the request to the server. Server processes the request and returns the view in new page ( by reloading the whole page). This process is inefficient, time consuming, and a little frustrating for you user if the only the small amount of data exchange is required. For example in an user registration form, this can be frustrating thing for the user, as whole page is reloaded only to check the availability of the user name. Ajax will help in making your application more interactive. With the help of Ajax you can tune your application to check the availability of the user name without refreshing the whole page.
Understanding the technology behind Ajax
Ajax is not a single technology, but it is a combination of many technologies. These technologies are supported by modern web browsers. Following are techniques used in the Ajax applications.
• JavaScript:
JavaScript is used to make a request to the web server. Once the response is returned by the webserver, more JavaScript can be used to update the current page. DHTML and CSS is used to show the output to the user. JavaScript is used very heavily to provide teh dynamic behavior to the application.
• Asynchronous Call to the Server:
Most of the Ajax application used the XMLHttpRequest object to send the request to the web server. These calls are Asynchronous and there is no need to wait for the response to come back. User can do the normal work without any problem.
• XML:
XML may be used to receive the data returned from the web server. JavaScript can be used to process the XML data returned from the web server easily.
How Ajax Works?
When user first visits the page, the Ajax engine is initialized and loaded. From that point of time user interacts with Ajax engine to interact with the web server. The Ajax engine operates asynchronously while sending the request to the server and receiving the response from server. Ajax life cycle within the web browser can be divided into following stages:
• User Visit to the page: User visits the URL by typing URL in browser or clicking a link from some other page.
• Initialization of Ajax engine:
When the page is initially loaded, the Ajax engine is also initialized. The Ajax engine can also be set to continuously refresh the page content without refreshing the whole page.
• Event Processing Loop:
* Browser event may instruct the Ajax engine to send request to server and receive the response data
* Server response - Ajax engine receives the response from the server. Then it calls the JavaScript call back functions
* Browser (View) update - JavaScript request call back functions is used to update the browser. DHTML and css is used to update the browser display.
Benefits of Ajax
Ajax is new very promising technology, which has become extremely popular these days. Here are the benefits of using Ajax:
• Ajax can be used for creating rich, web-based applications that look and works like a desktop application
• Ajax is easy to learn. Ajax is based on JavaScript and existing technologies like XML, CSS, DHTML. etc. So, its very easy to learn Ajax
• Ajax can be used to develop web applications that can update the page data continuously without refreshing the whole page
As the use of XML and web services is increasing day by day, it is good to connect an HTML page with XML, with the help of that we can get interim updates so easily without reloading the page. It is possible due to the XMLHttpRequest object, which is responsible for retrieving and submitting the XML data directly from the client side. It relies on Document Object Model (DOM) to convert the retrieved XML data into HTML.
Microsoft first implemented the XMLHttpRequest object in IE 5 for Windows as an ActiveX object. Afterward Mozilla and Apple's Safari also implemented in their own style.
XMLHttpRequest object facilitates the web developer a lot because with the help of this object you can update the page with new data without reloading the page, communicate with server in the background, request and receive data from the web server.
Creating an XMLHttpRequest object.
We can create an instance of the XMLHttpRequest in most of the modern popular browsers, and in the old versions of the browsers we need to create an object of ActiveXObject.
var xmlobj=new XMLHttpRequest ();
var activeobj=new ActiveXObject("Microsoft.XMLHTTP");
How to use an XMLHttpRequest Object and Handle the server response:
We need to create an XMLHttpRequest, after that we will use few important functions like:
1. onreadystatechange property: After submitting the request to the server, we need to store the response from the server. onreadystatechange property stores the response from the function which process the server.
2. readystate property: readystate property holds the state of the server response, every time readystate property change , onreadystatechange function executes. Possible values and their meaning are given below:
State The Request is:
0 Not initialized
1 Has been set up
2 Has been sent
3 In process
4 Is complete
3. responseText property: The data sent back from the server is stored and retrieved later with the help of responseText property.
AJAX XMLHttpRequest
« Previous
Next Chapter »
________________________________________
AJAX uses the XMLHttpRequest object
To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.
With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object.
With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.
________________________________________
The XMLHttpRequest object
By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded!
AJAX was made popular in 2005 by Google (with Google Suggest).
Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.
The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari).
AJAX Browser Support
« Previous
Next Chapter »
________________________________________
The keystone of AJAX is the XMLHttpRequest object
________________________________________
The XMLHttpRequest
All new browsers support a new built-in JavaScript XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).
This object can be used to request information (data) from a server.
Let's update our HTML file with a JavaScript in the section:
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML=xmlhttp.responseText;
}
Example explained
Try to create a XMLHttpRequest object:
xmlhttp=new XMLHttpRequest()
If not (if IE5 or IE6) create an ActiveXObject:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
Open the request object:
xmlhttp.open("GET",url,false)
Send your request to your server:
xmlhttp.send(null)
Update your page with the response from the server:
document.getElementById('test').innerHTML=xmlhttp.responseText
Note: The code above can be used every time you need to create an XMLHttpRequest object, so just copy and paste it whenever you need it.
In the next chapter you will learn more about the XMLHttpRequest.
________________________________________
All Together Now
Click to let AJAX change this text
AJAX - The XMLHttpRequest Object
« Previous
Next Chapter »
________________________________________
Important Methods and Properties of the XMLHttpRequest object.
________________________________________
Important Methods
The XMLHttpRequest object has 2 important methods:
The open() method
The send() method
________________________________________
Sending an AJAX Request to a Server
To send a request to a web server, we use the open() and send() methods.
The open() method takes three arguments. The first argument defines which method to use (GET or POST). The second argument specifies the name of the server resource (URL). The third argument specifies if the request should be handled asynchronously.
The send() method sends the request off to the server. If we assume that requested a file called "time.asp", the code would be:
url="time.asp"
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
In the example we assume that the current web page and the requested resource are both in the same file directory.
________________________________________
Important Properties
The XMLHttpRequest object has 3 important properties:
The responseText property
The readyState property
The onreadystatechange property
________________________________________
The responseText property
The XMLHttpRequest object stores any data retrieved from a server as a result of a server request in its responseText property.
In the previous chapter we copied the content of the responsText property into our HTML with the following statement:
document.getElementById('test').innerHTML=xmlhttp.responseText
________________________________________
XMLHttpRequest Open - Using False
In the examples (from the previous pages) we used this simplified syntax:
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML=xmlhttp.responseText;
The third parameter in the open call is "false". This tells the XMLHttpRequest object to wait until the server request is completed before next statement is executed.
For small applications and simple server request, this might be OK. But if the request takes a long time or cannot be served, this might cause your web application to hang or stop.
________________________________________
XMLHttpRequest Open - Using True
By changing the third parameter in the open call to "true", you tell the XMLHttpRequest object to continue the execution after the request to the server has been sent.
Because you cannot simply start using the response from the server request before you are sure the request has been completed, you need to set the onreadystatechange property of the XMLHttpRequest, to a function (or name of a function) to be executed after completion.
In this onreadystatechange function you must test the readyState property before you can use the result of the server call.
Simply change the code to:
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{document.getElementById('test').innerHTML=xmlhttp.responseText}
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
________________________________________
The readyState property
The readyState property holds the status of the server's response.
Possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
________________________________________
The onreadystatechange property
The onreadystatechange property stores a function (or the name of a function) to be called automatically each time the readyState property changes.
You can store a full function in the property like this:
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{document.getElementById('test').innerHTML=xmlhttp.responseText}
}
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
Or you can store the name of a function like this:
xmlhttp.onreadystatechange=state_Change()
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
...
...
...
function state_Change()
{
if(xmlhttp.readyState==4)
{document.getElementById('test').innerHTML=xmlhttp.responseText}
}
Asynchronous JavaScript Technology and XML (Ajax) With the Java Platform
Print-friendly Version
By Greg Murray, June 9, 2005; updated October 2006
Anyone who has used Flickr, GMail, Google Suggest, or Google Maps will realize that a new breed of dynamic web applications is emerging. These applications look and act very similar to traditional desktop applications without relying on plug-ins or browser-specific features. Web applications have traditionally been a set of HTML pages that must be reloaded to change any portion of the content. Technologies such as JavaScript programming language and cascading style sheets (CSS) have matured to the point where they can be used effectively to create very dynamic web applications that will work on all of the major browsers. This article will detail several techniques that you can use today to enable your web applications to be more rich and interactive like desktop applications.
Introducing Asynchronous JavaScript Technology and XML (Ajax)
Using JavaScript technology, an HTML page can asynchronously make calls to the server from which it was loaded and fetch content that may be formatted as XML documents, HTML content, plain text, or JavaScript Object Notation (JSON). The JavaScript technology may then use the content to update or modify the Document Object Model (DOM) of the HTML page. The term Asynchronous JavaScript Technology and XML (Ajax) has emerged recently to describe this interaction model.
Ajax is not new. These techniques have been available to developers targeting Internet Explorer on the Windows platform for many years. Until recently, the technology was known as web remoting or remote scripting. Web developers have also used a combination of plug-ins, Java applets, and hidden frames to emulate this interaction model for some time. What has changed recently is the inclusion of support for the XMLHttpRequest object in the JavaScript runtimes of the mainstream browsers. The real magic is the result of the JavaScript technology's XMLHttpRequest object. Although this object is not specified in the formal JavaScript technology specification, all of today's mainstream browsers support it. The subtle differences with the JavaScript technology and CSS support among current generation browsers such as Mozilla Firefox, Internet Explorer, and Safari are manageable. JavaScript libraries such as Dojo, Prototype, and the Yahoo User Interface Library have emerged to fill in where the browsers are not as manageable and to provide a standardized programming model. Dojo, for example, is addressing accessibility, internationalization, and advanced graphics across browsers -- all of which had been thorns in the side of earlier adopters of Ajax. More updates are sure to occur as the need arises.
What makes Ajax-based clients unique is that the client contains page-specific control logic embedded as JavaScript technology. The page interacts with the JavaScript technology based on events such as the loading of a document, a mouse click, focus changes, or even a timer. Ajax interactions allow for a clear separation of presentation logic from the data. An HTML page can pull in bite-size pieces to be displayed. Ajax will require a different server-side architecture to support this interaction model. Traditionally, server-side web applications have focused on generating HTML documents for every client event resulting in a call to the server. The clients would then refresh and re-render the complete HTML page for each response. Rich web applications focus on a client fetching an HTML document that acts as a template or container into which to inject content, based on client events using XML data retrieved from a server-side component.
Some uses for Ajax interactions are the following:
Real-time form data validation: Form data such as user IDs, serial numbers, postal codes, or even special coupon codes that require server-side validation can be validated in a form before the user submits a form. See Realtime Form Validation for details.
Autocompletion: A specific portion of form data such as an email address, name, or city name may be autocompleted as the user types.
Load on demand: Based on a client event, an HTML page can fetch more data in the background, allowing the browser to load pages more quickly.
Sophisticated user interface controls and effects: Controls such as trees, menus, data tables, rich text editors, calendars, and progress bars allow for better user interaction and interaction with HTML pages, generally without requiring the user to reload the page.
Refreshing data and server push: HTML pages may poll data from a server for up-to-date data such as scores, stock quotes, weather, or application-specific data. A client may use Ajax techniques to get a set of current data without reloading a full page. Polling is not the most effecient means of ensuring that data on a page is the most current. Emerging techniques such as Comet are being developed to provide true server-side push over HTTP by keeping a persistent connection between the client and server. See this blog entry on Comet using Grizzly for more on the development of server push with Java technology.
Partial submit: An HTML page can submit form data as needed without requiring a full page refresh.
Mashups: An HTML page can obtain data using a server-side proxy or by including an external script to mix external data with your application's or your service's data. For example, you can mix content or data from a third-party application such as Google Maps with your own application.
Page as an application: Ajax techniques can be made to create single-page applications that look and feel much like a desktop application. See the article on the use of Ajax and portlets for more on how you can use portlet applications today.
Though not all-inclusive, this list shows that Ajax interactions allow web applications to do much more than they have done in the past.
The Anatomy of an Ajax Interaction
Now that we have discussed what Ajax is and what some higher-level issues are, let's put all the pieces together and look at an Ajax-enabled Java application.
Let's consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the Ajax interaction that will provide the validation logic.
Figure 1: An Ajax Interaction Provides Validation Logic
The following items represent the setups of an Ajax interaction as they appear in Figure 1.
1. A client event occurs.
2. An XMLHttpRequest object is created and configured.
3. The XMLHttpRequest object makes a call.
4. The request is processed by the ValidateServlet.
5. The ValidateServlet returns an XML document containing the result.
6. The XMLHttpRequest object calls the callback() function and processes the result.
7. The HTML DOM is updated.
Now let's look at each step of the Ajax interaction in more detail.
1. A client event occurs.
JavaScript technology functions are called as the result of an event. In this case, the function validate() may be mapped to a onkeyup event on a link or form component.
size="20"
id="userid"
name="id"
onkeyup="validate();">
This form element will call the validate() function each time the user presses a key in the form field.
2. A XMLHttpRequest object is created and configured.
An XMLHttpRequest object is created and configured.
var req;
function validate() {
var idField = document.getElementById("userid");
var url = "validate?id=" + encodeURIComponent(idField.value);
if (typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("GET", url, true);
req.onreadystatechange = callback;
req.send(null);
}
The validate() function creates an XMLHttpRequest object and calls the open function on the object. The open function requires three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously. The API is XMLHttpRequest.open(String method, String URL, boolean asynchronous). If an interaction is set as asynchronous (true) a callback function must be specified. The callback function for this interaction is set with the statement req.onreadystatechange = callback;. See section 6 for more details.
3. The XMLHttpRequest object makes a call.
When the statement req.send(null); is reached, the call will be made. In the case of an HTTP GET, this content may be null or left blank. When this function is called on the XMLHttpRequest object, the call to the URL that was set during the configuration of the object is called. In the case of this example, the data that is posted (id) is included as a URL parameter.
Use an HTTP GET when the request is idempotent, meaning that two duplicate requests will return the same results. When using the HTTP GET method, the length of URL, including escaped URL parameters, is limited by some browsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will affect the server-side application state. An HTTP POST requires a Content-Type header to be set on the XMLHttpRequest object by using the following statement:
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("id=" + encodeURIComponent(idTextField.value));
When sending form values from JavaScript technology, you should take into consideration the encoding of the field values. JavaScript technology includes an encodeURIComponent() function that should be used to ensure that localized content is encoded properly and that special characters are encoded correctly to be passed in an HTTP request.
4. The request is processed by the ValidateServlet.
A servlet mapped to the URI "validate" checks whether the user ID is in the user database.
A servlet processes an XMLHttpRequest just as it would any other HTTP request. The following example show a server extracting the id parameter from the request and validating whether the parameter has been taken.
public class ValidateServlet extends HttpServlet {
private ServletContext context;
private HashMap users = new HashMap();
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.context = config.getServletContext();
users.put("greg","account data");
users.put("duke","account data");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !users.containsKey(targetId.trim())) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("
}
}
}
In this example, a simple HashMap is used to contain the users. In the case of this example, let us assume that the user typed duke as the ID.
5. The ValidateServlet returns an XML document containing the results.
The user ID duke is present in the list of user IDs in the users HashMap. The ValidateServlet will write an XML document to the response containing a message element with the value of invalid. More complex usecases may require DOM, XSLT, or other APIs to generate the response.
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("
The developer must be aware of two things. First, the Content-Type must be set to text/xml. Second, the Cache-Control must be set to no-cache. The XMLHttpRequest object will process only requests that are of the Content-Type of only text/xml, and setting Cache-Control to no- cache will keep browsers from locally caching responses for cases in which duplicate requests for the same URL (including URL parameters) may return different responses.
6. The XMLHttpRequest object calls the callback() function and processes the result.
The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction.
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
// update the HTML DOM based on whether or not message is valid
}
}
}
Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded.
Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now let's look at how to use the DOM APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet.
valid
This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user:
function parseMessage() {
var message = req.responseXML.getElementsByTagName("message")[0];
setMessage(message.childNodes[0].nodeValue);
}
The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.
7. The HTML DOM is updated.
JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById("userIdMessage"), where "userIdMessage" is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements.
One common means to change the body content of an element is to set the innerHTML property on the element as in the following example.
The portions of the HTML page that were affected are re-rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as Popular Posts
L N Mishra s Blog
Labels
Facebook Badge
Followers