Saturday, October 8, 2011

MyEclipse Shortcuts

Navigational Shortcuts
F10 Main menu
Shift F10 Context menu
Ctrl F10 View menu
   
Workspace navigation
F12 Activate editor
Ctrl+Shift+W Switch editor
Ctrl F6 Next editor
Ctrl Shift F6 Prev editor
Ctrl F7 Next workspace
Ctrl Shift F7 Prev workspace
Ctrl F8 Next perspective
Ctrl Shift F8 Prev perspective
Alt Left Back
Alt Right Forward
   
Files
Alt Shift S Show in…
Ctrl Shift R Jump to file
Ctrl N New file
Ctrl S Save file
Ctrl Shift S Save all files
Ctrl F4 Close file
Ctrl Shift F4 Close all files
   
Find
Ctrl L Goto line
Ctrl F Find
Ctrl J Incremental find
Ctrl Shift J Incremental find prev
Ctrl K Find next
Ctrl Shift K Find prev
Ctrl H Search workspace
Ctrl (dot) Navigate next
Ctrl (comma) Navigate prev
   
Java navigation
F3 Goto declaration
Ctrl Shift U Find references in file
Ctrl Shift G Find references in workspace
Ctrl G Find declarations in workspace
Ctrl Shift P Navigate to matching bracket/brace
Ctrl T Popup type hierarchy
Ctrl Shift T Open Type
Ctrl O Outline of current source
Ctrl F3 Outline of current cursor position
Ctrl Shift Arrow Jump beetween methods up or down
F2 Show Javadoc
F4 Show hierarchy
Ctrl Alt H Open call hierarchy
   
   
General editing
Alt Arrow Move line(s) up or down
Alt Shift Up Expand selection to enclosing element
Alt Shift Right Expand selection to next element
Alt Shift Left Expand selection to previous element
Alt Shift Down Restore previous selection
Ctrl Alt Arrow Duplicate line(s) up or down
Shift Enter Insert line below
Ctrl Shift Enter Insert line above
Ctrl D Delete line
Ctrl Shift Q Toggle Quick Diff
Ctrl Shift Y Convert to lowercase
Ctrl Shift X Convert to uppercase
   
