Web

Keywords / Categories: Apache HTTP Server, Apache Tomcat, Jakarta Tomcat, Ajax Comet, COMETD, Jetty, Bayeux Protocol, Websocket Protocol, HTTP Streaming, Long Polling, Java Servlet, Web Application, Eclipse IDE, NetBean IDE, J2EE, Servlet, JSP, JSF 2, GlassFish 3.1, WebLogic Server 12c, JBOSS AS 7
 

Server Type based on scripts

  • Java Server (*.jsp, *.jsf)
  • ASP Server (*.asp)
  • PHP Server (*.php)
  • Perl Server (*.pl)
  • ColdFusion Server (*.cfm)

1. Apache HTTP Server

Appache Web Server is a C implementation of an HTTP web server.

1.1. Installation

sudo apt-get install apache2

1.2. Configuration

Main configuration file: /etc/apache2/apache2.conf. Other configuration files may be added using the Include directive, and wildcards can be used to include many configuration files. Changes to the main configuration files are only recognized by Apache2 when it is started or restarted.

Virtual Host Sites: /etc/apache2/sites-available/default. If you wish to configure a new virtual host or site, copy that file into the same directory with a name you choose. For example, sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/mynewsite Edit the new file to configure the new site using some of the directives described below.

Listener: The default value for the Listen directive is 80. Change this to 127.0.0.1:80 to cause Apache2 to listen only on your loopback interface so that it will not be available to the Internet, to (for example) 81 to change the port that it listens on, or leave it as is for normal operation. This directive can be found and changed in its own file, /etc/apache2/ports.conf

ServiceNmae: The default virtual host has no ServerName directive specified, so it will respond to all requests that do not match a ServerName directive in another virtual host. If you have just acquired the domain name ubunturocks.com and wish to host it on your Ubuntu server, the value of the ServerName directive in your virtual host configuration file should be ubunturocks.com. Add this directive to the new virtual host file you created earlier (/etc/apache2/sites-available/mynewsite).

DocumentRoot: The default value is /var/www. No site is configured there, but if you uncomment the RedirectMatch directive in /etc/apache2/apache2.conf requests will be redirected to /var/www/apache2-default where the default Apache2 site awaits. Change this value in your site's virtual host file, and remember to create that directory if necessary!

The /etc/apache2/sites-available directory is not parsed by Apache2. Symbolic links in /etc/apache2/sites-enabled point to “available” sites. Use the a2ensite (Apache2 Enable Site) utility to create those symbolic links, like so: sudo a2ensite mynewsite where your site’s configuration file is /etc/apache2/sites-available/mynewsite. Similarly, the a2dissite utility should be used to disable sites.

DirectoryIndex: the default page served by the server when a user requests an index of a directory by specifying a forward slash (/) at the end of the directory name. The default value, found in /etc/apache2/apache2.conf is " index.html index.cgi index.pl index.php index.xhtml". Thus, if Apache2 finds a file in a requested directory matching any of these names, the first will be displayed.

ErrorDocument: allows you to specify a file for Apache to use for specific error events. For example, if a user requests a resource that does not exist, a 404 error will occur, and per Apache2's default configuration, the file /usr/share/apache2/error/HTTP_NOT_FOUND.html.var will be displayed. That file is not in the server's DocumentRoot, but there is an Alias directive in /etc/apache2/apache2.conf that redirects requests to the /error directory to /usr/share/apache2/error/. To see a list of the default ErrorDocument directives, use this command: grep ErrorDocument /etc/apache2/apache2.conf

TransferLog: the server writes the transfer log to the file /var/log/apache2/access.log. You can change this on a per-site basis in your virtual host configuration files with the CustomLog directive, or omit it to accept the default, specified in /etc/apache2/apache2.conf. You may also specify the file to which errors are logged, via the ErrorLog directive, whose default is /var/log/apache2/error.log. These are kept separate from the transfer logs to aid in troubleshooting problems with your Apache2 server. You may also specify the LogLevel (the default value is "warn") and the LogFormat (see /etc/apache2/apache2.conf for the default value).

1.3. Status/start/stop/restart

sudo /etc/init.d/apache2 [status|start|stop|restart]

1.4. Get Started

edit this document: /var/www/index.html

http://localhost

1.5. Exploring More…

Documentation: http://httpd.apache.org/docs/2.2/

2. Tomcat Server

Appache Tomcat (Jakarta Tomcat) is a pure java implementation of  HTTP web server which also support Java Servlet and JavaServer Pages (JSP) specification.

2.1. Installation

sudo apt-get install tomcat6

2.2. Configuration

