Home  >  Forum  >  Java EE
Post New Query

Example of Servlet and web.xml in java


joined on
October 13,2014
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.
joined on
March 15,2013
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;
//res.getWriter().write(output);
PrintWriter pw= res.getWriter();
pw.println("Hello "+name+" your age is "+age);
}
}

Step 2: now create a web.xml code


<servlet>
    <servlet-name>Link</servlet-name>
    <servlet-class>programs.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>Link</servlet-name>
    <url-pattern>/start</url-pattern>
</servlet-mapping>

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.

End..

joined on
September 16,2014
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
      response.setContentType("text/html");

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


--------------------------------------------------------------------


<servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/HelloWorld</url-pattern>
    </servlet-mapping>

Write Answer








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us