output of try and catch block should be printed in 2 different jsp pages

StackOverflow https://stackoverflow.com/questions/23667029

  •  22-07-2023
  •  | 
  •  

سؤال

I am trying to print the output of a java file to a jsp file.

for(String x : list)
{
    try {
        output 1
    }
    catch {
        output 2
    }
}

The output 1 should go to x.jsp file The output 2 should go to y.jsp file

Where do I give response.Redirect(x.jsp) and response.Redirect(y.jsp)?

If I give each statements within each block/try and catch) it will throw error:

cannot redirect after committing

Any help is much appreciated. Let me know if you don't understand my question correctly.

هل كانت مفيدة؟

المحلول

I was able to do it. selection of radio buttons

if(radio value==(value of 1st radio button))
{
for(String x : list)
{
   try {
    output 1
      RequestDispatcher dispatcher =request.getRequestDispatcher("1st.jsp");
      dispatcher.forward(request, response);
      return;
}
catch {
    output 2
      RequestDispatcher dispatcher =request.getRequestDispatcher("2nd.jsp");
      dispatcher.forward(request, response);
      return;
  }
  }
  }
 else{

 for(String x : list)
  {
  try {
    output 1
      RequestDispatcher dispatcher =request.getRequestDispatcher("1st.jsp");
      dispatcher.forward(request, response);
      return;
}
catch {
    output 2
      RequestDispatcher dispatcher =request.getRequestDispatcher("2nd.jsp");
      dispatcher.forward(request, response);
      return;
}
 }
}

based on this it will go to one of the jsp pages depending upon the selection of radio buttons.

I hope this will help people in the future too.

thanks all for helping me out.

نصائح أخرى

response.sendRedirect() method creates a new request every time , why dont you use the RequestDispatcher and add a return statement to it .

see this RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

so you may rewrite your code as ,

for(String x : list)
{
    try {
        output 1
          RequestDispatcher dispatcher =request.getRequestDispatcher("1st.jsp");
          dispatcher.forward(request, response);
          return;
    }
    catch {
        output 2
          RequestDispatcher dispatcher =request.getRequestDispatcher("2nd.jsp");
          dispatcher.forward(request, response);
          return;
    }
}

Hope this helps!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top