• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Servlets

WebServlet Annotations

November 19, 2015 By j2eereference Leave a Comment

WEBSERVLET ANNOTATIONS

Among many interesting features, Servlet 3.0 introduced annotations that make deploying Servlets, Filters and Listeners of all types easier. Most of the WebServlet annotations are packaged under javax.servlet.annotation. In this post we’ll see the following annotations.

  • @WebServlet
  • @WebFilter
  • @WebListener
  • @WebInitParam

WebListener, WebServlet and WebFilter annotations are placed on classes implementing respectively Listeners, Servlets and Filters. The WebInitParam annotation is used with WebServlet and WebFilter annotations specifying Servlet and Filter initialization parameters.

In order to provide support for these annotations, the mechanics of WebApp loading has to become a bit smarter.

Application Loading Phase

When an application loads, all classes comprising the application are examined for presence of the annotations. When these annotations are found on a particular class, the container registers instances of the classes as Listeners, Servlets, or Filters.

Registering a Listener using @WebListener

The WebListener annotation is used to register the following types of listeners

  • Context Listener (javax.servlet.ServletContextListener)
  • Context Attribute Listener (javax.servlet.ServletContextAttributeListener)
  • Servlet Request Listener (javax.servlet.ServletRequestListener)
  • Servlet Request Attribute Listener (javax.servlet.ServletRequestAttributeListener)
  • Http Session Listener (javax.servlet.http.HttpSessionListener)
  • Http Session Attribute Listener (javax.servlet.http.HttpSessionAttributeListener)

@WebListener is the easiest to use.
Example:
Registering ServletContextListeners.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.j2eereference;
 
import javax.servlet.annotation.WebListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
 
@WebListener
public class FooApplicationLifeCycleListener implements ServletContextListener {
  public void contextInitialized(ServletContextEvent event) {
    //do on application init
  }
 
  public void contextDestroyed(ServletContextEvent event) {
    //do on application destroy
  }
}

The type of listener is deduced from the list of interfaces that the class or its super class implements. If the class annotated with WebListener does not implement any of the listeners an error message will be logged.

Registering a Servlet using @WebServlet annotation

@WebServlet annotation is used to register a Servlet with a container. Below is the complete list of attributes that annotation encapsulates.

  • name
  • description
  • value
  • urlPatterns
  • initParams
  • loadOnStartup
  • asyncSupported
  • smallIcon
  • largeIcon

The attributes are simply bits of data that prior to Servlet 3.0 would go into <servlet> or <servlet-mapping> tags of web.xml. Now they can be specified in java code.
Note: the spec mandates either value or urlPatterns attribute be specified.
Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.j2eereference;
 
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.*;
 
@WebServlet(value="/hello", name="hello-servlet")
public class HelloServlet extends GenericServlet {
 
  public void service(ServletRequest req, ServletResponse res)
    throws IOException, ServletException
  {
    res.getWriter().println("Hello World!");
  }
}

After the successful build, a compile class will be created in WEB-INF/classes folder.Accessing http://localhost:8080/sample/hello should render the below text (‘sample’ is app name here).

1
Hello World!

Using @WebInitParam with @WebServlet
The @WebInitParam annotation provides a means of specifying initialization parameters for servlets and filters.
The annotation defines the following attributes:

  • name
  • value
  • description

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.j2eereference;
 
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.annotation.*;
 
@WebServlet(value="/hello",
initParams = {
   @WebInitParam(name="param1", value="Hello "),
   @WebInitParam(name="param2", value=" World!")
})
public class HelloServlet extends GenericServlet {
 
public void service(ServletRequest req, ServletResponse res)
throws IOException, ServletException
{
PrintWriter out = res.getWriter();
out.println(getInitParameter("param1"));
out.println(getInitParameter("param2"));
}
}

Accessing the servlet at http://locahost:8080/sample/hello will render (‘sample’ is the web-app name here)

1
Hello World!

Registering a Filter with @WebFilter annotation

The @WebFilter annotation has the following attributes

  • filterName
  • description
  • displayName
  • initParams
  • servletNames
  • value
  • urlPatterns
  • dispatcherTypes
  • asyncSupported