Java editing
Alt Shift U Remove occurrence annotations
Ctrl 1 Quick fix (works even when there are no errors
Ctrl Shift M Add import
Ctrl Shift F Reformat
Ctrl Shift O Organize Imports
Ctrl / Comment
Ctrl \ UnComment
Ctrl Shift Space Parameter hints
Ctrl Hyperlink identifier
Ctrl I Correct indentation
Shift Space Incremental content assist
   
Debugger
F5 Step into
F6 Step over
F7 Run to return
F8 Resume
F9 Relaunch last
F11 Run/debug last
Ctrl F11 Run
Ctrl Shift B Toggle breakpoint
Ctrl D Display
Ctrl Q Inspect
Ctrl R Run to line
Ctrl U Run snippet
   
Refactoring
Alt T Refactoring menu
Ctrl Shift Z Undo refactor
Ctrl Shift Y Redo refactor
Alt Shift R Rename
Alt Shift V Move
Alt Shift I Inline
Alt Shift M Extract method
Alt Shift L Extract local
Alt Shift C Change method signature
   
Misc
F5 Refresh
F1 Infopop
F2 Show resizeable hover

MyEclipse JSF Tutorial

Outline




 

1. Preface

This document was written using MyEclipse. However, if you notice discrepancies between this document and the version of MyEclipse you are using to perform the install that make it difficult or impossible to follow this guide, please see the User Feedback section on how to

 

2. Introduction

In this tutorial we will be walking through a small JSF demo application using MyEclipse. Previous knowledge of JSF and/or MyEclipse is not necessary, but would be helpful.

Since Struts is such a prevalent web application framework, similarities between JSF and Struts will be noted, wherever appropriate, to help the reader with previous Struts experience. However, if you have no prior experience with Struts, you may feel free to skip those sections.

3. Requirements

Below is a list of software used by this guide:
  • MyEclipse (download available here)
  • For this demo the User Name is "myeclipse" and the Password is "myeclipse" as well.

4.  New Project Setup & Structure 

To organize our development artifacts, we will need to create a new Web Module Project in MyEclipse that has JSF Capabilities added to it.  You can create a web project by selecting Web Project from the new toolbar menu:

Figure 4.1: Create a new web project

Figure 4.2: Web Project Wizard Dialog
The wizard will allow you to customize your project settings by entering your preferences into the dialog fields, as demonstrated in Figure 4.2.
NoteIt is popular when developing JSF applications to also use the JSTL libraries, so selecting add "JSTL Libraries" during project creation is recommended.  However, it is also possible to add the JSTL libraries later, via the "Add JSTL Libraries" item from the MyEclipse context menu.
Once the Web Project is created, we need to add JSF Capabilities to it. This is done by right clicking on the root of our project in the Package Explorer View, and selecting MyEclipse > Add JSF Capabilities, as shown in Figure 4.3.

Figure 4.3: Adding JSF Capabilities to a Web Project
The default values for the JSF dialog are fine for the purposes of this tutorial.  Advanced users may perform additional configuration by changing the default settings in the dialog, as shown in Figure 4.4.

Figure 4.4: Configuring JSF Capabilities
After the wizard completes, the project structure will look like what is shown in Figure 4.5.

Figure 4.5: Project Layout After Configuration
Now that the project has been created, we can start editing and creating our application.

5. Creating the Message Bundle

Let's start off our new application with the creation of the MessageBundle file. This is a simple property file that stores all our messages along with their associated keys.  Then the bundle can be used in any of our JSP pages to allow our application to be easily internationalized.  As an analogy, Struts provided similar support in this area by using the ApplicationResources.properties file,  the various <bean /> tags, and the message bundle attributes that the bean tags accepted.

In JSF, we can load a message bundle into a page with the line:
<f:loadBundle basename="com.jsfdemo.MessageBundle" var= "bundle"/>

Note: This line of code creates a page-scoped message bundle that we can reference later in the page via the 'bundle' variable name, use to lookup messages keys, and return the associated message value.

Before creating the message bundle file, create a  com.jsfdemo package in the source folder by right-clicking it and selecting New > Package.   To create the message bundle file, we'll use the New File Wizard that is accessed from the context menu of the project by right-clicking on the project's 'source' folder and selecting New > File.
The new file is opened in the MyEclipse Properties Editor.
After successfully creating the new message bundle file, we need to fill the file with key/value pairs for each label or text string that we want to display in the JSP page. Add the contents from Figure 5.2 by clicking on the Add button, provide values for Name and Value in the Add Property dialog and click Finish.
MessageBundle.properties
user_name_label=User Name:
user_password_label=Password:
login_button_label=Login

Figure 5.1: Contents of MessageBundle.properties
After adding the properties, the MessageBundle.properties file will look like the one shown in Figure:5.2


Figure 5.2: MessageBundle.properties
file
When specifying the file location, select Browse..., choose the directory /JSFLoginDemo/src/com/jsfdemo, name the file MessageBundle.properties, and select Finish.
Now that we have the MessageBundle complete, in the next section we will create the ManagedBean now that will handle our user logging in.

6. Creating the Managed Beans

In this section we'll see how to create the ManagedBean that will perform the login operation when prompted by the login JSP page as well as store the user name and password entered by the user. For the purpose of this demo, the login operation simply checks if the username and password are both "myeclipse"  and then redirects the user to the userLoginSuccess.jsp page.  Otherwise it sends them back to the login page.
First open up the faces-config.xml file with the MyEclipse JSF Editor:

Figure 6.1: Opening faces-config.xml file for editing
Open Tree page and select Managed Beans node on the tree. Press Add... to open new managed bean wizard. Figure 6.2:

Figure 6.2: Launch the managed bean wizard
You will then be presented with the new Managed Bean wizard;  Fill out the values as shown in Figures 6.3 below:

Figure 6.3: Setup the new managed bean
Press "Add..." next to managed properties list to add a new property:

Figure 6.4: Managed bean editor
Fill managed property wizard as described below to create a password property:

Figure 6.5: Managed bean property wizard
Repeat for userName property.
You will now notice that the new UserBean was added to the Outline View as shown in Figure 6.6:

Figure 6.6: UserBean now shown in the Outline View
Open UserBean.java source file will also be opened in the java editor:

Figure 6.7: UserBean Java source opened up in an editor
Notice that the getters and setters for our two properties (username and password) were already generated for us, so the only thing we need to add to this class is the implementation of the loginUser method that will be called to process the user login.
The code snippet for the loginUser method is in Figure 6.8 below.  Please copy and paste it into your file, adding any new imports as necessary:
UserBean.java
    public String loginUser() {
        if("myeclipse".equals(getUserName()) && "myeclipse".equals(getPassword()))
            return "success";
       
        FacesContext facesContext = FacesContext.getCurrentInstance();
        FacesMessage facesMessage = new FacesMessage(
            "You have entered an invalid user name and/or password");
        facesContext.addMessage("loginForm", facesMessage);
       
        return "failure";
    }
Figure 6.8: loginUser code for the new UserBean.java file

Looking at the bean code, we can notice some unique properties about it. For example, the UserBean class doesn't extend or implement any classes or interfaces tied to JSF. It is simply a javabean that includes the additional logic to perform a useful operation.  In Struts terms, it contains all the functionality of a Struts Form and a Struts Action, conveniently located in one class.

Another thing to note is that unlike Struts, these methods do not return special classes, like an ActionForward, because navigation is specified externally in a declarative fashion in the faces-config.xml deployment descriptor.  And, in Section 8 we will show how this descriptor is created and configured.

7. Creating the JSP Pages

In this section we are going to focus on creating the JSP pages for our example JSF application, which will mimic a simple website login screen.  As a result, we will only need 2 JSP pages, one to prompt the user to login and the other to indicate that login was successful.  We will call these pages loginUser.jsp and loginUserSuccess.jsp, respectively. For simplicity, if there is an authorization error during the login attempt, we will redirect the user back to the loginUser.jsp page.  To avoid confusion, we are not using any validation in this demo, but you can easily add validators to the two inputText/Secret JSF components.  We will use these fields to validate the user's entry for length and additionally display an error message if the login was incorrect.
MyEclipse also provides tools that make it simple to create the web pages for our JSF application by editing the faces-config.xml file in the MyEclipse JSF Editor. So make sure that file is still open and we can get started creating our userLogin.jsp page.
To create our userLogin.jsp page we are going to first click the JSP button, then click on our canvas.  When the new JSP wizard comes up, type in the File Name and select the JSF template as shown in Figure 7.1:

Figure 7.1: Creating userLogin.jsp using the faces-config.xml editor

We can also create our userLoginSuccess.jsp now in the same manner:

Figure 7.2: Creating userLoginSuccess.jsp using the faces-config.xml editor

Let's start working on our application now by opening up the userLogin.jsp page:

Figure 7.3: Begin editing the userLogin.jsp page
Now, what we need to do now on this page is:
  • Add an h:inputText component for the user name
  • Add an h:inputSecret component for the password
  • Add an h:outputLabel for the user name inputText
  • Add an h:outputLabel for the password
First thing we need to do is remove the default template text as well as type in our bundle basename so our page can use our MessageBundle.  We will end up with JSP that looks like Figure 7.4:

Figure 7.4: Remove template text and add our MessageBundle to the JSP page

Figure 7.4a: Create the new form
In Figure 7.4a we create the new HTML form element that will contain our login controls. Now we need to actually create the input text boxes!
Now let's create our h:inputText component for the user name, this is shown in Figures 7.6 and 7.7:

Figure 7.6: Adding new inputText component


Figure 7.7: Adding new inputText component continued
Now let's add our h:inputSecret component (no labels yet):

Figure 7.8 Adding new inputSecret component

Figure 7.9 Adding new inputSecret component continued
Now let's add the outputLabel's for both of our input components, starting with our userLabel:


Figure 7.10: Adding outputLabel component to our userName component
We will also need to add a label for our h:inputSecret component in the same manner. After we are done, as mentioned above, let's manually change our h:outputLabel components to wrap h:outputText components that are bound to our MessageBundle so we can see them in the designer, it will look something like this:

Figure 7.11: Adding outputText components to our labels
Be sure to make the modification to both the userName label and password label.
Now it is time to add our login button, we will do that almost identically to how we have added the other components so far, as shown in Figures 7.12 and 7.13:

Figure 7.12: Adding a new commandButton component

Figure 7.13: Adding a new commandButton component continued
Now we have a page that looks something like this:

Figure 7.14: Our almost-complete userLogin.jsp page
You might notice that everything looks pretty ugly on 1 line, so let's add some space to put things on separate lines:

Figure 7.15: Nicely laid out userLogin.jsp page

Now that our userLogin.jsp page is done, let's quickly do our userLoginSuccess.jsp page which is much simpler. Open that file up and edit it, simply adding a line to print out the name of the user that logged in as shown in Figure 7.16:

Figure 7.16: Making userLoginSuccess.jsp page print out the user's name
Now that we have created our two pages, the only thing left for us to do is hook them together with proper Navigation Cases, that is done by visual editing our faces-config.xml file, so open that file. After the file is open for editing, perform the following steps to create the navigation case: 
  1. Click the Navigation Case tool
  2. Click your userLogin.jsp file
  3. Then click on your userLoginSuccess.jsp file
  4. You will be prompted with a wizard to create the navigation case.
Follow Figures 7.17 and 7.18 for creating the success navigation case. In order to create the failure navigation case, we simply do the same steps as before but click twice on the userLogin.jsp file, in order to create a circular navigation case.


Figure 7.17: Creating the success navigation case

Figure 7.18: Creating the success navigation case continued
After we have created both navigation cases, our file will look something like this:

Figure 7.19: Reviewing navigation cases for our app
Now that we have created all our JSP pages and added our Navigation Cases correctly, the only thing left is to run our application!

8. Running the Application

In this section we will quickly show what our new application looks like when its running.

Select your project in the Package Explorer. Expand Run... dropdown. In the Run As menu select MyEclipse Server Application.

Figure 8.1: Run your project as server application
The output from the server log will be redirected to the Eclipse Console View.  From the log shown in Figure 8.2, it is evident that the sever started successfully.

Figure 8.2: Tomcat Startup Log
Once Tomcat is running,  we can test it by opening the MyEclipse Browser View.  This can be done by clicking the Browser button as shown in Figure 8.3.

Figure 8.3: Opening the Web Browser View
 In the browser's address bar, enter http://localhost:8080/JSFLoginDemo/userLogin.faces to activate the example application, as shown in Figure 8.7.
NOTE : The reason the URL ends in .faces and not .jsp is because above, we mapped our FacesServlet to the *.faces extension, that means in order for JSF to be given a chance to process the request and build out the component tree, we must use the .faces extension to access the actual pages. If you don't, you will get an exception along the lines of "FacesContext cannot be found".

Figure 8.4: Accessing the Example Application
Now type in myeclipse for the user name and password and click Login to see your app in action!

Figure 8.5: Logging in...

Figure 8.6: Successful Login
We see our navigation rules kick in as we are validated and directed to the userLoginSuccess.jsp page where our name is displayed. While this application is certainly simple, it does convey the basics of developing a JSF application using MyEclipse.

Building Web Application With Ant and Deploying on Jboss 3.0

Building Web Application With Ant and Deploying on Jboss 3.0 Building Web Application With Ant and Deploying on Jboss 3.0 Previous Tutorial Index Next In this lesson I will show you how to build you web application and install on the Jboss 3.0

Building Web Application With Ant and Deploying on Jboss 3.0

     
In this lesson I will show you how to build you web application and install on the Jboss 3.0 application server.
After the completion of the lesson you will be able to include jsp, html and servlets in the ear file and deploy on the Jboss 3.0 application server. This example will provide a strong foundation for the further development. Ant script developed in this lesson will be used in subsequent tutorial for the development and deployment of complex J2EE Applications with little or no more modification.
In this lesson we will write one Hello World Servlet and a JSP file file to call Hello World Servlet. In order to deploy components we have to build .ear file which is the standard format for the deployment of J2EE application.
First of all let's understand the structure of .ear and .war files.
Enterprise Archive Contents
Enterprise Archive (.ear) component follows the standard directory structure defined in the J2EE specification. 
Directory Structure of .ear archive
 /
  .war and .jar files
  Meta-inf
      application.xml
    
In the .ear file .war,.jar and application.xml file are packaged in the above format.
Enterprise Archive Contents
Web component follows the standard directory structure defined in the J2EE specification. 
Directory Structure of Web Component
 /
   index.htm, JSP, Images etc..
  Web-inf
   web.xml
   classes
     servlet classes
   lib
     jar files
    
Root directory of the web archive ('.war' file) contains all the html, jsp, images files and the additional directories containing these files. In the root directory there is a special directory 'Web-inf' which contains the web deployment descriptor (web.xml), classes and the lib directory.  
Directory Structure of Example2 directory
After understanding the structure of .ear and .war file let's look at the directory structure of example2 directory where we have work to develop the deployable .ear file.
Directory structure:

Description of Directory and its content:
Directory Description
example2 Base directory which contains build.xml and the .ear file generated by Ant utility will be placed here.
build Various files generated by Ant utility will be placed in different directories under this directory. 
build/deploymentdesciptors Web.xml and application.xml files are placed in this directory.
build/ear Intermediate files for the assembling of example2.ear ear file are placed here.
build/jar Any jar file if required will be placed in this directory.
build/war Intermediate files for the assembling of example2.war ear file are placed here.
build/src All the compiled .class files are placed in this directory.
src All the java source files are placed here.
web All the html,jsp, images etc. files are placed in this directory.
In this lesson we creating HelloWorld.java and index.jsp which is in the /src and /web directory respectively.
Source code of HelloWorld.java:
/* * HelloWorld.java
*
*/
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* The Hello World Servelet.
*
* @author Deepak Kumar
* http://www.roseindia.net
* deepak@roseindia.net
*/
public class HelloWorld extends HttpServlet {

public void service(HttpServletRequest request,
HttpServletResponse response) throws  IOException, ServletException{
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head>");
  out.println("<title>Hello World Servlet!</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<p align=\"center\"><font size=\"5\" color=\"#000080\">Hello World!</font></p>");
  out.println("<p align=\"center\"><a href=\"javascript:history.back()\">Go to Home</a></p>");
  out.println("</body>");
  out.println("</html>");
   }
}
    
Here is the code of index.jsp file:
 <%@page language="java" %>
<html>

<head>
<title>Welcome to Jboss 3.0 tutorial</title>
</head>

<body bgcolor="#FFFFCC">

<p align="center"><font size="6" color="#800000">Welcome to<br>
Jboss 3.0 Tutorial</font></p>
<p align="center"><font color="#000080" size="4">Congralutations you have successfully
installed lesson 2 tutorial</font></p>
<p align="center"><font color="#000080" size="4"><a href="servlet/HelloWorld">Click here
to</a> execute Hello World Servlet.</font></p>
<p><font size="4">&nbsp;</font></p>
<p align="center"><font color="#000080"><font size="4">For more tutorials and examples visit
</font> </font><font size="4"><a href="http://www.rosindia.net"><font color="#000080">http://www.rosindia.net</font></a></font></p>
<p align="center"><font size="4">&nbsp;</font></p>
<p align="center"><font color="#000080">Copyright © 2001 roseindia.net. All
rights reserved.</font></p>

</body>

</html>

    
You can download all the file of this tutorial from here.
Writing Application and Web deployment descriptor
Since in this lesson we are developing one servlet and one jsp files so our deployment descriptor is very simple.
web.xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
<servlet>
   <servlet-name>HelloWorld</servlet-name>
  <servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
  <url-pattern>/servlet/HelloWorld</url-pattern>
  <servlet-name>HelloWorld</servlet-name>
</servlet-mapping>

</web-app>


    
application.xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>

<application>
<display-name>Example 2 </display-name>
<module>
<web>
<web-uri>example2.war</web-uri>
<context-root>/example2</context-root>
</web>
</module>
</application>

    
Above application.xml file describe the content of example2.ear. Tag <web-uri>example2.war</web-uri> describe the name of web module (i.e.. example2.war) packaged in the archive. The context root of this example2.ear is eample2.
Writing Ant build xml file
To build example2.ear file, I have written build.xml which compiles source code and builds deployable archive file.
build.xml file:
 <?xml version="1.0"?>
<!-- ==================================================== -->
<!-- Build file for our first web application -->
<!-- build.xml, Sunday, July 07, 2002 -->
<!-- Author: Deepak Kumar -->
<!-- Email : deepak@roseindia.net -->
<!-- Url : http://www.roseindia.net -->
<!-- ==================================================== -->


<project name="Jboss 3.0 tutorial series" default="all" basedir=".">


<target name="init">
<property name="dirs.base" value="${basedir}"/>
<property name="classdir" value="${dirs.base}/build/src"/>
<property name="src" value="${dirs.base}/src"/>
<property name="web" value="${dirs.base}/web"/>
<property name="deploymentdescription" value="${dirs.base}/build/deploymentdescriptors"/>

<property name="warFile" value="example2.war"/>
<property name="earFile" value="example2.ear"/>


<property name="earDir" value="${dirs.base}/build/ear"/>
<property name="warDir" value="${dirs.base}/build/war"/>


<!-- Create Web-inf and classes directories -->
<mkdir dir="${warDir}/WEB-INF"/>
<mkdir dir="${warDir}/WEB-INF/classes"/>

<!-- Create Meta-inf and classes directories -->
<mkdir dir="${earDir}/META-INF"/>

</target>

<!-- Main target -->
<target name="all" depends="init,build,buildWar,buildEar"/>


<!-- Compile Java Files and store in /build/src directory -->
<target name="build" >
<javac srcdir="${src}" destdir="${classdir}" debug="true" includes="**/*.java" />
</target>

<!-- Create the War File -->
<target name="buildWar" depends="init">
<copy todir="${warDir}/WEB-INF/classes">
<fileset dir="${classdir}" includes="**/*.class" />
</copy>

<copy todir="${warDir}/WEB-INF">
<fileset dir="${deploymentdescription}" includes="web.xml" />
</copy>

<copy todir="${warDir}">
<fileset dir="${web}" includes="**/*.*" />
</copy>

<!-- Create war file and place in ear directory -->
<jar jarfile="${earDir}/${warFile}" basedir="${warDir}" />


</target>


<!-- Create the War File -->
<target name="buildEar" depends="init">
<copy todir="${earDir}/META-INF">
<fileset dir="${deploymentdescription}" includes="application.xml" />
</copy>

<!-- Create ear file and place in ear directory -->
<jar jarfile="${dirs.base}/${earFile}" basedir="${earDir}" />
</target>

</project>

 
Above build.xml file is design to create example2.ear for us in the base directory.
Running Ant utility to build example2.ear
Now it's time to build example2.ear and deploy on the Jboss 3.0 application server.
To execute Ant utility go to c:\anttest\example2 directory and issue ant command.
Out put of ant command:
C:\anttest\example2>ant
Buildfile: build.xml

init:
[mkdir] Created dir: C:\anttest\example2\build\war\WEB-INF
[mkdir] Created dir: C:\anttest\example2\build\war\WEB-INF\classes
[mkdir] Created dir: C:\anttest\example2\build\ear\META-INF

build:
[javac] Compiling 1 source file to C:\anttest\example2\build\src

buildWar:
[copy] Copying 1 file to C:\anttest\example2\build\war\WEB-INF\classes
[copy] Copying 1 file to C:\anttest\example2\build\war\WEB-INF
[copy] Copying 1 file to C:\anttest\example2\build\war
[jar] Building jar: C:\anttest\example2\build\ear\example2.war

buildEar:
[copy] Copying 1 file to C:\anttest\example2\build\ear\META-INF
[jar] Building jar: C:\anttest\example2\example2.ear

all:

BUILD SUCCESSFUL

Total time: 8 seconds
C:\anttest\example2>|
The above process will create example2.ear in c:\anttest\example2 directory.
Deploying and testing J2EE application
Statrt Jboss 3.0 and copy example2.ear file into the JBOSS_HOME/server/default/deploy directory. Jboss application server automatically deploys the application. Open web browse and type http://localhost:8080/example2 in the web browser. Browse should show the screen something like this:

Also try to execute Hello World Servlet by clicking "Click Here to" link on the index.jsp in the browser.
In this lesson you learned how to write build.xml file to automate the process of .ear file creation. Ant utility with help of our build.xml file automatically compiles source code and assembles J2EE application for us. Ant utility is very power full and it reduces the development time significantly.

Configure web logic server in myeclipse



Image

Download & Configure Oracle OC4J Server for Netbeans IDE

Are you using Oracle OC4J server? If you're, did you think about using the Netbeans IDE (Integrated Development Environment)?

Download OC4J from the Netbeans updates
Open Netbeans IDE and then follow below steps to configure the OC4J server.
1. Tools > Update Center
2. Select "Netbeans Update Center Beta"
3. Select OC4J 10g

You can then configure a new server and run/stop the server from your IDE.

You can get more info from official website for Netbeans OC4J module @ Netbeans OC4J module.

Java program to fetch and sort files from a directory

Hi - Have you worked with Java file system objects? It has very good features like accessing files and sorting them in ascending order and descending order. In Java 1.5, Sun Microsystem has introduced the Comparator class to make the sort operations easier. So, I'm going to discuss about this today.

When you create a File object, it will just create a reference for the path that you've given for the constructor. You can invoke methods like exists() to find whether the file exists or isDirectory() to find whether this file represents a directory on the disk etc.

Here is the sample program to to access files and order them by ascending order based on name, last modified date, and size. It explains about file filter as well.

SortFiles.java
package filesdemo;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;

/**
 * A demo class to show the file sorting techniques.
 * @author Santhosh Reddy Mandadi
 * @since 05-Mar-2010
 * @version 1.0
 */
public class SortFiles
{
  public static void main(String[] args)
  {
    File dir = new File("C:\\");
    if(dir.isDirectory())
    {
      // Fetching the list from the directory
      File[] files = dir.listFiles();

      //Prints all the files and folders exists under dir
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("All the files including folders");
      System.out.println("--------------------------------");
      
      // Creating a filter to return only files.
      FileFilter fileFilter = new FileFilter()
      {
        @Override
        public boolean accept(File file) {
          return !file.isDirectory();
        }
      };
      files = dir.listFiles(fileFilter);

      //Lists only files since we've applied file filter
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After filtering the folders");
      System.out.println("--------------------------------");

      // Sort files by name
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2) {
          return ((File) f1).getName().compareTo(((File) f2).getName());
        }
      });

      //Prints the files in file name ascending order
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After sorting by name");
      System.out.println("----------------------------------");

      // Sort files by size.
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2)
        {
          if (((File) f1).length() < ((File) f2).length())
          {
            return -1;
          }
          else if (((File) f1).length() > ((File) f2).length())
          {
            return 1;
          }
          else
          {
            return 0;
          }
        }
      });

      //Prints files in order by file size
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("After sorting by length");
      System.out.println("-------------------------------");

      // Sort files by date.
      Arrays.sort(files, new Comparator()
      {
        @Override
        public int compare(Object f1, Object f2)
        {
          if (((File) f1).lastModified() < ((File) f2).lastModified())
          {
            return -1;
          }
          else if (((File) f1).lastModified() > ((File) f2).lastModified())
          {
            return 1;
          }
          else
          {
            return 0;
          }
        }
      });

      //Prints files in order by last modified date
      for(File file:files)
      {
        System.out.println(file.getName());
      }
      System.out.println("-------------------------");
    }
  }
}


Above program has been tested in 1.5 and 1.6.

Click here to check out other programs that I've developed.

System.out.println() short cut keys on different IDEs

If you're using different IDE to develop a program in Java, you might have searched for a short cut key for System.out.println(). I've so far programmed Java using 3 different IDEs Netbeans, Eclipse, and JDeveloper.

Here the short cuts for System.out.println on each IDE above
Short cut on Netbeans
Type sout and press tab key

Short cut on Eclipse
Type syso and press Ctrl+space

Short cut on JDeveloper
Type sop and press Alt+Enter

Servlet

URI And URL Difference

Before going into URL and URI,
you need to know some background. Do you ever thought about, who decides what is URL? and what is URI? or who is the authority for URL, URI and such naming conventions?

W3C and IETF

There are two separate bodies W3C and IETF. The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. The specifications for URI and URL are defined by W3C.
It was founded and headed by Sir Tim Berners-Lee. He is one of the greatest scientist living now. He created this www model of server and client architecture, a web server serving web pages through network and client browsers reading it. He did it first when he was with CERN. He created the world’s first web page http://info.cern.ch/ . He was also in HTML 2.0 working group of IETF. So it is very appropriate for W3C to define URI and URL.
Internet Engineering Task Force (IETF) is an open international community working on Internet related standards. In general it addresses issues of Internet protocols.
In particular W3C defines the web, html specifications and related information. IETF defines IP, TCP, or DNS, for security at any of these levels; with SMTP or NNTP protocols.
So the stake for definition for URI and URL is with W3C. But as there is only a thin line between these organisation’s work they tend to cross each other. In some place IETF gives dissimilar definition for URL and URI.
If you read through the huge volume of journals available in web for this topic, you can sense that experts :-( are using URI and URL synonymously. Which is causing all these confusion among the web community about URI, URL and URN.

URI

An URI identifies a resource. It is a locator. It includes a URI scheme, authority, path, query and fragment by syntax. For example, http: is a URI scheme.
Syntax of URI based on RFC 3986
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
| _____________________|__
/ \ / \
urn:example:animal:ferret:nose

URL

The term “Uniform Resource Locator” (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network “location”).

URN

The term “Uniform Resource Name” (URN) is used to identify a resource independent of its location. Example urn:ISBN:1-23-432536-5

Summary of differences between URI and URL

  • A URI was either a URL or a URN.
  • URL is a subset of URI. It identifies a resource using one of the URI schemes.
  • URN is a subset of URI. It identifies a resource independent of its location.
Whenever you have a doubt that, whether something is a URL or URI then use URI as a term to identify it. Since URI is a super set of URL.

Session Life Cycle

When I say life cycle, I can hear you murmur “Oh no not again, how many life cycles I have to deal with”! In real world everything has life cycle, then why not in programming, after all, software is all about mimicking real life.  In a previous article I discussed about methods used for session tracking.
Frog Life Cycle
Frog Life Cycle
It has fundamental information about what a session is and how to manage it. At the end of that article I have given a preview about “5. Session tracking API”. Now we are going to dive deep into it.
Just to recap, session is a conversion between a server and a client. An elite way to manage the session in servlets is to use API. Any web server supporting servlets will eventually have to implement the servlet API. It may or may not provide with more features of luxury but the minimum is guaranteed. Servlet specification ensures that, the minimum features provided make the session management job easier. Servlet API will use one of the underlying traditional mechanisms like cookies, URL rewriting, but that will happen behind the scenes and you need not worry about it!

How to access HttpSession object?

Every request is associated with an HttpSession object. It can be retrieved using getSession(boolean create) available in HttpServletRequest. It returns the current HttpSession associated with this request or, if there is no current session and create is true, and then returns a new session. A session can be uniquely identified using a unique identifier assigned to this session, which is called session id. getId() gives you the session id as String.
isNew() will be handy in quite a lot of situations. It returns true if the client does not know about the session or if the client chooses not to join the session. getCreationTime() returns the time when this session was created. getLastAccessedTime() returns the last time the client sent a request associated with this session.

How to store data in session?

Once you have got access to a session object, it can be used as a HashTable to store and retrieve values. It can be used to transport data between requests for the same user and session. setAttribute(String name, Object value) adds an object to the session, using the name specified. Primitive data types cannot be bound to the session.
An important note to you, session is not a bullock cart. It should be used sparingly for light weight objects. If you are in a situation where you have to store heavy weight objects in session, then you are in for a toss. Now it’s time to consult a software doctor. Your software design is having a big hole in it. HttpSession should be used for session management and not as a database.
Follow a proper naming convention to store data in session. Because it will overwrite the existing object if the name is same. One more thing to note is your object needs to implement Serializable interface if you are going to store it in session and carry it over across different web servers.

How to retrieve data from session?

getAttribute(String name) returns the object bound with the specified name in this session. Be careful while using this, most programmers fell into a deeply dug pit NullPointerException. Because it returns null if no object is bound under the name. Always ensure to handle null. Then, removeAttribute(String name) removes the object bound with the specified name from the session. Note a point; be cautious not to expose the session id to the user explicitly. It can be used to breach into another client’s session unethically.

How to invalidate a session object?

By default every web server will have a configuration set for expiry of session objects. Generally it will be some X seconds of inactivity. That is when the user has not sent any request to the server for the past X seconds then the session will expire. What do I mean by expire here. Will the browser blowup into colorful pieces? When a session expires, the HttpSession object and all the data it contains will be removed from the system. When the user sends a request after the session has expired, server will treat it as a new user and create a new session.
Apart from that automatic expiry, it can also be invalidated by the user explicitly. HttpSession provides a method invalidate() this unbinds the object that is bound to it. Mostly this is used at logout. Or the application can have an absurd logic like after the user logins he can use the application for only 30 minutes. Then he will be forced out. In such scenario you can use getCreationTime().
Generally session object is not immortal because of the default configuration by the web server. Mostly these features are left to the imagination of web server implementers. If you take Apache Tomcat 5.5, there is an attribute maxInactiveInterval. A negative value for this will result in sessions never timing out and will be handy in many situations.
Long live the sessions!

An example servlet program to demonstrate the session API

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
public class SessionExample extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
 
// getting current HttpSession associated with this request or, if there
// is no current session and create is true, returns a new session.
HttpSession session = request.getSession(true);
 
// Calculating Hit Count
Integer count = (Integer) session
.getAttribute("SessionExample.HitCount");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.setAttribute("SessionExample.HitCount", count);
 
out.println("<HTML><HEAD><TITLE>SessionExample</TITLE></HEAD>");
out.println("<BODY><H1>Example session servlet to "
+ "demostrate session tracking and life cycle</H1>");
 
// Displaying the hit count
out.println("Hit count for your current session is " + count);
 
out.println("<H2>Some basic session information:</H2>");
out.println("Session ID: " + session.getId() + "</BR>");
out.println("Is it a new session: " + session.isNew() + "</BR>");
out.println("Session Creation time: " + session.getCreationTime());
out.println("(" + new Date(session.getCreationTime()) + ")</BR>");
out.println("Last accessed time: " + session.getLastAccessedTime());
out.println("(" + new Date(session.getLastAccessedTime()) + ")</BR>");
out.println("Max in active time interval: "
+ session.getMaxInactiveInterval() + "</BR>");
// Checks whether the requested session ID came in as a cookie
out.println("Session ID came in as a cookie: "
+ request.isRequestedSessionIdFromCookie() + "</BR>");
 
out.println("<H2>Iteratively printing all the values "
+ "associated with the session:</H2>");
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = session.getAttribute(name).toString();
out.println(name + " = " + value + "</BR>");
}
 
