Happy Diwali
happy diwali

Saturday, 7 June 2014

Basics on Servlets tutorial




Servlet :
Servlet technology is used to create web application.Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
 uses of Servlets
1.    better performance: because it creates a thread for each request not process.
2.    Portability: because it uses java language.
3.    Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage collection etc.
4.    Secure: because it uses java language
features of  Servlet 2.5
  • A new dependency on J2SE 5.0
  • Support for annotations
  • Loading the class
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications
Server  It is a running program or software that provides services.
There are two types of servers:
  1. Web Server
  2. Application Server
Web Server
Web server contains only web or server container. It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB.
Example of Web Servers are: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc.
Example of Application Servers is:
  1. JBoss Open-source server from JBoss community.
  2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.
  3. Weblogic provided by Oracle. It more secured.
  4. Websphere provided by IBM
Content Type  Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP header that provides the description about what are you sending to the browser.
There are many content types:
  • text/html
  • text/plain
  • application/msword
  • application/vnd.ms-excel
  • application/jar
  • application/pdf
  • application/octet-stream
  • application/x-zip
  • images/jpeg
  • video/quicktime etc.

Server API

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
  1. Servlet
  2. ServletRequest
  3. ServletResponse
  4. RequestDispatcher
  5. ServletConfig
  6. ServletContext
  7. SingleThreadModel
  8. Filter
  9. FilterConfig
  10. FilterChain
  11. ServletRequestListener
  12. ServletRequestAttributeListener
  13. ServletContextListener
  14. ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
  1. GenericServlet
  2. ServletInputStream
  3. ServletOutputStream
  4. ServletRequestWrapper
  5. ServletResponseWrapper
  6. ServletRequestEvent
  7. ServletContextEvent
  8. ServletRequestAttributeEvent
  9. ServletContextAttributeEvent
  10. ServletException
  11. UnavailableException
Interfaces in javax.servlet.http packageThere are many interfaces in javax.servlet.http package. They are as follows:HttpServletRequest
  1. HttpServletResponse
  2. HttpSession
  3. HttpSessionListener
  4. HttpSessionAttributeListener
  5. HttpSessionBindingListener
  6. HttpSessionActivationListener
  7. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
  1. HttpServlet
  2. Cookie
  3. HttpServletRequestWrapper
  4. HttpServletResponseWrapper
  5. HttpSessionEvent
  6. HttpSessionBindingEvent
  7. HttpUtils (deprecated now)
What is web application  web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request.

Installation tomcat
àClick on setup file ànextàAgreànext
àModify  http1.1 port  no(any other server using same port number may get chance of errors  )
àJustify and select path of JDK
àSelect tomcat Installation path
àok
Description : After the installation creating several  folders
Conf  folder  :
àThis folder contains several configuration files to be supported inside configuration
Lib  : In case of java jar files are Library files
àMajorly servlet-api,jsp-api, annotations-api etc are avalible these are developed by sun microsystems
Logs  All login messages related to web application
webapp :  inside three folders
1)docs     2)manager     3)root
Bin  : bin folder contains binary files
è  Tomcat developed by apache it is open source
Checking  : Open the browser and make http request
Ex :
 Type http: //localhost : 7070/
We can display the successful installation of tomcat
Developing the Servlet :
Inside webapp we can developed two types
1)    Static resources : If the project doesn’t having any jsp or servlet  then its called as static web applications
2)   

 

How Servlet works

It is important to learn how servlet works for understanding the servlet well. Here, we are going to get the internal detail about the first servlet program.

The server checks if the servlet is requested for the first time.
If yes, web container does the following tasks:
·loads the servlet class.
·instantiates the servlet class.
·calls the init method passing the ServletConfig object
else
·calls the service method passing request and response objects
The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project.

How web container handles the servlet request?
The web container is responsible to handle the request. Let's see how it handles the request.
·maps the request with the servlet in the web.xml file.
·creates request and response objects for this request
·calls the service method on the thread
·The public service method internally calls the protected service method
·The protected service method calls the doGet method depending on the type of request.
·The doGet method generates the response and it is passed to the client.
·After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation.

Simple program :
App1 :
package COM.LARA;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet {protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out=response.getWriter();
            String s1=request.getParameter("param1");
            String s2=request.getParameter("param2");
            response.setContentType("text/html");
            out.println("param1 : " +s1);
            out.println("param2 : "+s2);
            }
}
web.xml :
 <servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-class>COM.LARA.Servlet1</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/Servlet1</url-pattern>
  </servlet-mapping>
  <servlet>
Servlet can be called as three ways
Through form action :
<form action='Servlet2'>
param1
<input type='text' name='param1'/> </br>
param2
<input type='text' name='param2'/></br>
<input type='submit'  value='submit'/>
</form>
Through hyper link :
<a href="Servlet2?param1=xyz&param2=123">call</a>
Through browser


Query String: After the question mark whatever is there that is query string
We can use query string three ways
Param1=123 & param2=456
1. foram action :Supplying the parameter value after ? mark  
<form action=”abc? Param1=123 & param2=456              “ method=’post’>

<input type='submit'  value='submit'/>                                               Query String
</form>
2.hyper link
<a href="Servlet2?param1=xyz&param2=123">call</a>
3.url browser;
http://localhost:7070/aPP1/ Servlet2?param1=xyz&param2=123
Constants of servlets :
mport java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletCon extends HttpServlet {
            protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            PrintWriter out=response.getWriter();
            response.setContentType("text/html");
            String s1=getInitParameter("con1");
            String s2=getInitParameter("drivaer");
            out.println("con1:" +s1);
            out.println("</br> driver :" +s2);
                       
            }
}