As mandated by the spec Resin expects that value, urlPatterns or servletNames will be specified.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.j2eereference;
 
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
 
@WebFilter(value="/hello",
initParams = {
@WebInitParam(name="message", value="Servlet says: Hello World!")})
public class TestFilter implements Filter {
private FilterConfig _filterConfig;
public void init(FilterConfig filterConfig)
throws ServletException
{
_filterConfig = filterConfig;
}
 
public void doFilter(ServletRequest req,
ServletResponse res,
FilterChain chain)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();
out.print(_filterConfig.getInitParameter("message"));
}
 
public void destroy() {
// destroy
}
}

Metadata specified in WebFilter are available via FilterConfig object, so the output of http://localhost:8080/sample/hello will render the following output.

1
Servlet says: Hello World!

 

Filed Under: Servlets

Servlet Quiz

February 8, 2013 By j2eereference Leave a Comment

Servlet Quiz

Start

Congratulations - you have completed Servlet Quiz.

You scored %%SCORE%% out of %%TOTAL%%.

Your performance has been rated as %%RATING%%


Your answers are highlighted below.
Question 1
In which file do we define a servlet mapping?
A
web.xml
B
servlet.xml
C
mapping.xml
D
deployment.xml
Question 2
Servlets and JavaServer Pages have become so popular that they are now supported directly or with third-party plug-ins by most major Web servers and application servers.
A
true
B
false
C
can not say
D
None of these
Question 3
What is the limit of data to be passed from HTML when doGet() method is used?
A
1k
B
2k
C
4k
D
8k
Question 4
The tasks – authentication-blocking of requests, data compression, logging and auditing – are performed by
A
servlet filter
B
servlet config
C
servlet context
D
servlet container
Question 5
Which of the following can be used to store client side user state information while avoiding any impact due to the users web browser configuration ?
A
Cookies
B
URL rewriting
C
HttpSessions
D
Hidden tags
Question 6
Which of the following is not true about Servlets?
A
They are instantiated every time a request is made.
B
They are a mechanism used by the class loader to download applets.
C
They can be used instead of CGI scripts.
D
They require a web browser that supports JDK 1.1
Question 7
Dynamic interception of requests and responses to transform the information is done by
A
servlet filter
B
servlet context
C
servlet config
D
servlet container
Question 8
The include() method of RequestDispatcher
A
includes resource of file like servlet, jsp or html
B
sends a request to another resource like servlet, jsp or html
C
appends the request and response objects to the current servlet
D
None of the above
Question 9
Using relative paths to reference resources in the same context root makes your Web application more flexible.
A
false
B
true
C
can't say
D
None of the above
Question 10
What is the servlet ?
A
Client side program
B
Server side program
C
Both are true
D
None of these
Question 11
How many ServletContext objects are available for an entire web application?
A
One each per servlet
B
One each per request
C
One each per response
D
Only One
Question 12
Which of the following describe ways that dynamic information can be made available to all servlet requests sent to an application
A
Make the information available from a singleton
B
Store the information in the ServletContext
C
Store the information in an HttpSession
D
Store the information in a Properties file
Question 13
Choose correct ansewrs
1. Servlet is a  Java technology based Web component.
2. Servlets are platform-independent 
3. Servlet has run on Web server which has a containers
4. Servlets interact with Web clients via a request/response using HTTP protocol. 
A
1,2,3,4
B
1,2,3
C
1,3,4
D
1,2,4
Question 14
The life cycle of a servlet is managed by
A
servlet context
B
servlet container
C
the supporting protocol (such as http or https)
D
all of the above
Question 15
All servlets must implement the Servlet interface of package:
A
java.servlet
B
javax.servlet
C
.servlet
D
All are same
Question 16
Servlet A receives a request that it forwards to servlet B within another web application in the same web container. Servlet A needs to share data with servlet B and that data must not be visible to other servlets in A's web application. In which object can the data that A shares with B be stored?
A
HttpServletResponse
B
HttpServletRequest
C
ServletContext
D
HttpSession
Question 17
Servlet mapping defines
A
an association between a URL pattern and a servlet
B
an association between a URL pattern and a request page
C
an association between a URL pattern and a response page
D
All of the above
Question 18
A developer wants a web application to be notified when the application is about to be shut down. Which two actions are necessary to accomplish this goal? (Choose two.)
A
include a listener directive in a JSP page
B
configure a listener in the TLD file using the element
C
include a element in the web application deployment descriptor
D
configure a listener in the application deployment descriptor, using the element
E
include a class implementing ServletContextListener as part of the web application deployment
Question 19
The getSession() method with ‘true’ as its parameter [ getSession(true) ] it will return the appropriate session object when
A
the session is completed
B
the session object is passed to another method
C
the session does not exists
D
the session is existing
Question 20
Which three are true about the HttpServletRequestWrapper class? (Choose three.)
A
The HttpServletRequestWrapper is an example of the Decorator pattern.
B
The HttpServletRequestWrapper can be used to extend the functionality of a servlet request.
C
A subclass of HttpServletRequestWrapper CANNOT modify the behavior of the getReader method.
D
An HttpServletRequestWrapper may be used only by a class implementing the javax.servlet.Filter interface.
E
An HttpServletRequestWrapper may modify the header of a request within an object implementing the javax.servlet.Filter interface.
Once you are finished, click the button below. Any items you have not completed will be marked incorrect. Get Results
There are 20 questions to complete.
←
List
→
Return
Shaded items are complete.
12345
678910
1112131415
1617181920
End
Return
You have completed
questions
question
Your score is
Correct
Wrong
Partial-Credit
You have not finished your quiz. If you leave this page, your progress will be lost.
Correct Answer
You Selected
Not Attempted
Final Score on Quiz
Attempted Questions Correct
Attempted Questions Wrong
Questions Not Attempted
Total Questions on Quiz
Question Details
Results
Date
Score
Hint
Time allowed
minutes
seconds
Time used
Answer Choice(s) Selected
Question Text
All done
Need more practice!
Keep trying!
Not bad!
Good work!
Perfect!

Filed Under: Servlets

ServletConfig and Initialization Parameters

July 24, 2012 By j2eereference Leave a Comment

ServletConfig

When the container initializes the servlet it makes a unique ServletConfig for it.Its main job is to give us init parameters.

The container reads the servlet init parameters from the Deployment Descriptor and gives them to the ServletConfig and then passes the ServletConfig to the servlet’s init() method.

Methods of the ServletConfig interface

The following methods can be called on the ServletConfig object:

getInitParameter(String)

This method returns a String containing the value of the named initialization parameter,Return value will be null if the parameter does not exist.

Enumeration getInitParameterNames()

This method returns the names of the servlet’s initialization parameters as an Enumeration of string. This method will return an empty Enumeration if the servlet has no initialization parameters.

getServletContext()

This method returns a reference to the ServletContext in which the caller is executing.

getServletName()

This method returns the name of this servlet instance. Servlet name can be assigned in the web application deployment descriptor.

 

Initialization Parameters

In case you want to put a certain value (an email address for example) in your servlet, a better option would be to configure it in the Deployment Descriptor(web.xml) rather than hard-coding it in the servlet class.
The getInitParameter() can be called on the ServletConfig object to return the init parameter but only once init() is called.

Example for getting init parameters from ServletConfig

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.j2eereference.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
 
public class TestServletConfig extends HttpServlet{
 
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
 ServletException{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("Testing ServletConfig and init parameters");
 
java.util.Enumeration e=getServletConfig().getInitParameterNames();
while(e.hasMoreElements()){
out.println("param name = "+e.nextElement());
}
 
out.println("main email is "+getServletConfig().getInitParameter("adminEmail"));
}
}

 

The web.xml file for the above servlet is shown below :

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<web-app 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/web-app_2_4.xsd”
version=”2.4″>
<servlet>
<servlet-name>ParamTesting</servlet-name>
<servlet-class>com.j2eereference.j2ee.TestServletConfig</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@209.97.166.197</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ParamTesting</servlet-name>
<url-pattern>/Tester.do</url-pattern>
</servlet-mapping>
</web-app>

Filed Under: Servlets

SingleThreadModel in Servlet

June 29, 2012 By j2eereference Leave a Comment

SingleThreadModel

Here we are going to discuss about SingleThradModel in Servlets. As we know that servlets are server side components that help us for developing web application on server side. Servlets are used to process multiple requests simultaneously.

First lets see what is mutithreadModel :

When we instantiate servlet then instance variable created, as a result it will be used over multiple client request,hence same
instance is shared across multiple clients.

As single instance is shared by all clients so there are chances that same instance variable is modified by many clients and hence giving undesirable result .

To avoid this concurrency, we use SingleThreadModel.

How To make single thread model

By default servlet is multithreaded . Single Thread Model ensures that servlet handles only one  request at a time.When your class is implemented SingleThreadModel no two threads run simultaneously in  service() method .

To use SingleThreadModel in servlet you have to implement SingleThreadModelIntetface. public interface SingleThreadModel. SingleThreadModel ensures that servlet handle only one request at a time.Every time a new instance of servlet is
created for each client request.It is also called thread safe.

It is a marker interface which does not have any body.

Single thread model is not used generally as it slow down the performance and increases overhead as new instance of the servlet is created for each and every new request.

Let’s take an example for SingleThreadModel in handling database connection as it is useful here to process one request at one time

Example demonstrating SingleThreadModel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.j2eereference.servlet;
 
 import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class SingleThreadModelExample extends HttpServlet implements SingleThreadModel {
 
Connection conn = null;  
  Statement stmt = null;
 
public void init() throws ServletException
{
try
{
// load the driver
Class.forName(driver).newInstance();
   conn = DriverManager.getConnection(url,userName,password);
}
catch (Exception e)
{
}
}
 
  public void doGet(HttpServletRequest request, HttpServletResponse response)
                               throws ServletException, IOException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    stmt = conn.createStatement();
    updateString = "update Persons set name = 'shobhna' where id=12"
    stmt.executeUpdate(updateString1);
    conn.commit();
  }
 
  public void destroy() {
stmt.close();
conn.close();
    }
   }
}

Note that SingleThreadModel does not solve all thread safety issues. For eg, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. This is the main reason due to which SingleThreadModel is deprecated. This interface is deprecated in Servlet API version 2.4.

We can use Synchronized block and synchronized method to obtain threadsafe Servlet.

Filed Under: Servlets

Generic servlet

June 25, 2012 By j2eereference Leave a Comment

GenericServlet Class

Before we start  let us first discuss what is servlet.

Servlet and servlet types

Servlet: Java servlets are server side components that are used for developing server side programs that runs on a server.

There are two types of servlets

  1. GenericServlet
  2.  HttpServlet

Generic Servlet

Generic servlet as name suggest doesn’t depend on particular type of protocol . In other words, generic servlet is a protocol independent servlet. thus,it contains only the generic features which a servlet should have.

It is an abstract class as it contains one abstract method service(ServletRequest request ServletResponse response).
This is an abstract class, So it is required that all the subclasses must implement service () method.

GenericServlet implements the Servlet and ServletConfig interfaces
GenericServlet must import javax.servlet package

Let us Consider the following GenericServlet example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.j2eereference.servlet;
 import java.io.*;
import javax.servlet.*;
 
public class GenericServletExample extends GenericServlet
{
  public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("Example of generic servlet");
 
out.close();
}
 
public void destroy() {
log("inside destroy() method");
}
 
}

service(ServletRequest req, ServletResponse res) : This method is called by servlet container when a request  is invoked by the client,after that request of client is processed by the servlet and response object is returned to the client as a result.

It is the service method where we write our business logic.In addition to service method generic servlet has some more methods like log, init and destroy.

1) Public void init(ServletConfig config)
As we already know this method is user for initializing the servlet

2)public void log(String msg)
This method is used for writing messages to log file.

3)Public void destroy()
This method is used for destroying servlet.

HttpServlet