out.println("</BODY></HTML>");
}
}
Output of the example session servlet
Output of the example session servlet

Servlet JSP Communication

getServletConfig().getServletContext().getRequestDispatcher(“jspfilepathtoforward”).forward(request, response);
The above line is essence of the answer for “How does a servlet communicate with a JSP page?”
When a servlet jsp communication is happening, it is not just about forwarding the request to a JSP from a servlet. There might be a need to transfer a string value or on object itself.
Following is a servlet and JSP source code example to perform Servlet JSP communication. Wherein an object will be communicated to a JSP from a Servlet.

Following are the steps in Servlet JSP Communication:

1. Servlet instantiates a bean and initializes it.
2. The bean is then placed into the request
3. The call is then forwarded to the JSP page, using request dispatcher.
Example Servlet Source Code: (ServletToJSP.java)
public class ServletToJSP extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    //communicating a simple String message.
    String message = "Example source code of Servlet to JSP communication.";
    request.setAttribute("message", message);
 
    //communicating a Vector object
    Vector vecObj = new Vector();
    vecObj.add("Servlet to JSP communicating an object");
    request.setAttribute("vecBean",vecObj);
 
    //Servlet JSP communication
    RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/javaPapers.jsp");
    reqDispatcher.forward(request,response);
  }
}
Example JSP Source Code: (javaPapers.jsp)
<html>
<body>
<%
  String message = (String) request.getAttribute("message");
  out.println("Servlet communicated message to JSP: "+ message);
 
  Vector vecObj = (Vector) request.getAttribute("vecBean");
  out.println("Servlet to JSP communication of an object: "+vecObj.get(0));
