Friday, 15 November 2013

Servlet Core Concept



Servlet

Introduction

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Advantages Of Servlet Over CGI:-
CGI Technology enables webserver to call an external program and pass Http request information to external program to process the request .For Each request , it starts with new Process.
While in Servlet,
The web container create threads for handling the multiple request to the servlet.since threads have a lots of benefits over process.

Servlet API

Two packages:
1-javax.servlet
2-javax.servlet.http represents  interfaces and classes for the Servlet API.
Interfaces in javax.servlet packages:-
1-Servlet
2-ServletRequest
3-ServletResponse
4-RequestDispatcher
5-ServletContext
6-Filter
7-FilterConfig
8-FilterChain
Classes in javax.servlet packages:-
1-Generic Servlet

Life Cycle Of Servlet

Web container maintains the life cycle of the Servlet.
1-Servlet classes are loaded
2-Servlet Instances are created
3-init method is invoked.
4-service method is invoked.
5-destroy method is invoked.
Steps to create and run the servlet using Tomcat Server and command prompt:
Create directory as given below:
Web-app(context-root)
                                           WEB-INF
                                                           Classes(class files)
                                                            lib
                                                            web.xml
                 HTML
                 Images/css etc.
Configure the web.xml and  paste the servlet jar file in side the JRE/lib/ext folder

How Servlet Works:-

The server checks if servlet is requested for the first time:-
If
 Yes , web container does the following task:-
Loads the servlet
Instantiates the servlet
Calls the init method to pass the request and response
Else
Calls the service method passing the request and response
The web container calls the destroy method when it need or server  undeploy the project or server stops.
How web container handles the request:-
1-Map the request  with servlet in web.xml.
2-create request and response  object for this request.
3-calls te service method on thread
4-public service method internally call the protected service method.
5-The protected service method calls the doGet() method depending upon the type of request.
6-the doGet() methodgenerates the response and it passes to the client.
7-After sending the response,the web container deletes the request and response objects

RequestDispatcher Interface

The request dispatcher interface provides the facility of dispatching the request to another resources it may be html,servlet,jsp.
This interface can also be used to include the content of another resource also .
Two methods
1-public void forward()
2-public void include()




Difference between GET and POST:-


History:
Parameters remain in browser history 
because they are part of the URL
Parameters are not saved in browser history.
Bookmarked:
Can be bookmarked.
Can not be bookmarked.









Hacked:
Easier to hack for script kiddies
More difficult to hack
Restrictions on form data type:
Yes, only ASCII characters allowed.
No restrictions. Binary data is also allowed.
Security:
GET is less secure compared to POST because data sent is part of the URL. So it's saved in browser history and server logs in plaintext.
POST is a little safer than GET because the parameters are not stored in browser history or in web server logs.
Restrictions on form data length:
Yes, since form data is in the URL and URL length is restricted. A safe URL length limit is often 2048 characters but varies by browser and web server.
No restrictions



Usability:
GET method should not be used when sending passwords or other sensitive information.
POST method used when sending passwords or other sensitive information.
Visibility:
GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.
POST method variables are not displayed in the URL.
Cached:
Can be cached
Not cached

Idempotent:
Get Request is Idempotent.
Post is not Idempotent.

Note:- 

 Imagine an operation that retrieves a particular database record for display. The URL might be something like ".../showOrder?orderID=123456" and is implemented with a GET. Idempotency means that accessing the URL one time or multiple times yields the same result. Clearly it does in this case - accessing this URL gives you the same result every time you access it. It retrieves the web page that shows the record. You can hit reload in the browser as many times as you want - the result is always going to be exactly the same page.

Now, POST is generally used to change something, e.g. inserting a new record into a database. If you have just submitted a form that adds a new order record to the database, and if you then hit Reload (in other words, you access the same URL again), you'd be inserting another record. That means the result would not be the same. That's why browsers generally ask the user before reloading a page that was the result of a POST - because POSTs often change something, and doing the same change twice is usually not what the user wants. (As an aside, that's also the reason of existence for the PostRedirectGet technique. It allows you to submit something with POST, and then show a page that can be reloaded without problems.)
[ November 23, 2007: Message edited by: Ulf Dittmer ]

ServletContext Interface


An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param> element.
<web-app>
……..
<context-param>
  <param-name>c_name</param-name>
  <param-value>Jenesys Technology Pvt Ltd,Bangalore</param-value>
  </context-param>…
<web-app>
And in any servlet class whatever would be configured in web.xml we can get the values mentioned.
For Example:-
ServletContext sercon=getServletContext();
            String name2=sercon.getInitParameter("c_name");
//for getting a number of contextparam values…

·  ServletContext context=getServletContext();  
·  Enumeration<string> e=context.getInitParameterNames();  
·        
·  String str="";  
·  while(e.hasMoreElements()){  
·      str=e.nextElement();  
·      out.print("<br> "+context.getInitParameter(str));  
·  }  

Difference between ServletConfig and ServletContext

The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole web application.


Attribute in Servlet

  ServletContext context=getServletContext();  
  context.setAttribute("company","IBM"); 

  ServletContext context=getServletContext();  
  String n=(String)context.getAttribute("company");  

Cookies in Session Tracking


Cookie is a mechanism to maintain the state of an user
Session simply means a particular interval of time.
Session Tracking is a way to maintain state of an user. Http protocol is a stateless protocol. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.


Why use Session Tracking?

To recognize the user.

Session Tracking Techniques

There are four techniques used in Session tracking:
  1. Cookies
  2. Hidden Form Field
  3. URL Rewriting
  4. HttpSession

1)     Cookies

