简体   繁体   中英

html form processing in java servlet

I'm building a java servlet to respond to some HTML form. Here is the simple test form:

 <FORM action="http://somesite.com/prog/adduser" method="post">
    <P>
    <LABEL for="firstname">First name: </LABEL>
              <INPUT type="text" id="firstname"><BR>
    <LABEL for="lastname">Last name: </LABEL>
              <INPUT type="text" id="lastname"><BR>
    <LABEL for="email">email: </LABEL>
              <INPUT type="text" id="email"><BR>
    <INPUT type="radio" name="sex" value="Male"> Male<BR>
    <INPUT type="radio" name="sex" value="Female"> Female<BR>
    <INPUT type="submit" value="Send"> <INPUT type="reset">
    </P>
 </FORM>

On the server side I get the HttpRequest alright. But when I get the parameters like this:

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String firstName = req.getParameter("firstname");
    String lastName = req.getParameter("lastname");
    String sex = req.getParameter("sex");
    String email = req.getParameter("email");

}

Only the "sex" is ok. I've been at this for hours without understanding why "sex" is different from the rest. All other parameters are null. Ok it's the only "radio" type but is there a special way to get the parameters for the others?

Thank you!

In an HTML Form it is important to give your Input values the Name attribute, the ID attribute only helps Javascript in the page find your Input elements better.

I noticed that you missed Name attributes for your fist few Input elements.

You need to add the name attribute with the rest of the input tags, like you did with the sex input tag:

<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
          <INPUT type="text" id="firstname" name="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
          <INPUT type="text" id="lastname" name="lastname"><BR>
<LABEL for="email">email: </LABEL>
          <INPUT type="text" id="email" name="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM