Rectangle 27 42

Messages get lost during redirect. You can use the flash to keep messages.

Add the following before returning from your action method:

FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getFlash().setKeepMessages(true);

Note that this approach has a peculiar bug when used with Mojarra: it won't work then the redirect goes to a different path. If the current and target page are in the same path (the same folder in URL), then it will work fine. See also java.net/jira/browse/JAVASERVERFACES-1877

jsf - How to use Primefaces' p:growl and redirect to a page - Stack Ov...

jsf redirect primefaces growl
Rectangle 27 12

This is a problem with the default way that Spring Security sends redirects back to the client. The default method of sending a redirect to the client is the HTML approach of sending a 302 Temporarily Moved response, however this does not work for AJAX clients. The AJAX client will interpret this as a redirect to a new location to post/get its data and not as a page redirect. The correct way to get the AJAX client to redirect the browser to a new page in the same way as a normal HTML request is:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<partial-response>
  <redirect url="http://your.url.here/"></redirect>
</partial-response>

To override the default invalid session strategy used by Spring Security, you need to create a SessionManagementFilter bean in your Spring config, and pass it a class that implements InvalidSessionStrategy and sends the correct redirect response when a request is received either via HTML or AJAX:

<bean id="sessionManagementFilter" class="org.springframework.security.web.session.SessionManagementFilter">
  <constructor-arg name="securityContextRepository" ref="httpSessionSecurityContextRepository" />
  <property name="invalidSessionStrategy">
    <bean class="yourpackage.JsfRedirectStrategy">
       <constructor-arg name="invalidSessionUrl" value="/your_session_expired_page.xhtml" />
    </bean>
  </property>
</bean>
<bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>
<security:http use-expressions="true">
    <security:custom-filter ref="sessionManagementFilter" before="SESSION_MANAGEMENT_FILTER" />
    ...
</security:http>

The custom session management filter will now be created when your application starts, and the invalid session strategy class provided will execute whenever an expired session is found.

A good example of how to implement the invalid session strategy can be found here: https://gist.github.com/banterCZ/5160269

One note from my (successful) implementation of your answer here: Don't clear your cookies then trigger the ajax request as a way of testing this method! The new, session-less request isn't considered "invalid" the same way an expired session is!

jsf 2 - Redirect handling PrimeFaces Ajax requests on session timeout ...

ajax jsf-2 primefaces spring-security session-timeout
Rectangle 27 12

This is a problem with the default way that Spring Security sends redirects back to the client. The default method of sending a redirect to the client is the HTML approach of sending a 302 Temporarily Moved response, however this does not work for AJAX clients. The AJAX client will interpret this as a redirect to a new location to post/get its data and not as a page redirect. The correct way to get the AJAX client to redirect the browser to a new page in the same way as a normal HTML request is:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<partial-response>
  <redirect url="http://your.url.here/"></redirect>
</partial-response>

To override the default invalid session strategy used by Spring Security, you need to create a SessionManagementFilter bean in your Spring config, and pass it a class that implements InvalidSessionStrategy and sends the correct redirect response when a request is received either via HTML or AJAX:

<bean id="sessionManagementFilter" class="org.springframework.security.web.session.SessionManagementFilter">
  <constructor-arg name="securityContextRepository" ref="httpSessionSecurityContextRepository" />
  <property name="invalidSessionStrategy">
    <bean class="yourpackage.JsfRedirectStrategy">
       <constructor-arg name="invalidSessionUrl" value="/your_session_expired_page.xhtml" />
    </bean>
  </property>
</bean>
<bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>
<security:http use-expressions="true">
    <security:custom-filter ref="sessionManagementFilter" before="SESSION_MANAGEMENT_FILTER" />
    ...
</security:http>

The custom session management filter will now be created when your application starts, and the invalid session strategy class provided will execute whenever an expired session is found.

A good example of how to implement the invalid session strategy can be found here: https://gist.github.com/banterCZ/5160269

One note from my (successful) implementation of your answer here: Don't clear your cookies then trigger the ajax request as a way of testing this method! The new, session-less request isn't considered "invalid" the same way an expired session is!

jsf 2 - Redirect handling PrimeFaces Ajax requests on session timeout ...

ajax jsf-2 primefaces spring-security session-timeout
Rectangle 27 1

