0
votes

I was trying some basic Servlet Programming. I had created a basic Html form and on submitting it, wanted to invoke a servlet which prints the name entered by the user. I am posting the code below.

HTML: (it is in rootfolder -- webapps\helloworld\hello.html)

<html>
<body>
<form action="./hello" method="get">
Name: <input type="text" name="P1">
<input type="submit" value="Submit">
</form>
</body>
</html>

> web.xml (Location: webapps\helloworld\WEB_INF\web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
     <servlet>
         <servlet-name>hs</servlet-name>
         <servlet-class>HelloWorld</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>hs</servlet-name>
         <url-pattern>/hello</url-pattern>
     </servlet-mapping>
</web-app>

> Servlet Class (Location: webapps\helloworld\WEB_INF\classes\HelloWorld.class

import javax.servlet.*;
import java.io.*;
public class HelloWorld implements Servlet{ 
    public void init(ServletConfig sc)throws ServletException{
        //initialization code
    }
    public ServletConfig getServletConfig(){
        return null;
    }
    public void service(ServletRequest request, ServletResponse response)throws ServletException,IOException{
        String name=request.getParameter("P1");
        PrintWriter out = response.getWriter();
        out.println("Hello: "+name);        
    }
    public String getServletInfo(){
        return null;
    }
    public void destroy(){

    }
}

So whenever I type a name and click on submit, I am getting 'HTTP Status 404' error. Could you please tell me what I am doing wrong! Any help would be much appreciated. Thanks!

1

1 Answers

0
votes

In your HTML form you have to give the form action to your servlet "HelloWorld" specifically.Because form action is the one who show the path to Data

<html>
<body>
<form action="/HelloWorld" method="get">
Name: <input type="text" name="P1">
<input type="submit" value="Submit">
</form>
</body>
</html>

The HTTP 404 Not Found Error means that the webpage you were trying to reach could not be found on the server

or try this servlet code:

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading  Request Parameters";

    out.println(
                "<HTML>\n" +
                "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"+
                "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
                "<UL>\n" +
                "  <LI><B>P1</B>: "
                + request.getParameter("P1") + "\n" +"</BODY></HTML>");
  }
}