Servlet first program


Prev Tutorial Next Tutorial

Servlet first program

Servlet programming is very simple but you need some basic knowledge for example interface, abstract class, exception handling.

Steps to write servlet program

  • Define web directory structure
  • Define .jsp/.html pages
  • Define servlet program, compile into classes folder
  • Define web.xml, into WEB-INF folder
  • Deploy the webroot into web server deployment folder location.
  • Start the server
  • Open web browser and invoke servlet/.html/.jsp.

Write a web applicaton to send hello word as response to client using servlet.

FirstServlet.java

import java.io.*;
import javax.servlet.*;
  
public class FirstServlet extends HttpServlet {  
  
  public void service(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
  {
   // get request parameter
   // business operation
   String resultvalue="<body bgcolor="cyan" text="red"> <h1> hello word</h1></body>";

   // prepare response
   resp.setContentType("text/html");
   printWriter out=resp.getWriter();

   // send response
   out.print(resultvalue);  
   out.close();  
   }  
} 

web.xml

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>s1</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  

</web-app>  

Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements