Tuesday, 26 March 2013

hello world servlet example

hello world servlet example:                                                           by, madhav
















web.xml




     <servlet>
  <servlet-name>gmr</servlet-name>
  <servlet-class>madhav.SaiHaiResource</servlet-class>

  </servlet>

  <servlet-mapping>
  <servlet-name>gmr</servlet-name>
  <url-pattern>/hai</url-pattern>
  </servlet-mapping>
</web-app>



1)   once u develop a application, the container will create the instance of SaiHaiResource  and it call automatically init() method in it.

2)  if client made a request url like: http://localhost:8080/sayhai/hai

3)  than the container will check the url pattern, if is matching than will check appropriate
    servlet mapping name, and it creates new thread .

4)   the newly created thread will executed on service method on that servlet instance.  


SaiHaiResourc.java




package madhav;

import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SaiHaiResource extends HttpServlet{

       public void doGet(HttpServletRequest req,HttpServletResponse res)
       {
              try
              {
                     res.setContentType("text");
                     PrintWriter out=res.getWriter();
                     out.println("hai how r u");
              }
              catch(Exception e)
              {
                    
              }
       }
}
 


       public void doGet(HttpServletRequest req,HttpServletResponse res)


This is life cycle method available in HttpServlet  . call by the container after getting request, response objects from the server.

This two objects are created by the server by the time of requested by the client for a resource.

hear initially container call the servvice method,from their it wil call the doGet (), doPost() based on request method type.



output:











Note:

hear i am trying to call  a static resource available is server.


hai.html




<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
hai  how r u?
</body>
</html>



If client made a request  like : http://localhost:8080/sayhai/hai.html


the server will automaticaly pick up that resource and send back to the client.


output:

























No comments:

Post a Comment