Sep 8, 2015

Sarvlets - Part 01

Web Servlet
Servlet ContainerBefore we concern about servlet containr we need to know what is the server?
ok when we load a web page using a web browser that web page comming from a web server. Web servers use HTTP protocal for transfer data between server and the client (browser).

generally web server send us to a static pages. That is not enough. Because we don't need always static pages. We need to dynamic pages ( web page based on user input). So that is done by servlet container (genarate dynamic pages).
So u can see that servlet container embeded inside Web Server. Servlet generate dynamic pages based on user input that pages send to the client by web server.

So a servlet is a component that is hosted in a servlet container to generate pages. The client interact with servlet by request/response.

The servlet container is responsible for the life cycle of the servlet, receives requests and sends responses, and performs any other encoding/decoding required as part of that.



POJO ( Plain Old Java Object )
POJO  is a normal Java object class (that is, not a JavaBean, EntityBean etc.)  and does not serve any other special role nor does it implement any special interfaces of any of the Java frameworks.

A servlet is defined using the @WebServlet annotation on a POJO, and must extend the
javax.servlet.http.HttpServlet class.
This is a sample definition of a servlet
1:  @WebServlet("/hello")  
2:  public class HelloServlet extends javax.servlet.http.HttpServlet {  
3:  //. . .  
4:  }  

Acording to above servlet client can interact with "HelloServlet" using the url "www.example.com/hello".
in here "/hello" is the url pattern. A servlet can have multiple url pattern. That kind of servlet can be definne as follow.
1:  @WebServlet(urlPatterns={"/hello", "/helloworld"})  
2:  public class HelloServlet extends javax.servlet.http.HttpServlet {  
3:  //. . .  
4:  }  

Then client can interact with this servlet by using two url pattern ("hello","helloworld").

HTTPServlet interface has some methods to override for handling the http requests.So what are http request types ?
Request Type Description
Get The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.
POST A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.
HEAD Same as GET, but transfers the status line and header section only.
PUT Replaces all current representations of the target resource with the uploaded content.
DELETE Removes all current representations of the target resource given by a URI.
CONNECT Establishes a tunnel to the server identified by a given URI.
OPTIONS Describes the communication options for the target resource.
TRACE Performs a message loop-back test along the path to the target resource.

so you can handle these request by servlet by overriding "doGet() , doPost() , doPut() ... ". Web developer more concern about the Get and Post method. So following example shows you how you handle Get request.
 @WebServlet("/hello")  
 public class Hello extends javax.servlet.http.HttpServlet {  
   @Override  
   protected void doGet(HttpServletRequest request,HttpServletResponse response) {  
     //. . .  
   }  
 }  

in here you can see that doGet method has two parameter

  • HttpServletRequest - capture web client request
  • HttpServletResponse  - capture the web client response
The request parameters; HTTP headers; different parts of the path such as host,port, and context; and much more information is available from HttpServletRequest.

The developer is responsible for populating the HttpServletResponse, and the container then transmits the captured HTTP headers and/or the message body to the client.

Following example show you how to populate sample response to client for a get request
 protected void doGet(HttpServletRequest request,HttpServletResponse response) {  
   try (PrintWriter out = response.getWriter()) {  
     out.println("<html><head>");  
     out.println("<title>MyServlet</title>");  
     out.println("</head><body>");  
     out.println("<h1>My First Servlet</h1>");  
     //. . .  
     out.println("</body></html>");  
   } finally {  
     //. . .  
   }  
 }  

in this example response object has method call getWriter(). That method returns PrintWriter object using that object we can create dynamic page content.

So, Now you now how to handle http request. So Now you think how to create dynamic page content acording to the user input. ok. one thing you need to know is there is a way to get request parameter. Request paramter is user data which is client send to server.

Following example will clear your doutes about above mentioned.

We are doing this example with NetBeans IDE. If you haven't it download from here.

  • First step open the netbean IDE and go to file -> New project -> click Java Web -> Wen Application then Click Next. Then Put a Name for the project then click next. Then click finish.
  • Then expand the project and Right Click on Source Packages -> New -> Servlet->Put a name and package name and finish. Now Your project will look like this.



  • Now you can run the project. Makesure "urlPattern = {"/"}" .
    Result will look like this.
  • Now modify the processRequest() method.
     protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
           throws ServletException, IOException {  
         response.setContentType("text/html;charset=UTF-8");  
         try (PrintWriter out = response.getWriter()) {  
           /* TODO output your page here. You may use following sample code. */  
           out.println("<!DOCTYPE html>");  
           out.println("<html>");  
           out.println("<head>");  
           out.println("<title>Servlet Index</title>");        
           out.println("</head>");  
           out.println("<body>");  
           out.println("<h1>Servlet Index at " + request.getContextPath() + "</h1>");  
           if(request.getParameter("name") != null){  
           out.println("<h1>My name is " + request.getParameter("name")+ "</h1>");  
           }  
           out.println("</body>");  
           out.println("</html>");  
         }  
       }  
    

    Now Run the project again. Now project result is Look like before. Now change the url by appending " ?name=Text". Check the following screenshot.


    Check the url, is that clear ?

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.