Main configuration file: /etc/tomcat6.

Default Port: By default Tomcat 6.0 runs a HTTP connector on port 8080 and an AJP connector on port 8009. You might want to change those default ports to avoid conflict with another server on the system. This is done by changing the following lines in /etc/tomcat6/server.xml:

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
...
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

JVM: By default Tomcat will run preferably with OpenJDK-6, then try Sun’s JVM, then try some other JVMs. If you have various JVMs installed, you can set which should be used by setting JAVA_HOME in /etc/default/tomcat6:

JAVA_HOME=/usr/lib/jvm/java-6-sun

User / Role: Usernames, passwords and roles (groups) can be defined centrally in a Servlet container. In Tomcat 6.0 this is done in the /etc/tomcat6/tomcat-users.xml file:

<role rolename="admin"/>
<user username="tomcat" password="s3cret" roles="admin"/>

2.3. Documentation

sudo apt-get install tomcat6-docs

2.4. Admin Web App

sudo apt-get install tomcat6-admin

The first one is the manager webapp, which you can access by default at http://yourserver:8080/manager/html. It is primarily used to get server status and restart webapps.

 [Note]
Access to the manager application is protected by default: you need to define a user with the role “manager” in /etc/tomcat6/tomcat-users.xml before you can access it.

The second one is the host-manager webapp, which you can access by default at http://yourserver:8080/host-manager/html. It can be used to create virtual hosts dynamically.

 [Note]
Access to the host-manager application is also protected by default: you need to define a user with the role “admin” in /etc/tomcat6/tomcat-users.xml before you can access it.

For security reasons, the tomcat6 user cannot write to the /etc/tomcat6 directory by default. Some features in these admin webapps (application deployment, virtual host creation) need write access to that directory. If you want to use these features execute the following, to give users in the tomcat6 group the necessary rights:

sudo chgrp -R tomcat6 /etc/tomcat6
sudo chmod -R g+w /etc/tomcat6

2.5. Example Package

The tomcat6-examples package contains two webapps that can be used to test or demonstrate Servlets and JSP features, which you can access them by default at http://yourserver:8080/examples. You can install them by entering the following command in the terminal prompt:

sudo apt-get install tomcat6-examples

2.6. Private Instance

Tomcat is heavily used in development and testing scenarios where using a single system-wide instance doesn’t meet the requirements of multiple users on a single system. The Tomcat 6.0 packages in Ubuntu come with tools to help deploy your own user-oriented instances, allowing every user on a system to run (without root rights) separate private instances while still using the system-installed libraries.

[Note]
It is possible to run the system-wide instance and the private instances in parallel, as long as they do not use the same TCP ports.

2.6.1. Installing private instance support

You can install everything necessary to run private instances by entering the following command in the terminal prompt:

sudo apt-get install tomcat6-user

2.6.2. Creating a private instance

You can create a private instance directory by entering the following command in the terminal prompt:

tomcat6-instance-create my-instance

This will create a new my-instance directory with all the necessary subdirectories and scripts. You can for example install your common libraries in the lib/ subdirectory and deploy your webapps in the webapps/ subdirectory. No webapps are deployed by default.

2.6.3. Configuring your private instance

You will find the classic Tomcat configuration files for your private instance in the conf/ subdirectory. You should for example certainly edit the conf/server.xml file to change the default ports used by your private Tomcat instance to avoid conflict with other instances that might be running.

2.6.4. Starting/stopping your private instance

You can start your private instance by entering the following command in the terminal prompt (supposing your instance is located in the my-instance directory):

my-instance/bin/startup.sh
[Note]
You should check the logs/ subdirectory for any error. If you have a java.net.BindException: Address already in use<null>:8080 error, it means that the port you’re using is already taken and that you should change it.

You can stop your instance by entering the following command in the terminal prompt (supposing your instance is located in the my-instance directory):

my-instance/bin/shutdown.sh

2.7. Exploring More

Documentataion: http://tomcat.apache.org/tomcat-7.0-doc/index.html

3. COMETD

Bayeux is a protocol for transporting asynchronous messages (primarily over HTTP), with low latency between a web server and a web client.

The primary purpose of Bayeux is to support responsive bidirectional interactions between web clients using Ajax and the web server.

The messages are routed via named channels and can be delivered:

  • server to client
  • client to server
  • client to client (via the server)

Delivery of asynchronous messages from the server to a web client is often described as “server-push”.

The combination of server push techniques with an Ajax web application has been called “Comet“.

CometD is a project by the Dojo Foundation to produce a specification, the Bayeux specification, and a set of implementations of that specification. It is an implementation of a scalable comet (server push) for the web.

