Example of Servlet and web.xml in java

Asked on November 29, 2014
How to create a servlet and web.xml and how to run this code in my pc. If possible please send me a proper code in steps.

Replied on December 14, 2014
Create a servlet code and web.xml

Step 1: create your servlet code i.e. MyServlet.java probably you can copy from here for demo use...

package programs;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws 

ServletException, IOException
String name= req.getParameter("name");
String age= req.getParameter("age");
String output= "Hello" +name+ "your age is" +age;
PrintWriter pw= res.getWriter();
pw.println("Hello "+name+" your age is "+age);

Step 2: now create a web.xml code



Step3: How to execute the code..
1- you need a server like tomcat or any other.
2- set the path for tomcat
3- copy the class file of MyServlet.java and paste it in the classes folder under the WEB-INF
4- now put the web.xml file parallel to the classes folder 

Step 4: Now create a html form to input the data..

Step 5: put the html file parallel to the WEB-INF folder

Step 6: run the html file.


Replied on December 17, 2014
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
  private String message;

  public void init() throws ServletException
      // Do required initialization
      message = "Hello World";

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
      // Set response content type

      // Actual logic goes here.
      PrintWriter out = response.getWriter();
      out.println("<h1>" + message + "</h1>");
  public void destroy()
      // do nothing.




Write Answer

©2024 concretepage.com | Privacy Policy | Contact Us