<p:growl id="growlmsg2" showDetail="true" sticky="true" autoUpdate="true"/>

jsf - How to use Primefaces' p:growl and redirect to a page - Stack Ov...

jsf redirect primefaces growl
Rectangle 27 3

There are several misconceptions in your code:

  • actionListener method can not fire a redirect. That could be done in action
  • An ajax request cannot fire a redirect. Ajax is meant to work as an asynchronous request to the server and get the desired result to the current view and handle the response to update the view without refreshing the page nor without navigating.
  • If using Primefaces components, you should work with them for efficiency in your page. For example, <p:commandButton> should work with <p:ajax> rather than <f:ajax>. But in this case, <p:commandButton> already has ajax capabilities built-in, so there's no need to use any of these ajax components.
<p:commandButton value="Print" type="button" title="Print"
    action="#{currentpage.redirect}" process="@this">
    <p:printer target="printer" />
</p:commandButton>

And the method declaration to:

//parameterless
public void redirect() {
    /* Deleted the record */ 
}

PrimeFaces let's you add behavior when the ajax request is complete by usage of oncomplete attribute. This attribute receives the name of a javascript function that will be invoked right when the ajax request finishes without problems. In this method, you can add the logic for your redirection:

<p:commandButton value="Print" type="button" title="Print"
    action="#{currentpage.redirect}" process="@this" oncomplete="redirect()">
    <p:printer target="printer" />
</p:commandButton>

<script type="text/javascript>
    redirect = function() {
        window.location.href = '<desired url>';
    }
</script>

Tried this but action and oncomplete both are not working now.

@niks please do not say it's not working, explain what's the problem you have.

The issue i'm having is it doesn't go in the redirect function in currentpage bean and nor it goes to javascript fuction.It only prints when clicked on the button.In other words no record get's deleted as well as it does not redirects to some page,it only printer is working on button click.

this is my issue as I mentioned above.Does it make sense?

jsf - How to redirect to a page after printing with primefaces Printer...

jsf jsf-2 primefaces
Rectangle 27 1

You can do it without having to bind them to the managed bean. In JSF there are two main navigation cases:

  • Perform a view request without doing nothing more. That's an HTTP GET request and is done using h:button, which doesn't need to be wrapped by a form and acts like a link.
  • Perform a form POST and after that ask for another page (REDIRECT-GET), that's done by h:commandButton.
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core">
<h:head />
<h:body>
    <f:metadata>
        <f:viewParam name="backurl" />
        <f:viewParam name="id" />
    </f:metadata>
    <h:outputText value="backurl value is #{backurl} and id value is #{id}" />
    <br />
    <h:button outcome="index" value="redirect">
        <f:param name="backurl" value="directUrl" />
        <f:param name="id" value="directId" />
    </h:button>
    <h:form>
        <h:commandButton value="action" action="#{bean.redirect}" />
    </h:form>
</h:body>
</html>
@ManagedBean
@RequestScoped
// You could also use @ViewScoped
public class Bean implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * Performs a redirection to index destination view with the given params
     * 
     * @return
     */
    public String redirect() {
        return "index?backurl=actionUrl&id=actionId&faces-redirect=true";
    }
}

You'll see when you initially load the page, both backurl and id don't have a value.

The first button performs a GET request with fixed view parameter values. When view loads again, values are already there. Second button does the same but using an action method.

Keep in mind that using @RequestScoped or @ViewScoped here has the same effect, as @RequestScoped doesn't maintain the state of the bean and @ViewScoped destroys it each time an String value is returned from the method, which is happening every time we invoke it.

but what can I do when I don't know parameter name but I want to reload page?

And I have to redirect to the same page, no other. In other word, I want to refresh page and don't lose parameter value.

Just replace the fixed values you're sending by #{backurl} and #{id} for the h:button case. For the action method, you can change the no-parametered #{bean.redirect} by #{bean.redirect(backurl,id)} and make it receive two String parameters at server side (if you're using EL 2.2, which makes possible passing parameters). Then, perform the redirection with that received parameters.

I want to get universal way to redirect from any page with any parameters, so have can i know about parameters of any request?

You need to know about parameters of the destination view previously. Obviously, you can leave them empty, but you need the destination view to be prepared for that case.

jsf - How to redirect to same page with all parameters? - Stack Overfl...

jsf redirect jsf-2 parameters query-string
Rectangle 27 2

If your page has separate content, consider using (i)frames. This way, if some particular content fails to load, the whole page would still render, but that frame would show the error page. This of course implies that all your separate components are full html pages.

BalusC is absolutely correct that you should NOT try to handle any parsing exception etc. Oddly rendered page segments are not user friendly, and can lead to very bizarre results.

If you have roles/rights issues, those scenarios should be maintained separate from jsf rendering. Authorization should be confirmed before forwarding to a page, not while attempting to render it.

Using iframes is a nice idea while maybe not too convenient. As I stated in my question "I know I should: Hide the parts that user cannot access". I will try to hide forbidden elements and catch exceptions beforehand. However, there are always exceptions leaking out and I would not like to trash the whole page, if the exception source is some minor component. After re-thinking the issue, I think it is enough to have this replace-the-content-of-the-element-on-failure-with-some-error-text feature on JSF components. Supporting it everywhere is not required. Any further thoughts?

java - Show error within JSF page and continue rendering it instead of...

java jsf exception-handling lifecycle
Rectangle 27 1

The navigation does by default not fire a new HTTP request. Instead, a different view is been used as content of the current HTTP response. Only when you navigate with a redirect by appending the <redirect/> entry to the <navigation-case>, then a new HTTP request would be created.

You should totally understand it if you're familiar with RequestDispatcher#forward() concept of the basic Servlet API which JSF is sitting on top of.

Thank you.Yes, it doesnt fire a new request(I can able to see it using debugBar tool). I'll try by appending the <redirect>.

jsf - Managed bean Constructor is not getting fired in page navigation...

jsf jspx
Rectangle 27 1

