Writing hello world program in servlet:

Writing the first web application.Follow the below steps,
Install Apache tomcat
set class path to apache\tomcat\lib\servlet-api.jar
copy the folder HttpServlet into the webapps folder inside the tomcat. This is known as deployment.
Files requird:

Index.html :
<form action="./hello" method="GET">
<input type="submit" value="click me"/>
-Here we use the GET method. So we have to override the same doGet() method in servlet.

This web.xml is known as deployment descriptor. It should be one per application. A dd can declare many servlets(inside the web-apps again add<servlet></servlet><servlet-mapping></servlet-mapping>)
The <servlet-name> ties the <servlet> element to the <servlet-mapping> element.
The <url-pattern> is the name that the client uses for a request.(here <url-pattern> is hello.do and in html also same action=”./hello.do”).

Servlet file:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class hello extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
PrintWriter out=response.getWriter();
out.println("<center><h1><font color='red'>Hello Client..,</font></h1></center>");
System.out.println("hello world");}}
Here is the HttpServlet and we override the doGet() method (as requested in index.html)
The content type is “text/html” tells the browser that the response contains simple text.
PrintWriter is used to print something in the browser.
The System.out.println(“hello world”); it will print in the server console not in the browser.
The request url:
here the server and client in the same machine. So we gave localhost. If the server will reside in another machine then we have to give the ip address of that machine.
8081 is the port number of tomcat.
HttpServlet is the root folder name.

Now create a GenericServlet:
For generic servlet all the file are same except the servlet file.
import javax.servlet.*;
import java.io.*;
public class MyGenericServlet extends GenericServlet{
public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException{
response.setContentType("text/html");// mime type
PrintWriter out=response.getWriter();
out.println("<center><h1><font color='red'>Hello Client..,</font></h1></center>");
System.out.println("hello Servlet");

No comments:

Post a Comment