-4

Hello I am trying to create a simple servlet as follows

import java.io.*;
import javax.servlet.*;    
import javax.servlet.http.*;
public class Form extends HttpServlet
{
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {
     res.setContentType("text/html");
     PrintWriter p=res.getWriter();
     p.println("<html><head></head><body bgcolor=\"red\">The request came from"+req.getMethod()+"</body></html>");
    }

}

The req.getMethod() should return POST but is giving me a null value.

I am taking the request from an html file coded as follows.

   <html>

   <body>

   <form action="http://localhost:8080/Form" method="GET">

   First Name: <input type="text" name="name"/>

  <br>

   <input type="submit" value="Submit form "/>

  </form>

  </body>

  </html>

here is the web.xml file. Should I make any changes here.

 <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                    
  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
  version="3.0"   metadata-complete="true">

    <display-name>Welcome to Tomcat</display-name>
    <description>
     Welcome to Tomcat
    </description>

    <servlet>
     <servlet-name>Form</servlet-name>
     <servlet-class>Form</servlet-class>
    </servlet>

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

    </web-app>
Zia
  • 1,001
  • 1
  • 13
  • 25

1 Answers1

0

You can write this annotation to attach your servlet to your form:

@WebServlet("/Form")
public class Form extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... }
}

You will have to import javax.servlet.annotation.WebServlet.

Santiago Gil
  • 1,292
  • 7
  • 21
  • 52