3.1. Installation

Download the CometD distribution from the above web site.

Then unpack the distribution:

$ tar zxvf cometd-<version>.tgz
$ cd cometd-<version>/

3.2. Directory Layout

bayeux                       – The Bayeux Specification
cometd-archetypes – The Maven2 archetypes for quick application development
cometd-demo           – Demo of the Java server and of the Dojo/jQuery clients
cometd-java             – The Java server and java client libraries
cometd-javascript  – The JavaScript (Dojo/jQuery) client libraries

3.3. Building COMETD

If you have checked out the source release, follow the instructions at
http://cometd.org/documentation/building, or just to

$ mvn install

3.4. Running COMETD Demo

$ cd cometd-<version>/
$ cd cometd-demo
$ mvn jetty:deploy-war     or     $ mvn jetty:run

point your browser at http://localhost:8080

Alternately you can deploy the CometD demo war into any servlet 2.5 or 3.0 server (eg jetty, tomcat, glassfish) with commands like
$ cp cometd-demo/target/cometd-demo/target/cometd-demo-*.war $MY_SERVER/webapps/cometd.war
cd $MY_SERVER
<command to run my server>

3.5. Load Testing

To run load testing, open two windows. In the server window run:

$ cd cometd-java/cometd-java-client
$ mvn -Pserver exec:exec

In the client window (potentially on another machine), run

$ cd cometd-java/cometd-java-client
$ mvn -Pclient exec:exec

Then follow instructions on the console to generate load.

3.6. Exploring More

Documentation for COMETD: http://cometd.org/documentation

Developing with Comet and Java Implementing the Servlet 3.0 specification

Ajax for Java developers: Write scalable Comet applications with Jetty and Direct Web Remoting

4. Jetty

Jetty s a lightweight Servlet container if you are going to develop servlets on your local machine.

4.1. Get Started

  1. Make sure you have a Java SDK installed.
  2. Download the latest version of Jetty.
  3. Extract the zip archive to somewhere on your computer.
  4. Open a command line terminal and navigate to the directory where you extracted the archive.
  5. Run the command:
    java -jar start.jar

    The server will start and log messages should start appearing in the terminal.

  6. Open a web browser and enter “http://localhost:8080&#8221; in the address bar.
  7. If you see a “Welcome to Jetty” page then the server is successfully set up. Return to the terminal and press Control-C to stop the server.

4.2. Example for Getting Started

installation
cd apps

export JETTY_VERSION=8.0.1.v20110908
wget http://download.eclipse.org/jetty/$JETTY_VERSION/dist/jettydistribution-$JETTY_VERSION.tar.gz
tar xfz jetty-distribution-$JETTY_VERSION.tar.gz

OR

download aggregate-all-test-jar

mkdir jetty
cd jetty
mkdir aggregate-all-test
cd aggregate-all-test
export JETTY_VERSION=8.0.1.v20110908
wget -U none http://repo1.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/$JETTY_VERSION/jetty-all-$JETTY_VERSION.jar
wget -U none http://repo1.maven.org/maven2/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar

Start the server

cd jetty-distribution-$JETTY_VERSION
java -jar start.jar

Test it

http://localhost:8080

4.3. Writing a Simple Web Application

The Jetty server has a directory called “webapps” which contains a directory for every website (web application) it hosts. We will create a simple application and place it in this directory.

  1. Make a new directory called “hello” in “webapps”. Files in this directory will be accessible as “http://localhost:8080/hello&#8221;.
  2. Make a new directory called “WEB-INF” in “hello”. This directory will contain configuration information for your application.
  3. Make a new directory called “classes” in “WEB-INF”. This directory will contain the .class files for all your servlets.
  4. Create a file “index.html” in “hello”. This is the page you will get when you go to “http://localhost:8080/hello&#8221;. The file should contain the following:
    <html>
    <head><title>Example Web Application</title></head>
    <body>
    <p>This is a static document with a form in it.</p>
    <form method="POST" action="servlet"/>
    <input name="field" type="text" />
    <input type="submit" value="Submit" />
    </form>
    </body>
    </html>

    If you start the server at this point and click here you will see this new page.

  5. Next we will create the handler for this form, which will be a Java Servlet. Create a file called HelloServlet.java with the following code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    public class HelloServlet extends HttpServlet
    {
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
        {
            String q = req.getParameter("q");
            PrintWriter out = resp.getWriter();
    
            out.println("<html>");
            out.println("<body>");
            out.println("The paramter q was \"" + q + "\".");
            out.println("</body>");
            out.println("</html>");
        }
    
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
        {
            String field = req.getParameter("field");
            PrintWriter out = resp.getWriter();
    
            out.println("<html>");
            out.println("<body>");
            out.println("You entered \"" + field + "\" into the text box.");
            out.println("</body>");
            out.println("</html>");
        }
    }
  6. To compile this class we need the servlet libraries, which are not part of the Java SDK, but can be found in Jetty. Use the following command (in the directory with HelloServlet.java) to compile your servlet:
    javac -cp PATH_TO_JETTY/lib/servlet-api-2.5-6.1.11.jar HelloServlet.java

    The “-cp” option adds the given jar file to the list of places to search for other classes your code requires. Copy the resulting HelloServlet.class file into the “hello/WEB-INF/classes” directory.

  7. Now, we must tell Jetty that this class should be used to handle requests. The following “web.xml” file, which goes in the WEB-INF directory, describes these mappings:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app>
      <display-name>Example</display-name>
    
      <!-- Declare the existence of a servlet. -->
      <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
      </servlet>
    
      <!-- Map URLs to that servlet. -->
      <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/servlet</url-pattern>
      </servlet-mapping>
    </web-app>
  8. If you restart the server you should be able to click here, enter something in the form, and the servlet will respond when you click “Submit”.

