MY mENU


Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts

Saturday, 18 May 2013

Interfaces and Classes in Servlet

Interfaces in javax.servlet package:
  • Servlet
  • ServletRequest
  • ServletResponse
  • RequestDispatcher
  • ServletConfig
  • ServletContext
  • SingleThreadModel
  • Filter
  • FilterConfig
  • FilterChain
  • ServletRequestListener
  • ServletRequestAttributeListener
  • ServletContextLitstener
  • ServletContextAttributeListener
Classes in javax.servlet package:
  • GenericServlet
  • ServetInputStream
  • ServletOutputStream
  • ServletRequestWrapper
  • ServletResponseWrapper
  • ServletRequestEvent
  • ServletContextEvent
  • ServletRequestAttributeEvent
  • ServletContextAttributeEvent
  • ServletException
  • UnavailableException
Interfaces in javax.servlet.http package:
  • HttpServletRequest
  • HttpServletResponse
  • HttpSession
  • HttpSessionListener
  • HttpSessionAttributeListener
  • HttpSessionBindingListener
  • HttpSessionActivationListener
  • HttpSessionContext (deprecated now)
Classes in javax.servlet.http package:
  • HttpServlet
  • Cookie
  • HttpServletRequestWrapper
  • HttpServletResponseWrapper
  • HttpSessionEvent
  • HttpSessionBindingEvent
  • HttpUtils (depricated now)

Servlet Interface

Servlet Interface provides common behavior to all the servlet  Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to service the requests and to destroy the servlet and 2 non-life cycle methods.

Methods of servlet Interface: There are 5 methods in servlet interface. The init, service and destroy are the life cycle method these are invoked by the web container.
  • public void init(ServletConfig config) initializes the servlet. It is the life cycle method invoked by the web container only once.
  • public void service(ServletRequest request, ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container.
  • public void destroy() is invoked only once and indicates that servlet is being destroyed.
  • public ServletCofig getServletConfig() returns the object of ServletCofig.
  • public String getServletInfo() returns information about servlet such as writer, copyright,version etc.
Example:

 import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;

public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req, ServletResponse res)throws IOException, ServletException{
 res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html>");<body>");
out.print("<b>Hai</b>");
out.print("</html></body>");
}

public void destroy(){ 
System.out.println("Servlet is destroyed");
}

pulbic ServletCofig getServletConfig(){ 
return config;
}

public String getServletInfo(){
return "copyrith @ futureimpact"
}


Tuesday, 17 April 2012

Servlets Introduction


Servlets are Java technology’s answer to Common Gateway Interface (CGI) programming. They are programs that run on a Web server, acting as a middlevlayer between a request coming from a Web browser or other HTTP clientvand databases or applications on the HTTP server. Their job is to:


1. Read any data sent by the user. This data is usually entered in a form on a Web page, but could also come from a Java applet or a custom HTTP client program.

2. Look up any other information about the request that isvembedded in the HTTP request.
This information includes details about browser capabilitie,vcookies, the host name of the requesting client, and so forth.


3. Generate the results. This process may require talking to a database, executing an
RMI or CORBA call, invoking a legacy application, or computing the response directly.


4. Format the results inside a document. In most cases, this involves embedding the information inside an HTML page.


5. Set the appropriate HTTP response parameters. This means telling the browser what type of document is being returned (e.g., HTML), setting cookies and caching parameters,
and other such tasks.


6. Send the document back to the client. This document may be sent in text format (HTML), binary format (GIF images), or even in a compressed format like gzip that
is layered on top of some other underlying format.

Monday, 19 March 2012

What is Server-Side Includes (SSI)?


Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with a .shtml extension.

Saturday, 17 March 2012

HttpRequestHeader & HttpResponseHeader


List of httpRequestHeader & httpResponseHeader :

httpRequesHeaders are:

1.cookie
2.host
3.referer
4.accept
5.accept-language
6.accept-encoding
7.keep-alive
8.user-agent
9.connection
10.if-modified-since

“keep-alive” request header value holds a number (300) indicating for how many seconds the connection between browser & web-server should be alive.

httpResponseHeaders are:

1.Location
2.refresh
3.set-cookie
4.cache-control/pragma
5.content-encoding
6.content-lenth
7.content-type
8.last-modified

“location” Instead of sending response to requested browser /source browser which has given request, if you want to send to new browser then use httpResponseHeader called location.

Important response codes in Servlets

Frequent http response codes:

100-199: warnings or Information

200-299: success
300-399: Redirection
400-499: Incomplete processing
500-599: server error
200-success & document of response follows as web page response.
201-success but no response body.
301- Given request is moved to other web resources or websites permanently.
302: Given request to web-resource is forwarded or moved to other Web-resources of website temporarity.

Note: The http response status code 300-399 comes if given request is forwarded to other web sites from the original & actually requested web-sites.