HTTPServlet is an abstract class extends Generic Servlet and as a result inherits properties of generic servlet.
It is defined in “javax.servlet.http” package .HttpServlet is a HTTP protocol specific servlet.
In HttpServlet mostly doGet() or doPost() methods are needed to be overridden to handle the GET or POST requests.

In order to create a Servlet , a class should extend HttpServlet and override goGet() and doPost() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.j2eereference.servlet;
 
  import java.io.*;
  import javax.servlet.*;
  import javax.servlet.http.*;
 
public class SomeServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
 
    PrintWriter out = response.getWriter();
    out.write("Example of HttpServlet");
    // Use "out" to send content to browser
  }
}

Difference between GenericServlet and HttpServlet

1)The main difference between Genericservlet and HttpServlet is , GenericServlet is protocol independent and HttpServlet is protocol dependent.

2)HttpServlet have methods that support cookies and session where as GenericServlet doesn’t have.

3)GenericServlet do not have doGet() and doPost() method while in HttpServlet you have to override atleast one method doGet() and doPost() .

4)GenericServlet is a superclass of HttpServlet.

5)GenericServlet is an abstract class so you have to override Service method where as in case of HttpServlet you have to override at least one method of doGet(), doPost(),doPut(), doDelete(), init(), destroy(),getServletInfo().

Filed Under: Servlets

Servlet FAQ

January 3, 2011 By j2eereference 3 Comments

What is Servlet ?

Servlets are server side programs , they are request and response oriented program. Suppose you enter something in the form and submit it, Then who is processing your request ? Someone has to pick up the details you have entered in the form.

Servlet is the server side program which handles all the request and redirect to the result page.

What is the difference between getSession(true) and getSession(false) ?

When you say getSession(true), this method will check whether already a session is existing for the user. If a session is existing, it will return that session object, otherwise will create a session object explicitly and return to the cilent.

When you say getSession(false), this method will check whether a session is existing. If yes, then it returns the reference of that session object, otherwise it will return null.

What is load on startup element in web.xml file ?

We can specify the order in which we want to initialize various Servlets.Like first initialize Servlet1 then Servlet2 and so on.This is accomplished by specifying a numeric value for the <load-on-startup> tag. <load-on-startup> tag specifies that the servlet should be loaded automatically when the web application is started.

The value is a single positive integer, which specifies the loading order. Servlets with lower values are loaded before servlets with higher values.

What is Session Tracking?

Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user. period of time

Difference between ServletContext and ServletConfig

ServletContext is for the whole web-app but the ServletConfig is for one particular Servlet.

The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.

The ServletContext parameters are specified for an entire application and are available to all the servlets within that application.

Example :

ServletConfig Parameters

<servlet>

<servlet-name>FirstServlet</servlet-name>

<servlet-class>FirstServlet</servlet-class>

<init-param>

<param-name>MaxLength</param-name>

<param-value>25</param-value>

</init-param>

</servlet>

ServletContext Parameters

<context-param>

<param-name>AdminEmail</param-name>

<param-value>admin@209.97.166.197</param-value>

</context-param>

Difference between RequestDispatcher’s forward method and HttpServletResponse’s sendRedirect method

The forward method of RequestDispatcher will forward the ServletRequest and ServletResponse that it is passed to the path that was specified in getRequestDispatcher(String path). This method is useful for communicating between server resources. Because the request and response are forwarded to another resource all request parameters are maintained and available for use.

Example using forward:

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

RequestDispatcher rd = request.getRequestDispatcher(“pathToResource”);

rd.forward(request, response);

}

In case of  sendRedirect(String path) method the client will build a new request and submit it to the server. All previous parameters stored in the request will be unavailable. The client’s history will be updated so the forward and back buttons will work.

Example using sendRedirect:

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.sendRedirect(“pathToResource”);

}

Filed Under: Servlets

Servet- Life Cycle

December 31, 2010 By j2eereference 1 Comment

 

 Servlet life cycle defines how a servlet is loaded, instantiated, initialized and handles requests from the clients.

Loading and Instantiating: –

Loading and instantiation can occur when the container is started. When the servlet engine is started, the servlet container loads the servlet class using normal Java class loading facilities. After loading the Servlet class, the container instantiates it