Note, there are two methods in a servlet class, doGet() and doPost(). These correspond to the two types of HTTP requests. The form we have uses the POST method. It could also use the GET method. The difference is that in the GET method the parameters are passed as part of the URL, which is inappropriate for most web forms. Try entering “http://localhost:8080/hello/servlet?q=Hello&#8221; into your browser to see how passing parameters with the GET method works.

4.4. Example of a simple application

gedit HelloWorld.java

write a simple HelloWorld handler with a main method to run the server

Compile HelloWorld.java
javac -cp servlet-api-2.5.jar:jetty-all-$JETTY_VERSION.jar HelloWorld.java

Run the handler and Server
java -cp .:servlet-api-2.5.jar:jetty-all-$JETTY_VERSION.jar HelloWorld

Browse Hello World Page
http://localhost:8080

4.5. Old version Jetty 6 from ubuntu

4.5.1. jetty for Debian

This debian package installs Jetty 6 into /usr/share/jetty and other directories under /var and /etc, which are linked to from the /usr/share/jetty directory.

The configuration of the server is in /etc/jetty. The configuration files listed in /etc/jetty/jetty.conf are passed to the command line of Jetty when it is started by /etc/init.d/jetty

Webapps can be deployed by placing them in /var/lib/jetty/webapps (linked from /usr/share/jetty/webapps)

Additional contexts can be configured and (hot) deployed via the /etc/jetty/contexts directory (linked from /usr/share/jetty/contexts).

4.5.2. Installing

$ sudo apt-get install libjetty-java
$ sudo apt-get install libjetty-extra-java
$ sudo apt-get install jetty

4.5.3. Starting

Edit /etc/default/jetty
Set:
NO_START=0

Then do:
$ sudo service jetty start

4.5.4. Stopping

$ sudo service jetty stop

4.6. Exploring More…

http://jetty.codehaus.org/jetty/

http://webtide.intalio.com

5. Web Socket

5.1. IETF Websocket Protocol Specification

Sponsor by Google, Here is the websocket specification.

5.2. Jetty Support Websocket Protocol from version 7.5

Jetty release 7.5.0 now includes a capable websocket java client that can be used for non browser applications or load testing. It is fully asynchronous and can create thousands of connections simultaneously.

5.3. First Example: Chat

Angelo’s Blog: a very detailed three parts article to examine how to do chat by using Websocket embedded in Jetty. The example itself can be found in Jetty download.

5.3.1. Why Websocket

  • Traditional Ajax style chat: the client need to consistently check (long pulling) [2] to get the asynchronous message from the server.
  • In websocket style of chats, the server deliver the message right back to client without the waiting for the client polling. Example of google talk.
For detail, refer to here.
5.3.2. Websocket Browser Support

Google Chrome has the websock support. URL is ws://localhost:8081/ in order to test the chat app from Jetty.

For detail, refer to here.

5.3.3. Configure Eclipse IDE for Jetty

Very detail step by step guide here:.

5.4. Load Testing

The Jetty, CometD and Weksocket developer shows their own example of using Websocks and load testing here.

6. Servlet and Java Server Page

6.1. Servlet / JSP Application Architecture

A servlet is a Java program. A servlet application consists of one or more servlets. A JSP page is translated and compiled into a servlet.

