Home » Java » Receive checkbox values in Java EE

Receive checkbox values in Java EE

Posted by: admin June 30, 2018 Leave a comment

Questions:

I have this simple html form code:

<html>
    <form method="post" action="http://localhost:7001/checkuser">
        <input type="checkbox" name="name" value="1">John</input>
        <input type="checkbox" name="name" value="2">Matt</input>
        <input type="checkbox" name="name" value="3">Chris</input>
        <input type="submit" name="sprawdz" value="Submit" />
    </form>
</html>

And when i receive this post request in a node.js app with express I see that the posted object has a “name” array with the checked values in it.

When I try this in a Java EE servlet:

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.sql.*;

public class NewServlet extends HttpServlet {

    private static final long serialVersionUID =1L;
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String name = request.getParameter("name");

}

The name variable only contains the first element checked, and I know how to get the whole array. I tried

String[] name = request.getParameter("name");

but this tells me that the left and right side are incompatible.

Answers: