Preserving JSF messages after a redirect - jsf

I have a JSF page (using MyFaces 2.0) that does a bit of data gathering the first time it is displayed. If it can't find some information, it is supposed to provide a message to that effect and redirect back to a different page. I've tried using the solution found here Preserving FacesMessage after redirect for presentation through <h:message> in JSF (setKeepMessages(true)) but the messages aren't displaying after the redirect. The only difference I can pick out is that I'm not using a navigation rule, I'm calling the redirect() call on the external context because this isn't occurring in a normal action.
Relevant code:
public void redirectToPageWithMessage(String inPage, String message, FacesMessage.Severity severity){
getFlash().setKeepMessages(true);
addMessage(message, severity);
try {
getFacesContext().getExternalContext().redirect(inPage);
} catch (IOException e) {
e.printStackTrace();
}
}
Unfortunately this doesn't seem to be working. The redirect happens just fine, but the < messages /> tag isn't displaying the message. Is there something different about the way redirect() happens that prevents this from working?

The code that saves the messages are executed after the phase ends (see Flash.doPostPhaseActions(FacesContext) ). So, it is expected it does not work, but maybe you can call Flash.doPostPhaseActions before the redirect. Note is not a "clean" solution, but it is possible.

I had the same problem and solve it not using ExternalContext.redirect() but to play with outcome for your actions.
That is to say, my action called by my buttons return a String (the outcome) which indicates the navigation rules to go to the next page. With that system, the messages are preserved.

JSFMessages are kept only for the processing of the actual request. A second request is made when using redirect, so the JSFMessages will be lost. The EL-Flash is a way to work around this. This example should work: http://ocpsoft.com/java/persist-and-pass-facesmessages-over-page-redirects/

Related

faces-redirect=true not working while creating and rendering view

I am currently working on a JSF 2.2 application. As per requirements, I have created custom view handler (using ViewHandlerWrapper) for my application. All the methods are just passing to default view handler except renderView which I am overriding as follows -
private viewHandler viewHandlerWrapped = null;
renderView(FacesContext facesContext, UIViewRoot viewToRender) {
String viewId = viewToRender.getViewId();
if (viewId == some condition) {
/* Do calculation to derive viewId */
}
UIViewRoot viewRoot = viewHandlerWrapped.createView(facesContext,viewId+"?faces-redirect=true");
facesContext.setViewRoot(viewRoot);
//now let system render the view
viewHandlerWrapped.renderView(facesContext,viewRoot);
}
The above is working fine and rendering & navigation is happening as expected. The only issue is faces-redirect=true is not working. The URL seems to be always one behind.
I have gone through many answers given in stackoverflow or internet. But nowhere I am able to find how to solve this.
I think I am doing something wrong e.g. ?faces-redirect=true might not be the correct way while creating view. But I am not sure what can be done to correct this.
Can someone please help me out with this?
After struggling with this for more than 4 weeks, I finally found a way to get the correct URL (instead of previous one). I am updating my answer here in case any one else falls into same problem -
"It looks like we can not use the faces-redirect=true the way I was using while creating and rendering the pages. It should be suffixed with form action. So I have changed my code as follows -
1) actions are returned on click of a button e.g.
public string doAction {
----
return "action?faces-redirect=true";
}
2) Code is updated to use implicit navigation wherever possible. With this, I didn't need to build my custom viewhandler as navigation is happening implicitly. So, I have scrapped the viewhandler.
With above two simple steps, the correct URL is being displayed on the browser now.

FacesException not being handled by standard error page

there is one issue to which i don't find any specific answer. there is an ArrayOutOfBoundException thrown in a setter method called during render response phase since i have the value of that property set in my faces-config. Now, when this happens, it is not redirecting. What i could understand till now is it might be converting this exception to FacesException and so its not redirecting. Any views to handle this ? the call does not seem to be an ajax call too since it is coming when i click on a menu item.

Navigation from managed bean constructor in ADF Faces JSF 1.2

