John D.
John D.

Reputation: 81

Why Java servlet returning null?

I'm trying to get values from html but it just gives null with either Post or Get commands. I'm also using Wildfly Application Server. When I submit it goes to the next page but the values seem 'null'.

PS: I added the servlet in xml file like this:

<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/dataServlet</url-pattern>
</servlet-mapping>

Servlet:

package webpackage;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/dataServlet")
public class DataServlet extends HttpServlet {


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

        // Get
        String combobox=request.getParameter("User");
        String value=request.getParameter("demo");

        PrintWriter writer = response.getWriter();

        // Build
        String htmlRespone = "<html>";
        htmlRespone += "<h2>User Id: " + combobox + "</h2>";
        htmlRespone += "<h2>User Id: " + value + "</h2>";
        htmlRespone += "</html>";

        // Return
        writer.println(htmlRespone);
        System.out.println(combobox);
    }
}

HTML:

<select name="User">
        <option selected="true" value="Example1">User1</option>
        <option value="Example2">User2</option>
        </select>
        <form method="post" action="dataServlet">
        <button type="submit">Change</button>
        </form>
        <h1></h1>
        <p id="demo">Example3</p>

Upvotes: 0

Views: 1660

Answers (1)

AxelH
AxelH

Reputation: 14572

The inputs should be in the <form> like this for User

    <form method="post" action="dataServlet">
        <select name="User">
            <option selected="true" value="Example1">User1</option>
            <option value="Example2">User2</option>
        </select>
        <button type="submit">Change</button>
    </form>

    <h1></h1>
    <p id="demo">Example3</p>

And this is the name attribute that is necessary (demo), note that I don't thing this will work woth a <p>, but you can use a hidden input to set a value in the form.

PS : be careful, you should use the same syntax, once you start with uppercase then with lowercase User demo

EDI : A w3schools form guide

Upvotes: 3

Related Questions