从request.getAttribute()

时间:2015-12-16 15:24:54

标签: java jsp servlets

我有一个.jsp文件,它通过post方法将数据发送到servlet,但是当我尝试通过request.getAttribute()访问servlet中的数据时,它打印出“null”

我的.jsp文件如下所示:

            <form name="update" action="UpdateServlet" method="post"
            accept-charset="utf-8">
            <label>Name:</label><input type="text" name="input_name"    id="input_name"><br>
            <label>Beschreibung:</label> <input type="text" name="input_beschreibung" id="input_beschreibung"><br>
            <input type="hidden" name="input_id" id="input_id">
            <input type="submit" value="Okay">
            <button type="button" onclick="closeDialog()">Abbrechen</button>
            </form>

我的servlet看起来像这样:

public class UpdateServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    System.out.println((String)request.getAttribute("input_id"));
    System.out.println((String)request.getAttribute("input_name"));
    System.out.println((String)request.getAttribute("input_beschreibung"));

    RequestDispatcher rd=request.getRequestDispatcher("LoadServlet");  
    rd.forward(request, response);

}

web.xml的一部分:

  <servlet>
  <servlet-name>UpdateServlet</servlet-name>
  <servlet-class>wochenplaner.UpdateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>UpdateServlet</servlet-name>
  <url-pattern>/UpdateServlet</url-pattern>
  </servlet-mapping>

我不明白为什么请求的属性为空。 提前谢谢!

3 个答案:

答案 0 :(得分:0)

您感到困惑request.getAttribute("")request.getParameter("")。你需要使用后者:

public class UpdateServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    System.out.println(request.getParameter("input_id"));
    System.out.println(request.getParameter("input_name"));
    System.out.println(request.getParameter("input_beschreibung"));

    RequestDispatcher rd=request.getRequestDispatcher("LoadServlet");  
    rd.forward(request, response);

}

请参阅此处进行进一步讨论:

https://stackoverflow.com/a/5243833/1356423

答案 1 :(得分:0)

试试这个:

request.getParameter("input_id");

答案 2 :(得分:0)

您应该使用request.getParameter()而不是request.getAttribute()

Difference between getAttribute() and getParameter()