Is it possible to navigate to another page/view from the constructor of the managed bean? I want this redirection if any exception occurred. I have tried many ways:
Try-1:
getFacesContext().responseComplete();
getFacesContext().getApplication().getNavigationHandler().handleNavigation(getFacesContext(), null, "gotoPartError");
getFacesContext().renderResponse();
Try-2:
getServletResponse().sendRedirect("partError.jspx")
Try-3:
getFacesContext().responseComplete();
getFacesContext().getExternalContext().redirect(getServletRequest().getContextPath() + "/pages/partError.jspx");
Try-4:
RequestDispatcher dispatcher = getServletRequest().getRequestDispatcher("partError.jspx");
dispatcher.forward(getServletRequest(), getServletResponse());
Try-5:
FacesContext context = getFacesContext();
UIViewRoot newPage = context.getApplication().getViewHandler().createView(context, "/partError.jspx");
context.setViewRoot(newPage);
context.renderResponse();
Try-6:
ControllerContext.getInstance().getCurrentViewPort().setViewId("partError");
Try-7:
Exception Handler in adfc-config.xml
Try-8:
Custom service handler defined in /.adf/META-INF/services/oracle.adf.view.rich.context.Exceptionhandler which extends oracle.adf.view.rich.context.Exceptionhandler
Try-9:
By extending JSF Life Cycle
None of them worked. For all the cases I received
java.lang.IllegalStateException: Cannot forward after response has been committed
Is not really possible in JSF 1.2? As I am using ADF 11.1.1.6.0, which uses JSF 1.2, some of the above "Try" contains ADF Faces ways.
I need anyway, that can be JSF 1.2 or ADF Faces, to navigate to error page. The only way I got success is the use of javascript, executed from backend, to open the error page in the _self window in case of error, but I don't really like it.
Any pointer in this matter would be very helpful.
It's easier to solve a problem if the cause of the problem is understood. A good exception tells basically already everything about the cause of the problem.
Look closer:
java.lang.IllegalStateException: Cannot forward after response has been committed
The response has been committed. This is a point of no return. Perhaps you failed to understand what it means that a response has been committed (which has the consequence that you also failed to understand the exception itself).
By default, the HTTP response is written to a buffer which is flushed every ~2KB, depending on server configuration. A flush of the response buffer causes the written bytes being actually sent from server to client. Once that happens for the first time, a response is considered committed. This is a point of no return. The server cannot take the already written bytes back from the client in case the server actually needs to change the response afterwards.
If you have some code which potentially needs to change the response, then you should be invoking it before the response is committed.
In your particular case, the managed bean is apparently constructed in the midst of the JSF render response phase during generating the HTML output. A part of the generated HTML output has already been sent to the client (so, the response is committed). You're apparently referencing the request scoped bean relatively late in the JSF page, or the response buffer is relatively small, or the HTML <head> is relatively large which causes a flush already before the <body> starts, etcetera.
You really need to invoke the code before the render response phase. In JSF 1.2, you can use the <f:view beforePhase> for this.
E.g.
<f:view beforePhase="#{bean.navigate}">
with
public void navigate(PhaseEvent event) {
if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
// Do here your job which should run right before the RENDER_RESPONSE.
}
}
Then your Try-1 and Try-3 will work (you can however leave those responseComplete() and renderResponse() lines away, they are implicitly already taken care of).
Try-2 and Try-4 are poor. You should avoid having javax.servlet.* imports in your backing bean. Try-5 is clumsy. Try-6, Try-7 and Try-8 are beyond my scope. Try-9 is doable, but extremely clumsy.

Can MVC Custom Error pages retain Route Values?

