在Java EE中接收复选框值

时间:2018-05-22 14:32:45

标签: java html post java-ee

我有这个简单的html表单代码:

<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>

当我在带有express的node.js应用程序中收到此发布请求时,我看到发布的对象有一个带有选中值的“name”数组。

当我在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");

}

name变量只包含已检查的第一个元素,我知道如何获取整个数组。我试过了

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

但是这告诉我左侧和右侧不兼容。

1 个答案:

答案 0 :(得分:0)

您可以使用getParameterValues()方法..

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[] myarr = request.getParameterValues("name");
        for(String s:myarr) {
            out.println("Name : " + s);
        }
}