从servlet读取POST请求参数

时间:2014-04-08 06:44:13

标签: java servlets post

我发现了其他类似的问题,但我无法弄清楚为什么我无法从servlet读取POST请求参数(我有一个表单)(GET参数没问题)。因此,使用firebug,我可以看到表单中引入的参数值,但下面的system.out.println显示为null。

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        IPentahoSession userSession = PentahoSessionHolder.getSession();
        String username = userSession.getName().toString();
        openSql();
        response.setContentType(
                "text/html");
        PrintWriter pw = response.getWriter();

        pw.println(
                "<html>");
        pw.println(
                "<head><title>Hello Pentaho</title></title>");
        pw.println(
                "<body>");
        pw.println(
                "<h1>Hello " + username + " Pentaho </h1>");

        pw.println(
                "<form method=\"post\" action=\"HelloPentaho\" >"
                + "Nume: <input type=\"varchar\" name=\"param1\" value=\"\"> <br>"
                + "Nume raport original: <input type=\"varchar\" name=\"param2\" value=\"\"> <br>"
                + "Cale raport original: <input type=\"text\" name=\"param3\" value=\"\"> <br>"
                + "<input type=\"submit\" value=\"Trimite date in baza\">"
                + "</form> ");

        pw.println(
                "<h1> The selected parameters are: " + request.getParameter("param1") + " " + request.getParameter("param2") + " " + request.getParameter("param3") + "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<br /></h1>");
        pw.println(
                "</body></html>");

        String insert = "INSERT INTO PREFERINTE_UTILIZATOR (nume,nume_rap_org,cale_rap_org) values (?,?,?);";
        PreparedStatement pstmnt = conn.prepareStatement(insert);
        pstmnt.setString(1, request.getParameter("param1"));
        pstmnt.setString(2, request.getParameter("param2"));
        pstmnt.setString(3, request.getParameter("param3"));
        pstmnt.executeUpdate();

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(HelloPentaho.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(HelloPentaho.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

1 个答案:

答案 0 :(得分:0)

或修改您的doPost代码以在控制台中打印值并查看打印的内容。试试这个:

Enumeration enParams = request.getParameterNames(); 
while(enParams.hasMoreElements()){
 String paramName = (String)enParams.nextElement();
 System.out.println("Attribute Name - "+paramName+", Value - "+request.getParameter(paramName));
}