Monday, June 18, 2012

Servlets

Servlets

SERVLETS

Introduction :
Client Server Application
Web-Based Application
1. In this we have to divide the application into 2 parts,one part we have to install in server machine and another part in client machine.

2. When you modify the application you have to re-install the client software in all the client machines.

3. We can use C, C++, java etc to develop client server application.


4. There is a limit for client server application in terms of accessibility.
1. We can place the entire application in the server itself and access this application with the help of web browser.

2. When you modify the application no modification in the client machines.


3. We can use servlets, JSP, ASP, PHP, Perl Script etc. to develop the web application.

4. It is unlimited(accessibility of the users)


Web Clients :

1. Internet Explorer
2. Netscape Navigator
3. Opera
4. Mozilla

Web Servers :

1. Tomcat
2. Any Application Servers

Technologies :

1. JSP
2. Servlets
3. PHP
4. ASP
5. Perl Script

Application Servers :

1. Web logic
2. JBoss
3. JRun
4. Oracle 9i
5. Web Sphere
6. E-matrix
7. Pramathi
Steps to Install Tomcat

1. Make sure that j2sdk is installed in your machine and paths and classpath are set and is running properly.
2. Double click on Jakarta-tomcat-5.0.16.
3. Click on next.
4. Click on I Agree.
5. Click on next.
6. Change the destination folder to d:\tomcat5.0 and click on next.
7. Change the port number to 9999, give username and password and click on next.
8. Click on install.
9. Uncheck two options and click on finish.
10. Start the server and open the browser and type the following http://localhost:9999.

Simple example of Html :

<html>
<head></head>
<body>
<font color="red">
<h1> Welcome to Javayom.blogspot.com </h1>
</font>
</body>
</html>

The above file consists of a Html code with simple welcome note. You have just type the above thing in notepad and save it as a .html. Then using one of the
browser in your system just open that?.

Program Trace :

<html> : used for starting and ending of a html file.
<head> : used for starting and ending of a header in the html file.
It consists of different types of tags such has
<body> : used for starting and ending of body in the html file. All the coding part will be available here only..
<h1> : used for making the heading of the thing.
<font> : used for formatting the text with different things such as color, size etc.
Difference between Web-Server and Application-Server
Client Server Application
Web-Based Application
1. Web Server has web container which gives the support for web components called "servlets" & "jsp"


2. Examples of Web Servers :
° Apache Tomcat
° Java Web Server
° Roxen Web Server
° Zeus WebServer






3. Services of Web container :
° Networking
° Threading
° Streams
° Declarative Security
° JSP Support
° Resource Management
1. Application Server as 2 categories, one is web container and another is EJB container. Web container supports JSP and servlets & EJB container supports EJB components.

2. Examples of Application Server :
° Web logic
° Web Sphere
° JBoss
° JRun
° Oracle 9i
° Resin
° Orien
° Pramathi
° E-matrix etc

3. Services of EJB container :
° Networking
° Threading
° Streams
° Resource Management
° Transaction Management
° Security
° Persistence
° Timer Service
° Web Services
Directory structure of Web-application

Note : One and only one instance will be created for each servlet because servlets are following Singleton Design Pattern.

» Servlet interface is the root for all the servlets.
» Each servlet class should implement Servlet interface directly or indirectly.
» Sun has given servlet classes one is GenericServlet and second is HttpServlet.
» GenericServlet is direct sub-class of Servlet interface
& is implementing all the methods of Servlet interface except service 
(ServletRequest,ServletResponse) method.
» GenericServlet is protocol independent (i.e. we can use any protocol)
to send the request.
» HttpServlet is sub-class of GenericServlet & is implementing abstract
service(ServletRequest, ServletResponse) method in GenericServlet.
» HttpServlet has two service() methods, one is with pubic specifier &
is taking ServletRequest & ServletResponse as parameters, second with 
protected HttpServletRequest & HttpServletResponse as parameters.
» In addition to these 2 service () methods HttpServlet has 7 protected 
doXXX() methods with HttpServletRequest & HttpServletResponse
as parameters :
o doGet(HttpServletRequest, HttpServletResponse)
o doPost(HttpServletRequest, HttpServletResponse)
o doHead(HttpServletRequest, HttpServletResponse)
o doPut(HttpServletRequest, HttpServletResponse)
o doDelete(HttpServletRequest, HttpServletResponse)
o doTrace(HttpServletRequest, HttpServletResponse)
o doOptions(HttpServletRequest, HttpServletResponse)
» The above 7 are Http methods used to send the request from client.
» The following is the way to specify the http method :
    <form action="/login. do" method="post">
    </form>
