index.html
<html> <body> <form action="./go"> <input type="submit" value="click here"/> </form> </body> </html>
Here just created submit button that is click here.
web.xml
<web-app> <servlet> <servlet-name>Demo</servlet-name> <servlet-class>Demo</servlet-class> </servlet> <servlet-mapping> <servlet-name>Demo</servlet-name> <url-pattern>/go</url-pattern> </servlet-mapping> </web-app>
Make sure that URL name should be match with HTML form that is /go.
Demo.java
import java.io.*; import javax.servlet.*; public class Demo implements Servlet{ ServletConfig config=null; public void init(ServletConfig config){ this.config=config; System.out.println("servlet is initialized:::"+config); } public void service(ServletRequest request,ServletResponse response) throws IOException,ServletException{ response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.print("<html><body>"); out.print(" <h1><b>welcome to Splessons</b></h1>"); out.print(" <h2><b>Example on Servlet Interface<b></h2>"); out.print("</body></html>"); } public void destroy(){System.out.println("servlet is destroyed");} public ServletConfig getServletConfig(){return config;} public String getServletInfo(){return "copyright 2007-2010";} }
Following is the code structure of life cycle methods.
Result will be as follows.