The MVC project that I am currently working on uses Regions so that we can localise pages etc.
I have spotted a problem with our Error page. We have turned the custom error pages on in the web.config file. If we are on a page lets say : /IT/News/Index and we get an error, when it redirects it will go to /Error and there will be no routevalue attached to it.
Is there away to ensure that the langauge routevalue is retained by the Error page?
I have searched around and cannot find a solution at the moment and was wondering if anyone else could help or point me in the right direction?
Hope that this all makes sense. Any help is much appreciated.
If you're getting physically redirected to /Error then it's not because of the MVC HandleErrorAttribute. It's probably due to your Web.Config having system.web/customErrors defined for error handling. Using the HandleErrorAttribute causes it to inject a specific view instead of the view you would have normally returned but does not redirect you to a different action by default. The problem is when redirected because of customErrors, there is no inherant information available to tell you where they came from. But using HandleErrorAttribute DOES cause some info to be populated for you. Specifically it creates a HandleErrorInfo to use as a view model and passes that to the view you specify. For example, here's one that is reigstered in the /App_Start/FilterConfig.cs file.
public class FilterConfig
{
public static void RegisterFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute {View = "Error"});
}
}
When you redirect to an error View using the HandleErrorAttribute, certain information is populated for you. The HandleErrorInfo view model will contain the ControllerName of the original controller requested, and the ActionName of the original action. Also, the ViewData and the TempData from the original request will be copied into the ViewData and Temp data for the request to the Error view. With that information it should have what you need. Be aware that not all errors happen inside of an Action however, and exceptions that don't happen in an action will not be caught by the HandleErrorAttribute. So you'll still need to use something like customErrors (or system.webServer/httpErrors if you're doing it inside of IIS7+) to handle exceptions that occur elsewhere in your app.
Here's a link to the HandleErrorAttribute file on CodePlex in case you're wondering what it does. HandleErrorAttribute.cs
I'm not sure if this solution meets you requirements. You can override in your base controller OnException and then redirect to a specific page.
protected override void OnException(ExceptionContext filterContext)
{
string controller = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
//get other stuff from routing
//here you can do redirect or other stuff
//if handled exception
//filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
It depends how you're getting to the error pages, really. If you're using an ActionFilter-based method to catch exceptions, then you can get route values from the context that gets passed into the OnException method. If you're using a redirect from a catch block, then you can push the relevant information into TempData or pass it directly as a parameter, depending on how you're doing that redirect.
You can add a custom HandleErrorAttribute or use a base controller to be inherited by all your controllers. Either way, you need to get the RouteData object, like this
var routeData = filterContext.RouteData;
with that object, you can get all the route values accordingly to your needs. Check the object definition in MSDN site for more detail
Say you have the following route
routes.MapRoute(
"Language", // Route name
"{language}/{controller}/{action}/{id}", // URL with parameters
new { language = "en", controller = "Sites", action = "Index", id = UrlParameter.Optional } // Parameter default
Then routeData.Values.Keys will tell you the name of the parameter and routeData.Values.Values the value itself
Then, wherever you handle the exception, you can store the route data in a TempData variable, like this
TempData["RouteData"]
And after that, it will be available on your error page
#model System.Web.Mvc.HandleErrorInfo
#{
ViewBag.Title = "Error";
}
<h2>
Sorry, an error occurred while processing your request.
</h2>
#TempData["RouteData"];

JSF adding query parameters

I am using JSF and I have a backing bean method which does some processing and sets a
variable 'outcome' which then decides the next page to navigate to depending on the
faces-config.xml navigation rules.
What I want to do is add parameters to the URL (in the backing bean?) when the next page is navigated to.
However in the Handler where the backing bean method is, there is no reference to the
HttpRequest object. This is an existing handler which has been around for a long time, so I
am wondering how I can do
request.setAttribute("name", value);
Is there a different approach available for JSF? Any help much appreciated.
HI BalusC,
I am trying to implement what you explained below, however I am running into a problem.
This is what I have:
StringBuffer url = ( (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRequestURL();
url.append( "?serialNumber=");
url.append(regBean.getSerialNumber());
try{ FacesContext.getCurrentInstance().getExternalContext().redirect(url.toString());
}catch (Exception ex){
ex.printStackTrace();
}
There is no exception generated however I get a 500 Http error "the server has encountered an unknown error." The log shows a little more detail but not enough to be helpful:
ERROR [lifecycle] JSF1054: (Phase ID: INVOKE_APPLICATION 5, View ID: /registration/productValidation.jsp) Exception thrown during phase execution: javax.faces.event.PhaseEvent[source=com.sun.faces.lifecycle.LifecycleImpl#591dae]
11:19:12,186 ERROR [[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception
java.lang.IllegalStateException
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435)
at com.sun.faces.context.ExternalContextImpl.redirect(ExternalContextImpl.java:421)
at com.sun.faces.application.NavigationHandlerImpl.handleNavigation(NavigationHandlerImpl.java:181)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:130)
at javax.faces.component.UICommand.broadcast(UICommand.java:387)
at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:321)
at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:296)
at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:253)
at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:466)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
Any ideas at all will be very much appreciated. Thanks!
Ok, thanks for your comments, I changed some stuff around and now I have:
FacesContext.getCurrentInstance().getExternalContext().redirect("mypage.jsp?serialNumber=555555");
Upon debugging I can see that the redirect is working since on mypage.htm I am displaying some headers from a resourcebundle (properties file) so when it tried to get the header to display it is encountering a NullPointer on the line below:
FacesContext context = FacesContext.getCurrentInstance();
context is null, so the log shows NullPointer error but the url of the page is correct I can see the address bar showing http://..../mypage.jsp?serialNum=5555 just as expected!
It appears its having trouble just displaying the contents of the page. So close yet so far ;-(
You need to fire ExternalContext#redirect() in the bean action method yourself.
public void submit() {
String url = "page.jsp?name1=value1&name2=value2";
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}
If your IDE validator is jerking about the void action method, then you can just ignore it or declare it back to String and put return null; at end of method block.
If you want to set the particular parameters back in some bean in the subsequent request, then you can set them as managed properties in faces-config.xml by #{param.name1} and #{param.name2}.
That said, request attributes should not be confused with request parameters. The request attributes are attached to the current request in the server side only. They are in no way passed to the next request. There you use request parameters for which you can either attach to the redirect URL or include as hidden parameters in a POST form in the response page.
Further, it might be useful to know that you can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You should however try to avoid to go that far with hauling the "raw" Servlet API from under the JSF hoods. Make use of JSF-provided facilities as many as possible.
JSF 2 added parameters to the navigation handler via the view-param element. From the spec:
If a matching <navigation-case> element was located, and the <redirect/> element was specified in this <navigation-case>, call getRedirectURL() on the ViewHandler, passing the current FacesContext, the <to-view-id>, any name=value parameter pairs specified within <view-param> elements within the element, and the value of the include-view-params attribute of the <redirect /> element if present, false, if not. The return from this method is the value to be sent to the client to which the redirect will occurr. Call getFlash().setRedirect(true) on the current FacesContext. Cause the current response to perform an HTTP redirect to this path, and call responseComplete() on the FacesContext instance for the current request. If the content of <to-view-id> is a value expression, first evaluate it to obtain the value of the view id.

Resources