【问题标题】:Unable to print value of a label in a servlet无法在 servlet 中打印标签的值
【发布时间】:2014-12-30 09:48:09
【问题描述】:

我想获取我在 Web 表单中使用过的几个标签的值。我正在使用隐藏的输入字段来完成这件事,但是我无法通过 servlet 打印标签的值,因为我将 null 作为标签的值

以下是我用来测试的示例代码

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <form name = "testform" action="submit" method = "post">
        <label> AgeoftheChild </label>
        <input type="hidden" name="lblage" value="AgeoftheChild">

        <input  type = "radio" name="age" value="10">10 <br>
        <input  type = "radio" name="age" value="20">20 <br>
        <input type = "radio" name="age" value="30">30 <br>

        <input type="submit" name="sub" value="submit">
    </form>     
</body>

这是 submit.java servlet

public class submit extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    String age = request.getParameter("lblAge");

    try {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet NewServlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet NewServlet at " + age + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }


}

}

我想显示 AgeoftheChild 但输出为空

请帮助解决可能的问题

提前致谢

【问题讨论】:

    标签: jsp servlets


    【解决方案1】:

    第一次显示表单时,lblAge 为空(仍然没有表单提交)。只有在您提交表单后,lblAge 才会被填写。

    if (request.getMethod().equalsIgnoreCase("POST")) {
        ...
    

    (忽略大小写有点过头了。)

    【讨论】:

      【解决方案2】:

      您是否尝试过使用 HttpServlet 的 doPost 方法?

      【讨论】:

        【解决方案3】:

        在您的 HTML 页面中,您传递了 lblage,而在您的 servlet 中,您将其视为 request.getParameter("lblAge"); 因此,您需要更改标签的大小写以获取 servlet 中的值

        `request.getParameter("lblage");`
        

        在servlet中需要实现GenericServletHttpServlet中的方法,然后使用request对象从request中获取所需的参数或属性。

        在您的情况下,您需要实现doPost 方法。

        【讨论】:

        • 感谢您指出错误。我在“清洁和建造”之后运行了这个项目,但我又得到了同样的东西:(
        • String age = request.getParameter("lblAge");这一行放在response.setContentType("text/html;charset=UTF-8");之前,即你的servlet中的第一行,并在sop检查年龄值的帮助下。将方法更改为doPost 在答案中编辑
        猜你喜欢
        • 1970-01-01
        • 2020-07-04
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多