Search code examples
javaservletsgetparameter

Servlet request.getParameter() returns null


I have read all the questions about this here, but I still do not have any progress. I want to pass the value from the input field to my servlet, but the servlet's request.getParameter returns null, instead of what is inputted. Here is my HTML:

<form method="post" action="MyHttpServletDemo" id="myForm">
    <input type="text" id="input" name="input1" placeholder="    Input coordinates...">
</form>
    <a href="welcome"><button type="button" id="vnes" onclick="Vnes()">Search</button></a>

Here is my .xml:

<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

And the Servlet:

public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      
      String value = (String) request.getParameter("input1");
      out.println("<h1>" + value + "</h1>");
   }

I tried this:

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
      PrintWriter out = response.getWriter();
      String value = (String) request.getParameter("input1");
      out.println("<h1>" + value + "</h1>");
   }

HTML:

<form method="post" action="/welcome" id="myForm">
    <input type="text" id="input" name="input1" placeholder="    Input coordinates...">
 <a href="welcome"><button type="button" id="vnes" onclick="Vnes()">Search</button></a>
</form>

And still does not work.


Solution

  • It worked! Here's the solution: HTML:

    <form method="get" action="welcome" id="myForm">
        <input type="text" id="pole" name="pole1" placeholder="    Input coordinates...">
        <button type="submit" id="vnes">Search</button>
    </form>
    

    .xml file:

    <servlet>
    <servlet-name>MyHttpServletDemo</servlet-name>
    <servlet-class>MyServletDemo</servlet-class>
    </servlet>
    
    <servlet-mapping>
    <servlet-name>MyHttpServletDemo</servlet-name>
    <url-pattern>/welcome</url-pattern>
    </servlet-mapping>
    

    Servlet:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/html");
          PrintWriter out = response.getWriter();
          String value = (String) request.getParameter("pole1");
          out.println("<h1>" + value + "</h1>");
    }