Abhishek Singh
Abhishek Singh

Reputation: 9765

response.sendRedirect does not preserve request attributes?

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

String branch =  req.getParameter("branch");
System.out.println(branch);
MOPMappingDAO dao = new MOPMappingDAO();
ArrayList<MOP> mops = dao.getMOP(branch);
System.out.println("No of MOPS " + mops.size());
req.setAttribute("mops",mops);
resp.sendRedirect("webpages/mopmapping.jsp");
}

Above is my controller code i am using resp.sendRedirect() so the request attribute are not preserved on my jsp code. Here is my jsp code

<%
ArrayList<MOP> mops = (ArrayList<MOP>)request.getAttribute("mops");
System.out.print(mops);
System.out.println(mops.size());
for(MOP mop : mops){ //searchResults }
%>

and i get a NullPointerException because mops is null. I can use request.forward() in this case but the url is not containing webpages/mopmapping.jsp. In that case for each refresh the operation //searchResults is done by controller.

Please provide with solution

Upvotes: 3

Views: 8033

Answers (3)

Monsif EL AISSOUSSI
Monsif EL AISSOUSSI

Reputation: 2456

To not loste your attributes use :

req.getRequestDispatcher("webpages/mopmapping.jsp").forward(request, response);

Instead of :

resp.sendRedirect("webpages/mopmapping.jsp");

Good luck

Upvotes: 4

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

A redirect is actually sending an instruction to the client to HTTP GET the redirected resource. So it is a completely new request/response cycle, that is why your attribute is lost.

Using the session partially solves the problem. You should take extra care to remove the thing you placed in the session, or it will stay as garbage (and if these accumulate under certain circumstances -not this case- they may cause memory leaks).

Frameworks solve this with the flash scope (googling it provides links such as this).

Depending on your use case, you should decide what is most appropriate, the session/flash scope or a forward.

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68413

You can do request forward after setting the URL in a request dispatcher

check this

http://www.javapractices.com/topic/TopicAction.do?Id=181

Upvotes: 0

Related Questions