%>
</body>
</html>

Session Tracking Methods

Following answer is applicable irrespective of the language and platform used. Before we enter into session tracking, following things should be understood.

What is a session?

A session is a conversation between the server and a client. A conversation consists series of continuous request and response.

Why should a session be maintained?

When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol.
When there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking.
Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.

Session tracking methods:

  1. User authorization
  2. Hidden fields
  3. URL rewriting
  4. Cookies
  5. Session tracking API
The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields

<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:
Cookie cookie = new Cookie(“userID”, “7456″);
res.addCookie(cookie);
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session object to store and retrieve java objects across the session. Session tracking is at the best when it is implemented using session tracking api.

What happens if you call destroy() from init() in java servlet?

destroy() gets executed and the initialization process continues. It is a trick question in servlets interview.
In java servlet, destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? No, it will not. destroy() method is not supposed to and will not destroy a java servlet. Don’t get confused by the name. It should have been better, if it was named onDestroy().
The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues. With respective to this question, the destroy() gets executed and then the servlet initialization gets completed.
Have a look at this java servlet interview question: Servlet Life Cycle – Explain, it might help you to understand better.

How to avoid IllegalStateException in java servlet?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
Example servlet source code snippet:

public void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException {
if("success".equals(processLogin())) {
response.sendRedirect("menu.jsp");
return; // <-- this return statement ensures that no content is adedd to the response further
}

Note: This same scenario of IllegalStateException is applicable in JSP also.
/*
other servlet code that may add to the response….
*/
}