web..xml :

  <servlet>
    <servlet-name>ServletCon</servlet-name>
    <servlet-class>com.lara.ServletCon</servlet-class>
  <init-param>
    <param-name>con1</param-name>
  <param-value>1000</param-value>
  </init-param>
  
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletCon</servlet-name>
    <url-pattern>/ServletCon</url-pattern>
  </servlet-mapping>
</web-app>
àservlet wise constants are reading while registering the servlet inside web.xml
àOne servlet context can’t read the another servlet
àservlets can be declare servlet tag of inside web.xml by using <init-par am>
àTo read the constants of servlet by using inherited method getinitParameter ();
Constants of application : any servlet we can acess it.
It’s global to al servlets
Inside web.xml :
<context-param>
<context-param>
  <param-name>test</param-name>
  <param-value>25358</param-value>
  </context-param>

Servlet life Cycle :
The life cycle of a servlet consists of the following phases:
  • Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
  • Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.
  • Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
  • Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
  • Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.





Can servlet have a constructor ?
One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.
Methods in GenericServlet class. They are as follows:
1.    public void init(ServletConfig config) is used to initialize the servlet.
2.    public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet.
3.    public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed.
4.    public ServletConfig getServletConfig() returns the object of ServletConfig.
5.    public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
6.    public void init() it is a convenient method for the servlet programmers, now there is no need to call super.init(config)
7.    public ServletContext getServletContext() returns the object of ServletContext.
8.    public String getInitParameter(String name) returns the parameter value for the given parameter name.
9.    public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.
10.  public String getServletName() returns the name of the servlet object.
11.  public void log(String msg) writes the given message in the servlet log file.
12.  public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack trace.

HttpServlet class :

It’s subclass to Generic servlet Here service method can be implemented according to Http protocol behavior not only service method implemented lot of methods to be implemented all are specific Http Protocol.Http method has concreate method for Http protocol.HttpServlet is a abstract class inside in this class service method implemented

There are many methods in HttpServlet class. They are as follows:
1.    public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.
2.    protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.
3.    protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container.
4.    protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container.
5.    protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container.
6.    protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.
7.    protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by the web container.
8.    protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is invoked by the web container.
9.    protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is invoked by the web container.
10.  protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last modified since midnight January 1, 1970 GMT.


àHttp request we can submit in two ways
1.Through method=get
2.Through method=post
à If the method type is reading and get type we are using doGet() Method
è  If the method type is reading and post type we are using doPost() Method
è  Overide doPost() and doGet() methods it’s purly depending on servlet request.
è  By defult request method is doGet() method
è  While calling the doPost method but reuest type is get we get  Exception 
è  It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

HttpServlet declared abstract  :
The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write adoPost() method too.

Difference between GenericServlet and HttpServlet?

GenericServlet
HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.
An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers.
The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol.
HttpServlet only supports HTTP and HTTPS protocol.

Difference between doGet() and doPost()?

#
doGet()
doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information.
In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar.
2
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.
You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)
doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encrypted
Parameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance
doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6
doGet() should be idempotent. i.e. doget should be able to be repeated safely many times
This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe
This method does not need to be either safe
8
It allows bookmarks.
It disallows bookmarks.



Useage of  doGet()  and  doPost()
Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:
  • If data is sensitive
  • Data is greater than 1024 characters
If your application don't need bookmarks
Request dispatcher and

Should I override the service() method?
We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.
servlet context object
A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.

Difference between ServletConfig and ServletContext :

ServletConfig
ServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig parameter per servlet.
There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
The param-value pairs for ServletConfig object are specified in the <init-param> within the <servlet> tags in the web.xml file
The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file.

RequestDispatcher Interface

The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.
Request dispatcher is serverside request doesn’t knows client side request
It is protocol independent and very similar to generic servlet

The RequestDispatcher interface provides two methods. They are:
1.public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
2.public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response

àThere are two ways to create object of request disDispatcher
1.relative way by using request object
2.Absulte way by using Servlet ContextObject

How to get the object of RequestDispatcher 

The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher.

Syntax of getRequestDispatcher method

public RequestDispatcher getRequestDispatcher(String resource);


Difference between include() and forward() methods

include()
forward()
The RequestDispatcher include() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.
The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.
If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored.
The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
The include() method is often used to include common "boilerplate" text or template markup that may be included by many servlets.
The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page.


Difference between sendRedirect() and forward() methods

forward()
sendRedirect()
A forward is performed internally by the servlet.
A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
The  browser is completely unaware that it has taken place, so its original URL remains intact.
The browser, in this case, is doing the work and knows that it's making a new request.
Any browser reload of the resulting page will simple repeat the original request, with the original URL
A browser reloads of the second URL ,will not repeat the original request, but will rather fetch the second URL.
Both resources must be part of the same context (Some containers make provisions for cross-context communication but this tends not to be very portable)
This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Since both resources are part of same context, the original request context is retained
Because this involves a new request, the previous request scope objects, with all of its parameters and attributes are no longer available after a redirect.
(Variables will need to be passed by via the session object).
Forward is marginally faster than redirect.
redirect is marginally slower than a forward, since it requires two browser requests, not one.





happy diwali
happy diwali