401: The user who has given request if not authorised web-site / web-resource [error].
404: Requested web-resource is not found
500: Problem in web-xml code

Servlet Mapping

Servlet mapping:

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

Servlet Questions- Part4

What is the important packages in Servlet Api ?
            According to JAVA language API means set of classes & interfaces that comes in the form of packages.  Servlet –API:
1. javax.servlet:  (This package definers several classes and interfaces to develop sevlets from the scratch irrespective of any protocol )

2. javax.servlet.http: (This package defines several classes and interfaces to develop http based servlets.)


I can access internet hosted websites by typing domain name like www.myjavahub.com.

But our class room web-applications are not accessed in the same manner more over we are typing technical URL(http://localhost:8080/webappname/url) to access the web-resource of web-application can you explain the answer?            
      The ISP[Internet service provider] maintains a special registry called ”DNS registry” containing domain names mapped with the URL’s to open the home pages of website. When user gives request to web-site by typing “domain name” the actual URL. will be collected from the DNS registry using that URL it interacts with real web-resource of web-application using the internet network. Due to this reason we can just type domain name which acts as a logical name to access web-sites while working with websites that are hosted on the Internet. In class room level web-application since we don’t take the help of domain naming registry so we need to type complete URL having port no web-application name & etc technical details to interact with web-resources. Protocol is a set of rules followed by both parties who want to participate in communication.

http is a protocol that is given to transfer hypertext [text with hyper links ] between web browser software & web server software, vice-versa.

Can we write a default constructor for servlet ?
 Yes.But not recommended.  Because by default container generating default constructor.so we no need to write explicitly.

what is the use of HttpServletRequest ?
1. retrive html form parameres
2. retrive html header inforamtion
3. retrive cookies.
4. retrive html form parameres

 What is the use of HttpServletResponse object ?
Http response:
1. S: http response status code
2. C: http rensonse content
3. H: http response headers.
4. add cookies to the response.

How to refresh the webpage generated by servlet automatically at regular intervals?
response.set header(“refresh”,”5”);
by mention above statement , the browser will refresh automatically for every “5” seconds.

What is a buffer/cache & how to disable the buffer available in the browser while displaying response of a web-resource [servlet] in the browser window?Buffer is a temporary memory residing in browser & stores the response data given by web-server
By default browser enable buffering while receiving response from a web-server.
To disable this we can use “cache-control/pragma” response Headers as shown below from the service () method of servlet.
res.setHeader(“cache-control”,”no-cache”);//for http1.1 based web server
(OR)
res.setHeader(“pragma”,”no-cache”);//for http1.o based servers.

HttpservletRequest, HttpServletResponse are the interfaces. How did you say request, response parameters of service() methods as objects?     
             An interface reference variable points to implementation class object. Reference variable also becomes indirect object of implementation class.
In any servlet service(request,response) method request is not the object of HttpServletRequest interface, it is the object of class that implements HttpServletRequest interface. Similarly response is not the object of HttpServletResponse interface, it is the object of a class that implements HttpServletResponse. Both these classes will be given by the underlying Web-server/Application server.

what are different mime types are there in servlets ?
The following is the list of some common mime types:
1.text/html à html document
2.text/xhtml à xhtml document
3.text/xml à xml document
4.image/GIF à gif image fiel
5.text/jpeg à jpeg image file
6.application/pdf à pdf file
7.application/jar à jar file

What is the difference between PrintWriter stream object ServletOutputStream object .which are useful to write response content to browser from servlet.
PrintWriter is a character stream & sends the response to browser in the form of characters.
ServletOutputStream is a byte stream & sends the response to browser in the form of binary data.
Both stream objects must be prepared using response object & associated with response object.
We cannot see both stream objects in a single servlet.
To get PrintWriter object the code is
PrintWriter pw = res.getWriter();
To get ServletOutputStream object the code is
ServletOutputStream out = res.getOutputStream();
Character stream object is good for sending text response And Byte stream object is good for sending binary information like images as response.

Note :between these two PrintWriter is best one.

What are the important resources in Servlet WebApplication ?
1.static content
[All the static information we have to place with in the context root either directly or indirectly]
2.jsp pages
3.Servlet classes
4.Deployment Descriptor (web.xml)
5.Tag Liabraries.
6.Jar files
7.Java class Files

How many web.xml files in possible in one web application ?
for every web application we have to maintain only one web.xml and should be placed directly in WEB-INF folder.

ServletConfig and ServletContext Objects

ServetConfig object?

1. for every servlet web container creates one ServletConfig object to hold servlet level configuration information.
2. ServletConfig interface defines several methods to access this configurations information.
Ex: getInitParameter()
getInitParameterNames();
getSerlvetName();
getServletContext()

ServletContext object ?
1. for every web application web container creates one ServletContext object to hold application level configuration information.
2. ServlerContext interface defines several methods to access this information.
Ex: getInitParameter();

Difference between ServletConfig and ServletContext object ?




                ServletConfig
           
             ServletContext


ServletConfig object means it is the object of a class that implements ServletConfig interface.[ javax.servlet.ServletConfig]


Servlet context object means it is the object of a class that implements javax.servlet.ServletContext interface.

1 per servlet object so it is called right-hand object for servlet object.


It is one per web-application         

Every Servlet contains one ServletConfig object.

Common for all the web-resources of a web-application. So it is called Global memory of the web-application.


Web container creates ServletConfig object for servlet object when servlet object is created. web container destroys ServletConfig object  when its servlet object is destroyed.

web-container creates ServletContext object when web-application is deployed and destroys ServletContext  object when web-application  stopped (or)reloaded (or) undeployed.


ServletConfig object is useful to pass additional data to the servlet and to read additional data from the servlet like “logical name “ given to servlet and etc…

Using ServletContext object we can gather following details
1)Name and version of the underlying web server.
2)servlet API version implemented by web server.
3)Logical Names of all servlets available in web-application 4)”context parameters”   available in the web-application.


Servlet Questions-part3


How can we get ServletConfig object ?
1st way :
public class TestServlet extends HttpServlet
{
public void init(ServletConfig cg)
{
super.init(cg);
===== usage of cg here ======
}
}

2nd way :
public class TestServlet extends HttpServlet
{
public void init(ServletConfig cg)
{
ServletConfig cg=getServletConfig();
==== use cg here=====
}
}

Note : getServletConfig() is the public method avaialbe in GenericServlet class.

How can we creae ServletContext object ?
First way :
public class TestServlet extends HttpServlet
{
public void service(HttpServletRequest req ,HttpServletResponse response) throws ServletException, IOException
{
ServletConfig cg=getServletConfig();
ServletContext sc=cg.getServletContext();
====== usage of ServletContext object here ====
}
}

Second way :
public class TestServlet extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException
{
ServletConfig sc=getServletContext();
====== usage of ServletContext object here ====
}
}
Note : getServletContext() is public method available in javax.servlet.ServletConfig interface and 
javax.servlet.GenericServlet class.

When ServletConfig object will be create ? when it will be destroy ? What is the use?
ServletConfig object will be created along with servlet object& will be destroyed along with servlet object. When container creates, object of servlet it uses zero argument constructor. “ServletConfig” object is right hand object for servlet object”. To pass additional info to servlet or to gather info about servlet object programmer uses ServletConfig object.

When ServletContext object will be create?when it will be destroy ?what is the use ?
web-container creates ServetContext object when web-application is deployed. And destroys ServletContext object when web-application stopped (or) reloaded (or) undeployed.

There is a web server having 10 java based web applications out of these 10 web applications only 4 web-applications are in running mode ,6 web-applications are in stopped mode can you tell me how many ServletContext objects are currently available?  Since ServeltContext object will be destroyed when web-application goes to stopped mode there will be only 4 number of ServletContext objects.

There is a web-application deployed in a web server having 10 servlets .out of 10 servlets 3 servlets load-on-startup is enabled and other 3 servlets are requested from client. Can you tell me total how many servletConfig objects are available currently in the web application?
Since ServletConfig object will be created only when servlet object will be created there will be total 6 number of ServletConfig objects[3 for requested servlet objects,3 for other srevlets on which load-on-startup is enabled].
Note : ServletConfig object will not be created HTML and image web resources. Even though web application is created without servlets there will be ServletContext object for that web application.web container creates ServletContext object before creating any servlet object.
Why super.init (config) will be the first statement inside init(ServletConfig config) method.
This will be the first statement if we are overriding the init(config ) method by this way we will store the config object for future reference and we can use by getServletConfig() to get information about config object. if we not do this config object will be lost and we have only one way to get config object because servlet pass config object only in init method . Without doing this if we call the servletConfig method will get NullPointerException.

What's the difference between init() & init(ServletConfig) and Which is better ?
It is Better to use init(). If you use init() you have no such worries as calling super.init(config).
If you use init(servletconfig) and forgot to call super.init(config) then servletconfig object will not set and you will not get the servletconfig object.

What is wrong if i don't call super(ServletConfig) in the init(ServletConfig) ?
You may create a subclass which extends GenericServlet class. If you override init(ServletConfig) method and don't call super(servletConfig) then the ServletConfig reference is not stored in the GenericServlet and if we call getServletConfig() we get null. The reason we're advised to add super.init(config) is because GenericServlet.init(ServletConfig) stores a copy of the ServletConfig so that its getInitParameter() can forward the call to the ServletConfig object. If you override init(ServletConfig) in your own code you should add super.init(config) to preserve that functionality.