» The default method is get().

Second Servlet Example :

1.) second.html
<html>
   <body>
    <center>
    <font size=6 color=red face="monotype corsiva">

</font><br><br>
     <form action="/yom.do" method="get">
         <input type="text" name="fname">
         <input type="text" name="lname">
         <input type="text" name="email">
         <input type="submit" value="Show">
     </form>
   </body>
</html>



2.)   MyServlet2.java 
package com.javayom.servlets;
 
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet
{
  String fn,ln,em;
  public void service(HttpServletRequest req,

      HttpServletResponse res)
            throws IOException,ServletException{
  fn=req.getParameter("fname");
  ln=req.getParameter("lname");
  em=req.getParameter("email");
  res.setContentType("text/html");
  PrintWriter out=res.getWriter();
  out.println("<h2>Hi.."+fn+" "+ln);
  out.println("<h2>Your email is"+em);
  Enumeration e=req.getHeaderNames();
  while(e.hasMoreElements())
  {
     String hn=e.nextElement().toString();
     out.println("<h3>"+hn);
     String hv=req.getHeader(hn);
     out.println("::"+hv);
  }
  out.println("<h3>Auth type"+req.getAuthType());
  out.println("<h3>Method"+req.getMethod());
  out.println("<h3>Remote User"+req.getRemoteUser());
  out.println("<h3>charEncoding."+

 req.getCharacterEncoding());
  out.println("<h3>Content-type"+req.getContentType());
  out.println("<h3>Contentlength"+

         req.getContentLength());
  out.println("<h3>servername"+req.getServerName());
  out.println("<h3>Protocal"+req.getProtocol());
  out.println("<h3>Serverport"+req.getServerPort());
  out.println("<h3>RemoteAddr"+req.getRemoteAddr());
  out.println("<h3>Remotehost"+req.getRemoteHost());
  out.println("<h3>Remoteport"+req.getRemotePort());
  out.println("<h3>local addr"+req.getLocalAddr());
  out.println("<h3>Local name"+req.getLocalName());
  out.println("<h3>Localport"+req.getLocalPort());
  out.println("<h3>is secure"+req.isSecure());
    Locale lc=req.getLocale();
  out.println("<h3>"+lc.getCountry());
  out.println("<h3>"+lc.getLanguage());
  out.println("<h3>"+lc.getVariant());
}
}



3.)   web.xml 
<web-app>
  <servlet>
        <servlet-name>myser</servlet-name>
        <servlet-class>com.javayom.servlets.MyServlet2

</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>myser</servlet-name>
        <url-pattern>/yom.do</url-pattern>
  </servlet-mapping>
</web-app>
Basic flow of the Servlet

» In World Wide Web(www) we are using http protocol to send the request & receive the responses.
» Here we using web browse (application) to send the request to the web server & receive the response from web server.
» Web server is an application which is used to receive the requests from web-clients, upon processing the requests and
send the response to the web-client.
» Http protocol makes the communication between web-browser and web-server.
» The request we are sending using http protocol is called as Http-request
and is having 2 parts. One is called Http-request header and second is Http-request body.
» Response we are getting using http protocol is called Http-response and is having 2 parts. One is called Http-response
header and second is Http-response body.
» Http protocol is a stateless protocol, i.e. it doesn't maintain client's conversational state i.e. it won't remember what
happen in the pervious request.
» Http is build upon TCP\IP.
» TCP is responsible to control the transmission of data from one machine to other.
» IP is responsible to carry the data from one machine to other. 
Servlet Example

Files Required : 
1. first.html
2. FirstServlet.java
3. web.xml

1. first.html :
<html>
   <body>
      <center><br><br>
      <font color="red" size="5">

JavaYom

</font >
      <form action="/login.do">
          Enter Name :
          <input type="text" name="ur_name">
          <input type="submit" value="Submit">
      </form>
      </center>
   </body>
</html>
        