Initialization :-

After the class is Loaded and Instantiated, the servlet engines initalize it by calling the following method:

public void init(ServletConfig config)  throws ServletException

In the method init, the config object is an instance of ServletConfig class. The config object contains initialization parameters and a ServletContext instance. The initialization parameters are specific to each servlet and configured in the deployment descriptor as part of the definition of the servlet.

Initialization parameter to the servlet is defined in the deployment descriptor file web.XML like following:

1
2
3
4
5
6
7
8
9
10
&lt;servlet&gt;
&lt;init-param&gt;
    &lt;param-name&gt;Emp_id&lt;/param-name&gt;
    &lt;param-value&gt;1&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
    &lt;param-name&gt;Emp_name&lt;/param-name&gt;
    &lt;param-value&gt;John&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;/servlet&gt;

Processing Request :-

 After initialization, the servlet is able to handle client requests.

Destroying :-

The servlet engine stops a servlet by invoking the servlet’s destroy() method. The destroy() method runs only one time during the lifetime of the servlet and this is the end of the servlet.

After a servlet’s destroy() method is invoked, the servlet engine unloads the servlet, and the Java virtual machine eventually performs garbage collection on the memory resources associated with the servlet.

Following three methods are known as servlet life cycle methods.

 1)           public void init(ServletConfig config) throws ServletException

 2)           public void doGet(HttpServletRequest req, HttpServletResponse rsp)  throws ServletException, IOException

                OR

               public void doPost(HttpServletRequest req, HttpServletResponse rsp)  throws ServletException, IOException 

3)            public void destroy()

Filed Under: Servlets

First Servlet

December 16, 2010 By j2eereference Leave a Comment

Why Servlet is different from traditional Java program ?

If you write a ‘traditional’ program and run it , then it is cleared from memory when you finish running it. It does its job then exits. And so it is with a java program that you run from the command line under the java command.

But if you’re running a web server, where lots of users request for the same page, you really don’t want a piece of code to keep dropping out of memory to be reloaded yet again a few milliseconds later as your next user comes along, as that would be hugely inefficient. So on a web server, when running Java, you may use the servlet approach

First Servlet

A servlet is just a JAVA class. And we know how to write a java class as bellow.

Public class className {

// Properties and Methods

}

But in case of servlet, the class should be a subclass of javax.servlet.http.HttpServlet . So creating servlet is just creating a class which extends javax.servlet.http.HttpServlet.

 

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;

Public class myFirstServlet extends HttpServlet {

// Properties and Methods

}

Notice that we have imported three packages,

1)      java.io.*;   // This contains classes for all standard input output operations

2)      javax.servlet.*; // This contains classes to make servlet working.

3)      javax.servlet.http.*; //This contains HttpServlet class , which is  extending  in our class

Servlet Methods

A servlet class should contain at least one method to handle the client request.  It could be name as doGet or doPost depends on the type of request we need to process. Notice that,

1)      The method should be public

2)      Return nothing.

3)      It accepts two parameters ,  HttpServletRequest object and HttpServletResponse object

4)      Method should throw IOException and ServletException.

 The method signature is

 public void doGet(HttpServletRequest req, HttpServletResponse rsp)  
               throws ServletException, IOException {  
   // … handle GET requests  
 }

Depending on the request type, get / post container invokes the corresponding doGet() or doPost() method.

doGet is the default method. This default method could be called by the following ways.

1)    Users click on a link,

2)    User enters a URL into the browser’s address bar.

3)     HTML FORMs with METHOD=”GET” specified in the FORM tag

 

 

doPost method could be called by HTML FORMs with METHOD=”POST” specified in the FORM tag

 

Difference between doGet and doPost method

Following are the difference between doGet and doPost method.

1)    In doGet user entered information are appended with the URL. But in case of doPost information will send as form. Hence if you want to send some sensible data like user name and password doPost is the preferable method for security reasons.

2)    doGet request can be use for bookmark as it uses URL but doPost can’t be used as bookmark.

3)    GET has restrictions on the size of the parameters sent. While Post doesn’t have the size restriction.

Filed Under: Servlets

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.