For more detailed overview on GenericServlet Click Here
First.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";} }
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
<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>
Following is the sample structure of the web.xml file.
index.html
<center><a href="./hello">Invoke Generic Servlet</a></center>
Output
When compile the program following is the output will be displayed.