tags:

views:

1001

answers:

1

I want to forward request to another page from action class I am using below code in my jsf action :

 public String submitUserResponse(){
    ......
    ......
    parseResponse(uri,request,response);
    ....

    return "nextpage";

 }  

public String parseResponse(String uri,request,response){

  if(uri != null){ 
  RequestDispatcher dispatcher = request.getRequestDispatcher(uri);

   dispatcher.forward(request, response);
   return null;
   }
   .................
   ..................  
   return "xxxx";

 }

"submitUserResponse" method is being called when user clicks the submit button from the jsp and this method returns "nextpage" string here request forwards to next page in normal flow. but in my requirement i will call "submitUserResponse () " which will execute and forwrd request to next page.It is going. but it is displaying some exceptions in server

That is :

   java.lang.IllegalStateException: Cannot forward after response has been committed

Here my doubts are: 1.why next lines of code is being executed after forwarding my request using dispatched.forward(uri) . Same thing happening in response.sendRedirect("").

+3  A: 

Here my doubts are: 1.why next lines of code is being executed after forwarding my request using dispatched.forward(uri) . Same thing happening in response.sendRedirect("").

Because you didn't call return to jump out of the method block. The include(), forward() or sendRedirect() really doesn't have some magic that they automagically does that. Those are still just Java methods like any other (except of System#exit() of course). They will be invoked in order and the code will just continue until end of method block or return statement. It's just all about the code flow you write and control yourself.

That said, the normal JSF practice is that you should use ExternalContext#dispatch() or ExternalContext#redirect() for this (the first is applicable in your case). Not only it keeps your code free from unnecessary "under-the-hood" clutter in JSF code such as the Servlet API, but it also removes the need to call FacesContext#responseComplete() which you could also have done to fix your initial IllegalStateException problem.

In a nutshell: replace your code by

public void submitUserResponse(){
    String uri = "foo.jsf";
    FacesContext.getCurrentInstance().getExternalContext().dispatch(uri);
}

That's all. No need to unnecessarily dig the Servlet request/response from under the JSF hoods. Note that the method is declared void. This is perfectly acceptable, although some know-it-better like IDE's will complain about it, if so, then just ignore it or replace by String and add return null;.

BalusC
I did samething . but i am getting same Exception message.Here i want to redirect request to another application.so i used public String editVerismo_initAction(){ .......... FacesContext.getCurrentInstance().getExternalContext().redirect(redirectUrl);return null;}
Satya