2. FirstServlet.java :
package com.javayom;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse
response) throws IOException,
ServletException
{
//1.take the data
String username=request.getParameter("ur_name");
//2.process
username="Hello ! "+username+" Welcome to Servlet First Program?";
//3.send response back to client
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println(username);
out.close();
}
}
3. web.xml :
<web-app> 
   <servlet> 
     <servlet-name>first</servlet-name>        
     <servlet-class>

com.javayom.FirstServlet

</servlet-class> 
   </servlet>       
   <servlet-mapping>        
     <servlet-name>first</servlet-name>        
     <url-pattern>/login.do</url-pattern>      
   </servlet-mapping>       
<web-app> 
        
Steps to run the Servlet Program : 

1. Compile the servlet file :
a. Set the classpath for servlet-api.jar [ d:\tomcat5.0\common\lib\servlet-api.jar ]
b. javac -d . *.java

2. Deployment Steps :
a. Copy the first.html to webapps\ROOT\
b. Copy the "com" folder to ROOT\WEB-INF\classes\
c. Update the web.xml
d. Start the Tomcat server.
e. Open the internet explorer and type http://localhost:9999/first.html

Servlet can be referred by the container with 2 names :
a. Servlet-name (Used by container)
b. Servlet-class ( -do- )
c. Url-pattern (Used by user)
Servlet Life Cycle


Servlet have the following 3 life cycle methods :
1.init()
2.service()
3.destroy()

»Servlet life cycle management will be done by container.
»In servlet life container does the following things :
a. Creating the servlet instance.
b. Calling the life cycle methods.
c. Destroying the servlet instance.
»Init() method will be called by the container to initialize servlet instance, this will happen only once in servlet life.
»ervice() method will be called by the container to provide the service for the given request, this will be called "n" number of times based on the number of requests coming.

»Destroy() will be called by the container to destroy the instance.

When you send a request to the servlet first-time, the following steps will happen :
1.Container identify the servlet class for the given request with the help of url-pattern in web.xml.
2.If url-pattern found then servlet name will be taken
else
give an error back to client
3.With servlet-name container identifies the servlet-class.
4.Container search for servlet-class in WEB-INF \classes folder or its sub-folders if any package structure.
5.If servlet-class found
Load the class into the memory
else
give an error back to the client.
6.Create the Instance of servlet by calling default constructor.
7.Container creates ServletConfig object.
8.Container reads the init parameters specified in the web.xml and associates with the Config object & also associates context object which is created at server startup.
9.Container calls the init() method by passing ServletConfig as parameter.
10.Container creates a new thread or obtains thread from the pool.
11.Container creates HttpServletRequest , HttpServletResponse objects.
12. Container calls service(HttpServletRequest, HttpServletResponse) method by passing request & response as parameters.
13.Code inside the service method will be executed & response will be given to the client.

Second request onwards container will do the following things :
1. Container identify the servlet class for the given request with the help of url-pattern in web.xml If url-pattern found then
               servlet name will be taken
                       else
               give an error back to client
2. With servlet-name container identifies the servlet-class.
3. Container search for servlet-class in WEB-INF \classes folder or its sub-folders if any package structure.
4. If servlet-class found
            Load the class into the memory
                else
            give an error back to the client.
               
5. Container creates a thread or takes already created thread form the pool.
6. Container creates HttpServletRequest, HttpServletResponse objects.
7. Container calls service(HttpServletRequest, HttpServletResponse) method by passing request & response as parameters.
8. Code inside the service method will be executed & response will be given to the client.

Container Behavior when a servlet is called :
» Container always tries to call HttpServlets's public service() method.
» When your not overriding this in your servlet HttpServlet public service will be called.
» When your overriding this in your servlet, your's servlet's service() method with ServletRequest & ServletResponse will be called.
» Instead of overriding service(ServletRequest ,ServletResponse) in your servlet, when you override service(HttpServletRequest,HttpServletResponse),
container calls HttpServlet's public service method and that in turn calls your servlet's service(HttpServletRequest,HttpServletResponse) .
» Instead of overriding both the service methods when you override doXXX() methods, container calls HttpServlet's public service(), that in turn calls protected service() and that decides http method associated with the http request & invokes the doXXX() in your servlet.
» When the corresponding doXXX() method is not their an error page will be sent to the client with the status code - 405.

No comments:

Post a Comment