Another method of GenericServlet, init() is provided as a convenience. GenericServlet.init(ServletConfig) internally calls GenericServlet.init(). If you want to add functionality at init-time, you should do it by overriding init(). The default implementation of init(ServletConfig) will save the ServletConfig reference and then call your overriding init().

Can we override service(request,response) in HttpServlet ?
You can override service method in HttpServlet also.But not recommended. If you override service method in HttpServlet then call will go to service() method instead of doGet() or doPost() method. But this is not good practise. If the jsp form you mentioned

Then also call will go to service method of the servlet. Call don't go to doPost() method. you can call doPost() method explicitly from servive() method.
If the jsp form you mentioned

Now also call will go to service method of the servlet. Call don't go to doGet() method. you can call doGet () method explicitly from servive() method.

what is servlet collaboration?
(OR)
In how many ways two servlets can communicate?
communication between two servlet is called servlet collaboration which is achieved by 3 ways.
1. RequestDispatchers include () and forward() method .
2. Using SendRedirect()method of Response object.
3. Shared static or instance variables (deprecated)

Friday, 16 March 2012

Can we place only parameterized constructors in a servlet class?


 No.. Because Web-container creates object of our servlet class using zero argument constructor. If servlet class contains only parameterized constructor the java compiler does not generate zero argument constructor so web-container fails to create an object of servlet class. So a programmer must make sure that the servlet class is going to contain zero argument constructor explicitly or implicitly. Because web-container uses zero argument constructor to create object of a servlet.

Note: When java class is not having any constructor the compiler automatically generates zero argument constructor. If java class is having user-defined constructors the compiler does not generate the default zero argument constructor.

Different ways to develop servlets?

How can you develop a servlet?

                            (OR)
      What are different ways to develop servlets?

Every servlet is a java class.There are 3 ways to develop a servlet based on servlet-API.

 1.Take a public java class implementing javax.servlet. servlet interface & provide implementation for all the 5 methods of that interface.

 2. Take a public java class extending from javax.servlet. Generic servlet &provide implementation for abstract method called service(servlet request, servlet response) method.

 3. Take a public java class extending from javax.servlet.http servlet &amp;override either one of the                 7 doxxx() methods (or) one of the two service ()methods.

Difference between GET and POST ?




               GET
            
                   POST   


Designed to get the data from web server


Designed to send the data to web server    

Can send limited amount of data to the server along with request.


Can send unlimited amount of data to the server

Query string will be visible in the browser address bar due to this there is no data secrecy


Query string will not be visible in the browser address bar  due to this there will be data secrecy.       

Not suitable for file uploading


 Suitable for file uploading   

Can’t send the data by applying encryption


Can send the data by applying encryption.

Default  HttpRequest method for request is Get()


This  is not default

Use  doGet() mehod or service() to receive request  and to process request in HttpServlet

Use  doPost() method or service() method to receive request and to process the request.     
    

Get is idempotent

Post is not idempotent.


Difference between Web server and Application server?




           Web Server


      Application Server     

Manages and executes only web applications


 Manages and executes web applications , EJB Components and web enterprise applications 


Comes with only web container


Comes with web container ,EJB Container

Allows only Http Clients

Allows all types of java clients including Http Clients like Java App , AWT , Swing etc


Recognizes only war files as applications           

Recognizes WAR , JAR , EAR And RAR files as Applications.
  EAR = WAR + RAR


Gives less amount of middleware services

Gives more amount of middleware services (nearly 16)   


Examples : Tomcat , Resin , Jws , Pws     

WebLogic , WebSphere , JBoss , JRun , O10gAs         


Web Server implements only Servlet ,Jsp Api’s of J2EE Specification.

Application server implements all API’  



Can you explain Servlet Life Cycle methods ?


Servlet Life Cycle:
Life cycle diagram of servlet:


To perform operations related to these three events & to handle these event there are  3 life cycle methods.
   1.Public void init(-)  [Servlet object is just created.]
   
   2.Public void service (ServletRequest req, ServletResponse res)
                                [Servlet object is ready for request processing]

   3.public void destroy() [Servlet object is about to destroy.]

Life cycle methods of a servlet helps the programmer events that are raised on the servlet object.
Step 1:
                      init(-) is a one time execution method in the life cycle of servlet object. This method executes automatically when underlying web-container creates the servlet object. We place initialization logic in the init(-) method like creating JDBC connection object.

Step 2:
                   service(-,-) method is a repeatedly executing method for servlet object. This method executes automatically when servlet gets the request so we place request processing logic in this method.
If multiple requests are given to a servlet multiple times the service (-,-) method of that servlet executes.

Step 3:
             destroy()  is a one time execution life cycle method. This method executes automatically when servlet object is about to destroy. So we place un initialization logic in the destroy() method like closing JDBC connection.