Following is an example which describes how HttpServlet Class will use GenericServlet.
First.java
[java]package servletinterface;
import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("");
out.print("<b>Hey man, welcome to SPLesons.</b>");
out.print("");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
}[/java]
Where
First is the class and that is implementing Servlet, where init() method has been used once all over the code, Class
java.io.PrintWriter. Print formatted representations of objects to a text-output stream, implements all of the print methods found in
PrintStream.
out.println() will be used which means to print the data in browser.
web.xml
[java]
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>servletinterface.First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>[/java]
Following is the sample structure of the
web.xml file.
index.html
[java]
<center><a href="./hello">Invoke Generic Servlet</a></center>
[/java]
Output
When compile the program following is the output will be displayed.
When click on the link following message will be opened.