A cookie is a small piece of information that is persisted between the multiple client requests.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.


Cookie cook=new Cookie("url","Jenesys technology Pvt. Blre");
            cook.setMaxAge(60*60);//1 hour
            response.addCookie(cook);
            out.print("cookie has been created");

Advantage of Cookies

  1. Simplest technique of maintaining the state.
  2. Cookies are maintained at client side.

Disadvantage of Cookies

  1. It will not work if cookie is disabled from the browser.
  2. Only textual information can be set in Cookie object.

2-Hidden Form Field

In case of Hidden Form Field an invisible textfield is used for maintaing the state of an user. In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.

Disadvantage of Hidden Form Field:

  1. It is maintained at server side.
  2. Extra form submission is required on each pages.
  3. Only textual information can be used.

 

3)URL Rewriting

We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??

Advantage of URL Rewriting


  1. It will always work whether cookie is disabled or not (browser independent).
  2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting


  1. It will work only with links.
  2. It can send Only textual information
For EG.-
out.print("<a href='servlet2?uname="+n+"'>visit</a>");  

4) HttpSession interface

In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks:
  1. bind objects
  2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.

How to get the HttpSession object ?


The HttpServletRequest interface provides two methods to get the object of HttpSession:
  1. public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.
  2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface


  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it.
                     HttpSession session=request.getSession();  
          session.setAttribute("uname",n);  
@another Servlet ..
                 HttpSession session=request.getSession(false);  
     String n=(String)session.getAttribute("uname");

Filter

A filter is an object that is used to perform filtering tasks such as conversion, log maintain, compression, encryption and decryption, input validation etc.
 A filter is invoked at the preprocessing and postprocessing of a request. It is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet. So it will be easier to maintain the web application.

Usage of Filter


  • recording all incoming requests
  • logs the IP addresses of the computers from which the requests originate
  • conversion
  • data compression
  • encryption and decryption
  • input validation etc.

Advantage of Filter


  1. Filter is pluggable.
  2. One filter don't have dependency onto another resource.

Filter API

Like servlet filter have its own API.The javax.servlet package contains the three interfaces of Filter API
  1. Filter
  2. FilterChain
  3. FilterConfig

1) Filter interface


For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a filter.
  1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  2. public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain): doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
  3. public void destroy():This is invoked only once when filter is taken out of the service.

How to define Filter

We can define filter same as servlet. Let's see the elements of filter and filter-mapping.
  1. <web-app>  
  2.   
  3. <filter>  
  4. <filter-name>...</filter-name>  
  5. <filter-class>...</filter-class>  
  6. </filter>  
  7.    
  8. <filter-mapping>  
  9. <filter-name>...</filter-name>  
  10. <url-pattern>...</url-pattern>  
  11. </filter-mapping>  
  12.   
  13. </web-app>  

Note:- For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an advantage over servlet-name element i.e. it can be applied on servlet, JSP or HTML.
Useful Example Of Filter:-

will update soon....



Important Question:-

we all know marker interface does't have any methods...but it has some functionalities.. how will it get fuctionality..(dont tell jvm provides that functionalities)
and
can we create marker interface(that has some functionality)
Answer:-
A marker interface doesn't have any functionality. Marker interfaces are used by other code to test for permission to do something. For example, the Serializable interface is used by the implementation of serialization like this:
  1. if (theObject instanceof Serializable) {  
  2.      // Do something  
  3. } else {  
  4.     throw new NotSerializableException();  



  5. }  

Servlet with Annotation (feature of servlet3):

At any stage you are required to give the information to the container by the web.xml file you can create yourself web.xml file, this file should be store in the WEB-INF folder.
When we are using the servlet 3.0 specifications it depends on the element metadata-complete value by true/false whether the container will use web.xml or annotations in the web.xml descriptor. The true value of attribute specifies that the annotation will not be processed by the container and web fragments,
 in such case all the metadata information is provided by the web.xml file to the container and the false value of attribute or the absence of element metadata-complete specifies that the annotations and web fragments will be used by the container. 

If you use annotation, deployment descriptor (web.xml file) is not required. But you should have tomcat7 as it will not run in the previous versions of tomcat. @WebServlet annotation is used to map the servlet with the specified name.

@WebServlet("/Simple") 
public class Srvlet_Using_Annotation extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                            throws ServletException, IOException { 
         
 
        response.setContentType("text/html"); 
        PrintWriter out=response.getWriter(); 
         
        out.print("<html><body>"); 
        out.print("<h3>Hello Servlet</h3>"); 
        out.print("</body></html>"); 
    } 
}
This is a simple Servlet 3.0 application using annotations for servlet, filter, and content listener.



The servlet reads the initial parameter, a request attribute and a context attribute and provides the result.

@WebServlet(name="mytest",
    urlPatterns={"/"},
    initParams={ @WebInitParam(name="message", value="my servlet") } )
public class TestServlet extends HttpServlet {
    public void init(ServletConfig config) throws ServletException {
        //read the context attribute
        ...
    }
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        ...
    } }
@javax.servlet.annotation.WebServlet is an annotation specifying the metadata for given servlet. In this case, it specifies the url pattern and an init-param. Note:You need to extend javax.servlet.http.HttpServlet.

For More details Please go through the following link:-
to download Servlet 3.0 pdf file


Classpath setting for servlet to make it run by command promt:-
javac –d “dir_of_servletclass_if_not_in_same_dir” –cp “path_of_jar;You_can_add_another_jar_also_after_putting_semicolon” classname.java

 

No comments:

Post a Comment