What is servlet mapping?

Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.

How is servlet mapping defined?

Servlets should be registered with servlet container. For that, you should add entries in web deployment descriptor web.xml. It is located in WEB-INF directory of the web application.
Entries to be done in web.xml for servlet-mapping:
<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

Syntax for servlet mapping as per servlet specification SRV.11.2:

A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
A string containing only the ‘/’ character indicates the “default” servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
All other strings are used for exact matches only.

Rule for URL path mapping:

It is used in the following order. First successful match is used with no further attempts.
1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

What is implicit mapping?

A servlet container can have a internal JSP container. In such case, *.jsp extension is mapped to the internal container. This mapping is called implicit mapping. This implicit mapping allows ondemand execution of JSP pages. Servlt mapping defined in web application has high precedence over the implicit mapping.

Example code for java servlet mapping:

<servlet>
<servlet-name>milk</servlet-name>
<servlet-class>com.javapapers.Milk</servlet-class>
</servlet>
<servlet>
<servlet-name>points</servlet-name>
<servlet-class>com.javapapers.Points</servlet-class>
</servlet>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>com.javapapers.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>points</servlet-name>
<url-pattern>/pointlist</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

What is Servlet Invoker?

As defined by Apache Tomcat specification, the purpose of Invoker Servlet is to allow a web application to dynamically register new servlet definitions that correspond with a <servlet> element in the /WEB-INF/web.xml deployment descriptor.By enabling servlet invoker the servlet mapping need not be specified for servlets. Servlet ‘invoker’ is used to dispatch servlets by class name.
Enabling the servlet invoker can create a security hole in web application. Because, Any servlet in classpath even also inside a .jar could be invoked directly. The application will also become not portable. Still if you want to enable the servlet invoker consult the web server documentation, because every server has a different method to do it.
In Tomcat 3.x, by default the servlet invoker is enabled. Just place the servlets inside /servlet/ directory and access it by using a fully qualified name like http://[domain]:[port]/[context]/servlet/[servlet.
This mapping is available in web application descriptor (web.xml), located under $TOMCAT_HOME/conf.
/servlet/ is removed from Servlet 2.3 specifications.
In Tomcat 4.x, by defaul the servlet invoker id disabled. The <servlet-mapping> tag is commented inside the default web application descriptor (web.xml), located under $CATALINA_HOME/conf. To enable the invoker servlet uncomment the following two blocks.
<!– The mapping for the invoker servlet –>
<!–
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
–>