Doing so would mean that you're giving the enduser a halfbaked HTML page (because JSF hasn't (and can't) complete the HTML rendering) and it's unspecified how the webbrowser would display the page.

Rendering incomplete HTML must be avoided, I agree, but there are cases where the HTML would still be valid. For example if I do <div>#{myBean.someProperty}</div> and the property is forbidden for the current user (throwing an exception), the page might just display the error text in place of the property like <div>AccessDeniedException</div> and HTML would be still valid. Propably I would want to initialize a special bean/facelet to report the thrown exception in a sane way. I do agree that in many cases the page would break, but when used carefully, valid output can be guaranteed as well?

There the rendered attribtue is for.

Yes, I will try to preemptively avoid exception and catch them the best I can. However, let's consider that I have a JSF component, calling a managed bean behind it. In the middle of the execution, a very unexpected exception is thrown and not caught. Is there an approach to, instead of redirecting the user to an error page, to show some generic error in place of the portlet (maybe the whole facelet) and continue rendering the rest of the page? Supposing the portlet doesn't have relations to other elements in the page, would you still consider this a bad thing?

This indicates a RuntimeException, so yes, it's likely bad. As a completely different alternative, you may consider JSTL's c:catch. But still, handling exceptions in the view side is a bad idea. Just catch it in business/model side and set some token/toggle accordingly where the view could intercept on using rendered attribtue.

Thanks for the pointer to c:catch. It seems like it might have some issues, but might as well do the trick, so I'll pick this as the accepted answer. Instead of using c:catch, I will, however, propably follow your advice and not ignore mid-page failures but redirect to a separate error page instead, to tell the user about the problem and allow her input some additional information into the crash report. I don't this is necessarily a better way, but certainly safer.

java - Show error within JSF page and continue rendering it instead of...

java jsf exception-handling lifecycle
Rectangle 27 0

I recommend a small redesign the page structure: Make the front page /start the page that an authenticated user is allowed to see, and redirect to /login if the user is not authenticated yet.

This design is not only cleaner in terms of separation of concerns (allows you to bundle the authentication logic in a distinct folder), it also solves the problem of mixing context root and authentication page.

jsf - How to redirect page request by user loggedin - Stack Overflow

jsf seam jboss7.x seam3
Rectangle 27 0

it will good if u have a dialog in xhtml page & if you want to show the Dialog just use.

& if u want to redirect then use Facescontext redirect("URL") method.

java - Redirecting form jsf managed bean and showing js alert based on...

java jsp jsf java-ee web-applications
Rectangle 27 0

  • check for the parameters that are submitted to the servlet
  • Disable/enable controls on the page

This is how you do it by maintaining a session in your application

//page submission at your server
HttpSession session = request.getSession();

//set your session variable here
session.setAttribute("validUser", someValue);

//redirect your page back to login page
response.sendRedirect(URL);

Back at your login homepage, check for session variable in JQuery and display accordingly:

// Read your session variable here
//you can set a boolean to check if the user is logged in then do not call the routine or otherwise
$(function() {
 alert( $.session("validUser") );
});

use the controls properly, add an edit to you original post and paste your code there.

i had tried implementing jquery for the form fields change. But when i click on login, the page submits and the fields get hidden giving error saying the fields are empty. Can you please suggest some solution using Jquery.

can you provide us with the code or show us what you are upto, only then we will be able to help.

i have edited my post and added the jquery used.For the dropdown to display different fields onchange i have created a div tag and based on the value change the jquery will display the associated div tag fields. Now when i login, i want to create a session and display the logout option in place. But with the above code the page refreshes the fields get hidden without the login getting triggered.

jsf - How to redirect to the same page after login in jsp? - Stack Ove...

jsp jsf
Rectangle 27 0

Doing so would mean that you're giving the enduser a halfbaked HTML page (because JSF hasn't (and can't) complete the HTML rendering) and it's unspecified how the webbrowser would display the page.

Rendering incomplete HTML must be avoided, I agree, but there are cases where the HTML would still be valid. For example if I do <div>#{myBean.someProperty}</div> and the property is forbidden for the current user (throwing an exception), the page might just display the error text in place of the property like <div>AccessDeniedException</div> and HTML would be still valid. Propably I would want to initialize a special bean/facelet to report the thrown exception in a sane way. I do agree that in many cases the page would break, but when used carefully, valid output can be guaranteed as well?

There the rendered attribtue is for.

Yes, I will try to preemptively avoid exception and catch them the best I can. However, let's consider that I have a JSF component, calling a managed bean behind it. In the middle of the execution, a very unexpected exception is thrown and not caught. Is there an approach to, instead of redirecting the user to an error page, to show some generic error in place of the portlet (maybe the whole facelet) and continue rendering the rest of the page? Supposing the portlet doesn't have relations to other elements in the page, would you still consider this a bad thing?

This indicates a RuntimeException, so yes, it's likely bad. As a completely different alternative, you may consider JSTL's c:catch. But still, handling exceptions in the view side is a bad idea. Just catch it in business/model side and set some token/toggle accordingly where the view could intercept on using rendered attribtue.

Thanks for the pointer to c:catch. It seems like it might have some issues, but might as well do the trick, so I'll pick this as the accepted answer. Instead of using c:catch, I will, however, propably follow your advice and not ignore mid-page failures but redirect to a separate error page instead, to tell the user about the problem and allow her input some additional information into the crash report. I don't this is necessarily a better way, but certainly safer.

java - Show error within JSF page and continue rendering it instead of...

java jsf exception-handling lifecycle
Rectangle 27 0

I don't know what you expect but when you redirect to localhost/my-project/ then a redirect to a page with url localhost/my-project/ seems like the correct behaviour.

Maybe you missed the port (e.g. redirect to localhost:8080/my-project/) but in general it is not intended to redirect to a URL containing localhost but to a specific page (e.g. redirect to index.jsf or index.xhtml). You don't even need the webapp context (i.e. my-project), you can just redirect to your "main page" like this:

FacesContext.getCurrentInstance().getExternalContext().redirect("home.xhtml");

jsf - Adding omnifaces project gives incorrect url at redirect - Stack...

jsf primefaces glassfish omnifaces
Rectangle 27 0

You can't use JSF navigation cases to go to pages in a different application context. So sending a redirect is the only option. If you'd like to pass additional parameters along with the redirect, then pass them as request query string parameters:

String from = request.getRequestURL().toString();
externalContext.redirect("/othercontext/login.xhtml?from=" + URLEncoder.encode(from, "UTF-8"));

The other application can then just redirect back as follows:

String from = request.getParameter("from");
externalContext.redirect(from);

jsf 2 - Navigate from one war to another JSF through bean - Stack Over...

jsf-2 java-ee-6 myfaces
Rectangle 27 0

there are several libraries or mechanisms to protect your pages from un-authorized users. In a Java EE environment you usually use the features from the application server and configure some security constraints in web.xml

If you want to rely on a more independent technology I can recommend Spring Security: http://www.springsource.org/spring-security (if you are using spring already that would be my first choice) and Apache Shiro: http://shiro.apache.org/ (which to me is a slightly simpler to understand)

The manual approach would be to create a Servlet-Filter in web.xml to protect certain urls (both frameworks above work like that).

jsp - jsf, how to redirect to login page when user doesn't login? - St...

jsp jsf java-ee redirect facelets
Rectangle 27 0

You shouldn't use command links for page-to-page navigation in first place. Use a normal link.

If you have an internal URL / (implicit) navigation outcome:

<h:link value="link" outcome="#{bundle.Myurl}" />

Or if you have an external URL:

<h:outputLink value="#{bundle.Myurl}">link</h:outputLink>

Your attempts failed because the actionListener and action attributes are declared as MethodExpression attributes, meaning that any EL will be interpreted as a bean action method. The target attribute has an entirely different meaning, which is exactly the same as the generated HTML <a> element has.

jsf - How to redirect to a page using Primefaces commadLink and bundle...

jsf primefaces
Rectangle 27 0

Messages get lost during redirect. You can use the flash to keep messages.

Add the following before returning from your action method:

FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getFlash().setKeepMessages(true);

Note that this approach has a peculiar bug when used with Mojarra: it won't work then the redirect goes to a different path. If the current and target page are in the same path (the same folder in URL), then it will work fine. See also java.net/jira/browse/JAVASERVERFACES-1877

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

jsf - How to use Primefaces' p:growl and redirect to a page - Stack Ov...

jsf redirect primefaces growl
Rectangle 27 0

As best I can deduce with my investigations so far, the problem here is with how seam forwards FacesMessages from one JSF context to another. Essentially the messages appear to have been removed to some other seam component while pages.xml rules are being applied, then returned by the time the page is rendering. I have worked around this issue for now by showing a 'no errors' message (note that global messages are present during page render):

<h:outputText id="noErrorsMessage"
    rendered="#{empty org.jboss.seam.international.statusMessages.currentGlobalMessages}">
    #{messages['jsf.NoErrors']}
</h:outputText>

and with some hard-coded redirect rules in one of my beans.

jsf - Redirect from error page when there are no errors to display - S...

jsf seam2
Rectangle 27 0

There are several misconceptions in your code:

  • actionListener method can not fire a redirect. That could be done in action
  • An ajax request cannot fire a redirect. Ajax is meant to work as an asynchronous request to the server and get the desired result to the current view and handle the response to update the view without refreshing the page nor without navigating.
  • If using Primefaces components, you should work with them for efficiency in your page. For example, <p:commandButton> should work with <p:ajax> rather than <f:ajax>. But in this case, <p:commandButton> already has ajax capabilities built-in, so there's no need to use any of these ajax components.
<p:commandButton value="Print" type="button" title="Print"
    action="#{currentpage.redirect}" process="@this">
    <p:printer target="printer" />
</p:commandButton>

And the method declaration to:

//parameterless
public void redirect() {
    /* Deleted the record */ 
}

PrimeFaces let's you add behavior when the ajax request is complete by usage of oncomplete attribute. This attribute receives the name of a javascript function that will be invoked right when the ajax request finishes without problems. In this method, you can add the logic for your redirection:

<p:commandButton value="Print" type="button" title="Print"
    action="#{currentpage.redirect}" process="@this" oncomplete="redirect()">
    <p:printer target="printer" />
</p:commandButton>

<script type="text/javascript>
    redirect = function() {
        window.location.href = '<desired url>';
    }
</script>

Tried this but action and oncomplete both are not working now.

@niks please do not say it's not working, explain what's the problem you have.

The issue i'm having is it doesn't go in the redirect function in currentpage bean and nor it goes to javascript fuction.It only prints when clicked on the button.In other words no record get's deleted as well as it does not redirects to some page,it only printer is working on button click.

this is my issue as I mentioned above.Does it make sense?

jsf - How to redirect to a page after printing with primefaces Printer...

jsf jsf-2 primefaces