A servlet application runs inside a servlet container and cannot run on its own. A servlet container passes requests from the user to the servlet application and responses from the servlet application back to the user. Most servlet applications include at least several JSP pages. As such, it’s more appropriate to use the term “servlet/JSP application” to refer to a Java web application than to leave JSP out.

Web users use a web browser such as Internet Explorer, Mozilla Firefox, or Google Chrome to access servlet applications. A web browser is referred to as a web client. The following shows the architecture of a servlet/JSP application.

Image from book

The web server and the web client communicate in a language they both are fluent in: the Hypertext Transfer Protocol (HTTP). Because of this, a web server is also called an HTTP server. HTTP is covered in more detail in the next section.

A servlet/JSP container is a special web server that can process servlets as well as serve static contents. In the past, people were more comfortable running a servlet/JSP container as a module of an HTTP server such as the Apache HTTP Server because an HTTP server was considered more robust than a servlet/JSP container. In this scenario the servlet/JSP container would be tasked with generating dynamic contents and the HTTP server with serving static resources. Today servlet/JSP containers are considered mature and widely deployed without an HTTP server. Apache Tomcat and Jetty are the most popular servlet/JSP containers and are free and open-source.

Servlet and JSP are two of a multitude of technologies defined in the Java Enterprise Edition (EE). Other Java EE technologies include Java Message Service (JMS), Enterprise JavaBeans (EJB), JavaServer Faces (JSF), and Java Persistence. The complete list of technologies in the Java EE version 6 (the current version) can be found here.

http://www.oracle.com/technetwork/java/javaee/tech/index.html

To run a Java EE application, you need a Java EE container, such as GlassFish, JBoss, Oracle WebLogic, and IBM WebSphere. You can deploy a servlet/JSP application in a Java EE container, but a servlet/JSP container is sufficient and is more lightweight than a Java EE container. Tomcat and Jetty are not Java EE containers, so they cannot run EJB or JMS.

6.2. Web Framework

There are many excellent frameworks freely available. Struts 2, JavaServer Faces (JSF), Spring MVC, and Google Web Toolkit (GWT) are all recommended. A framework solves common problems in servlet/JSP development and shorten development time.

6.3. Structure of Web Applications And Deployment

Web Applications use a standard directory structure defined in the Servlet specification. When developing web applications on J2EE platform, you must follow this structure so that application can be deployed in any J2EE compliant web server.

A web application has the directory structureas shown in below figure.

J2EE Web Application Directory Structure

The root directory of the application is called the document root. Root directory is mapped to the context path. Root directory contains a directory named WEB-INF. Anything under the root directory excepting the WEB-INF directory is publically available, and can be accessed by URL from browser. WEB-INF directory is a private area of the web application, any files under WEB-INF directory cannot be accessed directly from browser by specifying the URL like http://somesite/WEB-INF/someresource.html. Web container will not serve the content of this directory. However the content of the WEB-INF directory is accessible by the classes within the application. So if there are any resources like JSPs or HTML document that you don’t wish to be accessible directly from web browser, you should place it under WEB-INF directory.

6.3.1. WEB-INF directory structure

WEB-INF directory contains

  • WEB-INF/web.xml deployment descriptor
  • WEB-INF/classes directory
  • WEB-INF/lib directory
/WEB-INF/web.xml

web.xml is called the web application deployment descriptor. This is a XML file that defines servlets, servlet mappings, listeners, filters, welcome files etc. Deployment descriptor is a heart of any J2EE web application, so every web application must have a web.xml deployment descriptor directly under WEB-INF folder. Example:

<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<servlet>
		<servlet-name>MyFirstServlet</servlet-name>
		<servlet-class>MyFirstServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>MyFirstServlet</servlet-name>
		<url-pattern>/MyFirstServlet</url-pattern>
	</servlet-mapping>
</web-app>
/WEB-INF/classes

The classes directory is used to store compiled servlet and other classes of the application. If your classes are organized into packages, the directory structure must be reflected directly under WEB-INF/classes directory. The classes directory is automatically included in CLASSPATH. Example: MyFirstServlet.class

/WEB-INF/lib

Lib directory is used to store the jar files. If application has any bundled jar files, or if application uses any third party libraries such as log4j, JDBC drivers which is packaged in jar file, than these jar files should be placed in lib directory.

All unpacked classes and resources in the /WEB-INF/classes directory, plus classes and resources in JAR files under the /WEB-INF/lib directory are included in classpath and made visible to the containing web application.