<!–
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
–>

Difference between HttpServlet and GenericServlet

javax.servlet.GenericServlet
Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable
  • GenericServlet defines a generic, protocol-independent servlet.
  • GenericServlet gives a blueprint and makes writing servlet easier.
  • GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface.
  • GenericServlet implements the log method, declared in the ServletContext interface.
  • To write a generic servlet, it is sufficient to override the abstract service method.
javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable
  • HttpServlet defines a HTTP protocol specific servlet.
  • HttpServlet gives a blueprint for Http servlet and makes writing them easier.
  • HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.

What is preinitialization of a java servlet?

In the java servlet life cycle, the first phase is called ‘Creation and intialization’.
The java servlet container first creates the servlet instance and then executes the init() method. This initialization can be done in three ways. The default way is that, the java servlet is initialized when the servlet is called for the first time. This type of servlet initialization is called lazy loading.

The other way is through the <load-on-startup>non-zero-integer</load-on-startup> tag using the deployment descriptor web.xml. This makes the java servlet to be loaded and initialized when the server starts. This process of loading a java servlet before receiving any request is called preloading or preinitialization of a servlet.
Servlet are loaded in the order of number(non-zero-integer) specified. That is, lower(example: 1) the load-on-startup value is loaded first and then servlet with higher values are loaded.
Example usage:
<servlet>
       <servlet-name>Servlet-URL</servlet-name>
       <servlet-class>com.javapapers.Servlet-Class</servlet-class>
       <load-on-startup>2</load-on-startup>
</servlet>