如何从Servlet获取JSP中的属性?

时间:2019-05-14 00:59:58

标签: java jsp servlets el

完成操作后,我想在我的JSP页面中获取请求属性。在我的doPost中,设置如下:

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

if(operation.equals("someAction")) {
  //Do something
} else if (operation.equals("otherAction")) {
  if (someParameter != null){
   //Doing a for loop
   //When loop is finished (so outside for loop)
      request.setAttribute("msg", "Attribute message");
      request.getSession().setAttribute("msg2","Session message");       
      request.getRequestDispatcher("/Absolute/path/Final.jsp").forward(request, response);
  }
}

在完成方法BUT之后,此代码完全不给我任何消息,如果我突然刷新页面,则会显示会话消息。我希望该消息立即显示,因此req.setAttribute看起来像我想要的。我添加了绝对路径,因为相对路径,程序进入了无限循环。

我的JSP的相关部分:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<p>
    Message from request: <b><%= request.getAttribute("msg") %></b>
    <br />
    Message from session: <b><%= session.getAttribute("msg2") %></b> //<---This is the only one that works (after refresh)
    <br />
    Message from EL: <b>${msg2}</b>
    <br />     
    Message from EL: <b>${msg3}</b>

</p>

这是我的jQuery代码:

$.ajax({
   type: "POST",
   url: "http://localhost:8080/MaJSPProject/MainServlet/*",
   dataType: 'JSON',
   data: {pTableData:JSON.stringify(TableData), operation:"submitLFoodTable", dropdownField: document.getElementById('dropdownField').value},
   success: function(msg){
       // return value stored in msg variable
       console.log(msg);
   }

});

我想念什么?

0 个答案:

没有答案