6.3.2. Deploy Web App to Tomcat Web Container

  • compile to *.class:  javac -cp $PATH/servlet-api.jar MyFirstServlet.java
  • deploy to /WEB-INF/classes: cp MyFirstServlet.class $CATALINA_HOME/webapps/MyFirstServlet/WEB-INF/classes
  • create web.xml in $CATALINA_HOME/webapps/MyFirstServlet/WEB-INF
  • create index.jsp or index.html in $CATALINA_HOME/webapps/MyFirstServlet if necessary
  • stop TOMCAT: $CATALINA_HOME/bin/shutdown.sh
  • start TOMCAT: $CATALINA_HOME/bin/startup.sh
  • goto http://localhost:8080/MyFirstServlet

6.3.3. Create the WAR (Web application archive) file

Web applications are packaged into a WAR (web application archive). There are many different ways to create a WAR file. You can use jar command, ant or an IDE like Eclipse. This following shows how to create the WAR file using jar tool privided that your src directory setup similar to WEB-INF.

Open the command prompt and change the directory to the MyFirstServlet source directory, and execute the following command.

jar cvf MyFirstServlet.war *

This command packs all the contents under MyFirstServlet directory, including subdirectories, into an archive file called MyFirstServlet .war.
We used following command-line options:

  • -c option to create new WAR file.
  • -v option to generate verbose output.
  • -f option to specify target WAR file name.

You can use following command to view the content of MyFirstServlet .war file.

Jar –tvf MyFirstServlet.war.

This command lists the content of the WAR file.

6.4. Servlet Life Cycle

The servlet life cycle methods defined in Servlet interface are init(), service() and destroy(). The life cycle starts when container instantiates the object of servlet class and calls the init() method, and ends with the container calling the destroy() method.

The signature of this methods are shown below.

public void init(ServletConfig config) throws ServletException<br />
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException<br />
public void destroy()

The servlet life cycle consists of four steps, instantiation, initialization, request handling and end of service. Each of these steps is explained below.

6.4.1. Loading and instantiation

During this step, web container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it until the servlet is needed to service a request.

6.4.2. Initialization

During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application

6.4.3. Request handling A.K.A service() method

After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.

6.4.5. Multithreading issues

During the request processing phase, there can be multiple threads running the service() method of a servlet instance. The Servlet container can send multiple concurrent requests through the service method of the servlet. So it’s upto the developer to properly handle the concurrency.

  1. If the servlet implements the SingleThreadModal interface, Servlet container guarantees that there will be only one request thread at a time in service method. The servlet container can satisfy this requirements by serializing requests to the service method or by maintaining the pool of servlet instance.
  2. If the servlet does not implement SingleThreadModal but either of service, doGet or doPost methods has been defined with the synchronized keyword, the servlet container can not create pool of servlet instance but must serialize requests.

Because of performance reasons, using SingleThreadModal and defining doGet, doPost or service methods with synchronized keywords is highly discouraged.

Though SingleThreadModal can protect your servlet instance variables by guaranteeing only one thread in service method at a time, It doesn’t guarantee thread safety and hence SingleThreadModal is deprecated. So its always a good idea to avoid SingleThreadModal and look for alternative solutions.

6.4.6. End of service destroy() method

When servlet container determines that the servlet should be removed from the service, it calls the destroy() method of the servlet to allow servlet to release any resources it is using (eg. database connections or file handles). Before calling the destroy() method, the container allows any request threads that are currently running in the service method to complete execution within a defined time limit. Once the servlet is removed out of service, container will not send any requests to the servlet. If the servlet needs to be put in service again, the container will create a new servlet instance and the life cycle begins from the initialization phase.

Example: ServletLifeCycleExample.java

6.5. Servlet API

The Servlet API comes in four Java packages. The packages are as follows.

  • javax.servlet. Contains classes and interfaces that define the contract between a servlet and a servlet container.

  • javax.servlet.http. Contains classes and interfaces that define the contract between an HTTP servlet and a servlet container.

  • javax.servlet.annotation. Contains annotations to annotate servlets, filters, and listeners. It also specifies metadata for annotated components.

  • javax.servlet.descriptor. Contains types that provide programmatic access to a web application’s configuration information.

6.5.1. javax.servlet

Click to collapse

Examples of Servlet

Example for Servlet: MyServlet.java

In Servlet interface, you need to implement all the methods. GenericServlet implements most of methods of Servlet for you.

Example: GenericServletExample.java

6.5.2. javax.servlet.http

The javax.servlet.http package is the second package in the Servlet API that contains classes and interfaces for writing servlet applications. Many of the types in javax.servlet.http override those in javax.servlet.

Click to collapse

The HttpServlet class overrides the javax.servlet.GenericServlet class. When using HttpServlet, you will also work with the HttpServletRequest and HttpServletResponse objects that represent the servlet request and the servlet response, respectively. The HttpServletRequest interface extends javax.servlet.ServletRequest and HttpServletResponse extends javax.servlet.ServletResponse.

HttpServlet overrides the service method in GenericServlet and adds another service method with the following signature:

protected void service(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, java.io.IOException

The difference between the new service method and the one in javax.servlet.Servlet is that the former accepts an HttpServletRequest and an HttpServletResponse, instead of a ServletRequest and a ServletResponse.

The servlet container, as usual, calls the original service method in javax.servlet.Servlet, which in HttpServlet is written as follows:

public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {
    HttpServletRequest request;
    HttpServletResponse response;
    try {
        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;
    } catch (ClassCastException e) {
        throw new ServletException("non-HTTP request or response");
    }
    service(request, response);
}

The original service method downcasts the request and response objects from the servlet container to HttpServletRequest and HttpServletResponse, respectively, and call the new service method. The downcasting is always successful because the servlet container always passes an HttpServletRequest and an HttpServletResponse when calling a servlet’s service method, to anticipate the use of HTTP. Even if you are implementing javax.servlet.Servlet or extending javax.servlet.GenericServlet, you can downcast the servlet request and servlet response passed to the service method to HttpServletRequest and HttpServletResponse, respectively.

The new service method in HttpServlet then examines the HTTP method used to send the request (by calling request.getMethod) and call one of the following methods: doGet, doPost, doHead, doPut, doTrace, doOptions, and doDelete. Each of the seven methods represents an HTTP method. doGet and doPost are the most often used. As such, you rarely need to override the service methods anymore. Instead, you override doGet or doPost or both doGet and doPost.

Click to collapse

To summarize, there are two features in HttpServlet that you do not find in GenericServlet:

  • Instead of the service method, you will override doGet, doPost, or both of them. In rare cases, you will also override any of these methods: doHead, doPut, doTrace, doOptions, doDelete.

  • You will work with HttpServletRequest and HttpServletResponse, instead of ServletRequest and ServletResponse.

Example: FormServlet.java

7. Oracle GlassFish Server 3.1

Administration

Usage: asadmin [-H|--host <host(default:localhost)>]
        [-p|--port <port(default:4848)>] [-u|--user <user(default:admin)>]
        [-W|--passwordfile <passwordfile>]
        [-t|--terse[=<terse(default:false)>]]
        [-s|--secure[=<secure(default:false)>]]
        [-e|--echo[=<echo(default:false)>]]
        [-I|--interactive[=<interactive(default:true)>]]
        [-?|--help[=<help(default:false)>]] [subcommand [options] [operands]]

Startup

C:\OpenSource\glassfish3\glassfish\bin>asadmin.bat start-domain
Waiting for domain1 to start ..
Successfully started the domain : domain1
domain  Location: C:\OpenSource\glassfish3\glassfish\domains\domain1
Log File: C:\OpenSource\glassfish3\glassfish\domains\domain1\logs\server.log
Admin Port: 4848
Command start-domain executed successfully.

Admin Console

http://localhost:4848/ (should change admin password)

Web Default page

http://localhost:8080/

Shutdown

C:\OpenSource\glassfish3\glassfish\bin>asadmin.bat stop-domain
Waiting for the domain to stop ..
Command stop-domain executed successfully.

Deployment an Application

Go to your clean build directory, create a WAR file:

jar -cvf webtest.war *

Go to login to Admin Console, click Application->Deploy button, choose the WAR file created above, and deploy.

8. Oracle WebLogic Server 12c

After download and unzip to D:\Apps\wls1211_dev on Window 2008 Server.

8.1. Unpack the software

rem **************************************************
@rem  WebLogic Server 12c (12.1.1.0) Zip Configuration
@rem
@rem  MW_HOME:   D:\Apps\wls1211_dev
@rem  JAVA_HOME: "D:\Apps\glassfish3\jdk7"
@rem  **************************************************
set JAVA_HOME="D:\Apps\glassfish3\jdk7"
set MW_HOME=D:\Apps\wls1211_dev
set JAVA_VENDOR=Oracle
D:\Apps\wls1211_dev>configure.cmd
 **************************************************
 WebLogic Server 12c (12.1.1.0) Zip Configuration
 MW_HOME:   D:\Apps\WLS121~1
 JAVA_HOME: D:\Apps\glassfish3\jdk7
 **************************************************
771 jar files are being unpacked.
Please wait, title bar will show progress ...
 "ACLs are being setup for D:\Apps\WLS121~1 Please wait..."
CLASSPATH="D:\Apps\glassfish3\jdk7\lib\tools.jar;D:\Apps\WLS121~1\wlserver\serve
r\lib\weblogic_sp.jar;D:\Apps\WLS121~1\wlserver\server\lib\weblogic.jar;D:\Apps\
WLS121~1\modules\features\weblogic.server.modules_12.1.1.0.jar;D:\Apps\WLS121~1\
wlserver\server\lib\webservices.jar;D:\Apps\WLS121~1\modules\ORGAPA~1.1/lib/ant-
all.jar;D:\Apps\WLS121~1\modules\NETSFA~1.0_1/lib/ant-contrib.jar;D:\Apps\glassf
ish3\jdk7\lib\tools.jar;D:\Apps\WLS121~1\wlserver\server\lib\weblogic_sp.jar;D:\
Apps\WLS121~1\wlserver\server\lib\weblogic.jar;D:\Apps\WLS121~1\modules\features
\weblogic.server.modules_12.1.1.0.jar;D:\Apps\WLS121~1\wlserver\server\lib\webse
rvices.jar;D:\Apps\WLS121~1\modules\ORGAPA~1.1/lib/ant-all.jar;D:\Apps\WLS121~1\
modules\NETSFA~1.0_1/lib/ant-contrib.jar;"
PATH=";D:\Apps\WLS121~1\wlserver\server\native\win\32;D:\Apps\WLS121~1\wlserver\
server\bin;D:\Apps\WLS121~1\modules\ORGAPA~1.1\bin;D:\Apps\glassfish3\jdk7\jre\b
in;D:\Apps\glassfish3\jdk7\bin;;D:\Apps\WLS121~1\wlserver\server\native\win\32;D
:\Apps\WLS121~1\wlserver\server\bin;D:\Apps\WLS121~1\modules\ORGAPA~1.1\bin;D:\A
pps\glassfish3\jdk7\jre\bin;D:\Apps\glassfish3\jdk7\bin;C:\Windows\system32;C:\W
indows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\P
rogram Files\Microsoft Network Monitor 3\;c:\Program Files\HP\HP BTO Software\bi
n;c:\Program Files\HP\HP BTO Software\bin\win64;c:\Program Files\HP\HP BTO Softw
are\bin\win64\OpC;;D:\Apps\WLS121~1\wlserver\server\native\win\32\oci920_8;D:\Ap
ps\WLS121~1\wlserver\server\native\win\32\oci920_8"
Your environment has been set.
BUILD SUCCESSFUL
Total time: 0 seconds

8.2. Create a WebLogic Domain

Create an directory for your propose domain first. Then,

D:\Apps\WLS121~1\wlserver\common\bin>config.cmd

For more detail,

http://docs.oracle.com/cd/E13222_01/wls/docs81/adminguide/createdomain.html#1127576

8.3. Startup the WebLogic

D:\Sites\wlsdomain\wlsdomain\startWebLogic.cmd

For detail, http://docs.oracle.com/cd/E13222_01/wls/docs81/ConsoleHelp/startstop.html

8.4. Access Admin Console

To access the Administration Console for the domain, use any of the following URLs:

  • From the same computer on which the server is running: http://localhost:7001/console
  • From any computer:
    http://DNS-name:7001/console
    where DNS-name is the DNS name of the computer on which the server is running.
  • From any computer:
    http://IP=Address:7001/console
    where IP-Address is an IP address of the computer on which the server is running.

9. JBOSS AS 7

9.1. Download and Install

gunzip jboss-as-7.0.2.Final.tar.gz
tar -xvf jboss-as-7.0.2.Final.tar
rm jboss-as-7.0.2.Final.tar

cd /home/henry/apps/jboss-as-7.0.2.Final
export JBOSS_HOME=/home/henry/apps/jboss-as-7.0.2.Final
cd $JBOSS_HOME/bin

make sure the tomcat is not started, if yes, $CATALINA_HOME/bin/shutdown.sh   (because they use the same port for web service localhost:8080)

9.2. Startup

start JBOSS AS 7 using the default web profile in standalone mode in background:
./standalone &

9.3. Testing and Admin

http://localhost:8080
http://localhost:9990/console

9.4. Shutdown

./jboss-admin.sh --connect command=:shutdown
or
./jboss-admin.sh --connect controller=<IP>:<port> command=shutdown

9.5. Deploy

Copy apps from TOMCAT
cd ~/apps/apache-tomcat-7.0.25/webapps/MyFirst
jar cvf MyFirst.war *.jsp WEB-INF
mv MyFirst.war ~/apps/jboss-as-7.0.2.Final/standalone/deployments

Leave a comment