I have following codes in my app which is using JSF 2.0
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
.getRequest();
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
......
try {
request.getRequestDispatcher("SomePage.xhtml").forward(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But when ever the line ..
request.getRequestDispatcher("SomePage.xhtml").forward(request, response);
is executed I'm getting the following exception...
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at javax.faces.component.AttachedObjectListHolder.restoreState(AttachedObjectListHolder.java:165)
at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1432)
at com.sun.faces.application.view.StateManagementStrategyImpl$1.visit(StateManagementStrategyImpl.java:265)
at com.sun.faces.component.visit.FullVisitContext.invokeVisitCallback(FullVisitContext.java:151)
Due to some appilcation constaints I can not use the
FacesContext.getCurrentInstance().getExternalContext().redirect();
method..
Is it a JSF 2.0 bug??
I never tried to send a redirect this way because this is not the standard solution for navigation in JSF2.
Here are some methods that will work correctly in a JSF 2.0 environment:
1. Specify the redirect command in the navigation link
Attach ?faces-redirect=true to your navigation and this should do the job.
public String someAction(){
// Logic here
return "newPage" + "?faces-redirect=true"
}
<h:form id = "form">
<h:inputText>...</h:inputText>
<h:commandButton action = "#{controller.someAction}" />
</h:form>
After processing the Login in the someAction the navigation flow will be redirected to newPage.xhtml. All you have to do is to correctly call the action from your UI Form.
2. Specify the redirect through external context
This method is closer to what you are looking for:
public void someAction(){
// Logic here
try{
FacesContext.getCurrentInstance().getExternalContext().redirect("newPage");
} catch (Exception e){
e.getMessage();
}
}
First of all, whenever you need to use javax.servlet.* classes inside a JSF managed bean, then changes are big that you're doing things the wrong way or unnecessarily overcomplicated. Keep this in mind for the next time you need to a add a import javax.servlet...; line.
As to your concrete problem, in your particular case, you should just be returning the view ID in order to perform a forward.
public String someAction() {
// ...
return "SomePage";
}
An alternative is ExternalContext#dispatch() method, but this is also unnecessarily overcomplicated.
Related
Im working on a asp.net core website and im trying to make som global validation exception handling using Filters. The backend can at random places throw fluentapi ValidationException and I want to catch these and show the error messages to the user. This filter only cares about ValidationExceptions. All other exceptions will be handled later..
Instead of using a try/catch in every post action in all my controllers, I want to use a filter that catches only ValidationExceptions, add the errors to the ModelState and then return to the original view with the updated ModelState.
I have tried many things but every time I just get a blank page after the filter finishes. I can easily set a new RedirectToRouteResult witht the controller and action from the context. But then I dont have the ModelState and values the user entered..
public class PostExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
if (context.Exception is FluentValidation.ValidationException)
{
var ex = context.Exception as FluentValidation.ValidationException;
context.Exception = null;
context.HttpContext.Response.StatusCode = 200;
context.ExceptionHandled = true;
foreach (var item in ex.Errors.ToList())
{
context.ModelState.AddModelError(item.PropertyName, item.ErrorMessage);
}
// Done with the stuff I want.
// Now please go back to the original view with the updated modelstate and values
}
else if (context.Exception is UnauthorizedAccessException)
{
// Do something else...
}
else
{
// Do something else...
}
base.OnException(context);
}
}
You cannot access the particlar Model(related to Action Method) in Exception Filters. So you have to handle the error at Controller level if you want to add Errors to model.
try
{
//Do something
}
Catch(Exception e)
{
ModelState.AddModelError(string key, string errorMessage);
Return View(model)
}
The error message will present itself in the <%: Html.ValidationSummary() %> in your View
Without try-catch blocks you won't know if exception occured in Action Method, So that you can add Custom Errors to Model.
I am trying to create standard error page for zuul server so that I can redirect exception to this page?
Currently, I have created a zuul filter to catch zuul exception as below:
code snippets
#Override
public Object run() {
try {
RequestContext ctx = RequestContext.getCurrentContext();
Object e = ctx.get("error.exception");
if (e != null && e instanceof ZuulException) {
ZuulException zuulException = (ZuulException)e;
LOG.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);
// Remove error code to prevent further error handling in follow up filters
ctx.remove("error.status_code");
// Populate context with new response values
ctx.setResponseBody("Internal Server Error : Please contact Phoenix Admin");
ctx.getResponse().setContentType("application/json");
ctx.setResponseStatusCode(500); //Can set any error code as excepted
}
}
catch (Exception ex) {
LOG.error("Exception filtering in custom error filter", ex);
ReflectionUtils.rethrowRuntimeException(ex);
}
return null;
}
appreciate for any advice?
I will have to spend some time to see how you can read from the error page I am traveling right now. But setting the response body by reading content might not be a bad option definitely might not be perfect.
Checkout the below code if it helps.
Also add some code that you might be trying and is not working its easier that way to answer and help.
You need to make sure the filter runs after the predecoration filter.
#Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String url = UriComponentsBuilder.fromHttpUrl("http://localhost:8082").path("/outage").build()
.toUriString();
ctx.set("requestURI", url);
return null;
}
Check this out for more information:- https://github.com/spring-cloud/spring-cloud-netflix/issues/1754
Hope this helps you.
I don't redirect or forward my user to another page. So when the my SessionExpiredExceptionHandler (extends ExceptionHandlerWrapper) handles the ViewExireException. I want the user to stay on the same page and display a PrimeFaces Dialog. For notifying that the session has expired and that the user needs to login again (dialog based). I am use Servlet 3.1 functions to login/logout user and Basic/file for auth-method to map the users to different system roles.
What is happening now is that the View/page get refreshed after 2 min, but the session doesn't get invalidated. That only happens the second time when the page refreshes, after 4 min.
<session-config>
<session-timeout>2</session-timeout>
</session-config>
Edit:
Which is refreshed by the meta tag:
<meta http-equiv="refresh" content="#{session.maxInactiveInterval}" />
How can I make SessionExpiredExceptionHandlerinvalidate the session object (Servlet logout) when the Exceptions occur the first time, and how can I invoke a JavaScript (expireDlg.show()) on the client to display a PrimeFaces dialog ?
I have looked at some other threads but not found a viable solution.
Session time-out
SessionExpiredExceptionHandler
#Override
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable t = context.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
requestMap.put("currentViewId", vee.getViewId());
nav.handleNavigation(fc, null, "Home");
fc.renderResponse();
} finally {
i.remove();
}
}
}
// At this point, the queue will not contain any ViewExpiredEvents.
// Therefore, let the parent handle them.
getWrapped().handle();
}
web.xml
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/home.xhtml</location>
</error-page>
How can I make SessionExpiredExceptionHandler invalidate the session object (Servlet logout) when the Exceptions occur the first time
The session is supposedly to be already invalidated/expired (otherwise a ViewExpiredException wouldn't be thrown at all), so I don't see how it's useful to manually invalidate/expire it yourself. But for the case that, you can invalidate it as follows:
externalContext.invalidateSession();
and how can I invoke a JavaScript (expireDlg.show()) on the client to display a PrimeFaces dialog ?
You can use the PrimeFaces RequestContext API to programmatically instruct PrimeFaces to execute some JS code on complete of ajax response.
RequestContext.getCurrentInstance().execute("expireDlg.show()");
Don't forget to remove the navigation handler block from the exception handler if you actually don't want to navigate.
This solution worked for my case. It seams that Primefaces (3.3) is swallowing the ExceptionQueuedEvent. There are no Exception to handle when my ViewExceptionHandler gets called. So instead I used the p:idleMonitor component with event listner. I also removed the meta refresh tag.
<p:idleMonitor timeout="#{(session.maxInactiveInterval-60)*1000}">
<p:ajax event="idle" process="#this" update="sessionMsg" listener="#{userController.userIdleSession()}" />
<p:ajax event="active" process="#this" update="sessionMsg" listener="#{userController.userActiveSession()}"/>
</p:idleMonitor>
One weird thing is if the timeoutis excatly the same as the web.xmlsession time-out parameter, the listener won't be invoked.
Bean functions
public void userIdleSession() {
if (!userIdleMsgVisable) {
userIdleMsgVisable = true;
JsfUtil.addWarningMessage(JsfUtil.getResourceMessage("session_expire_title"), JsfUtil.getResourceMessage("session_expire_content"));
}
}
public void userActiveSession() {
if (!userSessionDlgVisable) {
userSessionDlgVisable = true;
RequestContext.getCurrentInstance().execute("sessionExipreDlg.show()");
}
}
The dialog (sessionExipreDlg) called the redirect instead of using navigation handler to get new scope and refresh the page.
public void userInactiveRedirect() {
FacesContext fc = FacesContext.getCurrentInstance();
userIdleMsgVisable = false;
userSessionDlgVisable = false;
sessionUser = null;
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
JsfUtil.findBean("homeController", HomeController.class).clearCurrentValues();
try {
fc.getExternalContext().redirect(JsfUtil.getApplicationPath(request, false, null));
} catch (IOException ex) {
BeanUtil.severe(ex.getLocalizedMessage());
}
}
I am currently creating a primfaces portlet. From my view.xhtml when I am calling Submit method in my bean class. I want to redirect the view base on input.
Below is my code snippet of Submit method:
Submit(){
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("/views/Success.xhtml");
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It simply adds to the local host URL as http://localhost:8081/views/Success.xhtml. I guess I am missing something critical probably. Should implement some render phase method if yes how do i go about it so that it created a render url for that page.
Why aren't you using normal JSF navigation for this? No need to bother with portlet URLs in that case, because it will be handled by the JSF bridge for you.
public String submit() {
// do stuff;
return "/views/Success";
}
You can omit the .xhtml extension.
You can create the url using the following code
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
PortletRequest portletRequest = (PortletRequest) externalContext
.getRequest();
ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY);
PortletURL url = PortletURLFactoryUtil.create(req,
PortalUtil.getPortletId(req),
themeDisplay.getLayout().getPlid(),
PortletRequest.ACTION_PHASE);
url.setParameter("_facesViewIdRender", "/views/Success.xhtml");
url.setWindowState(WindowState.NORMAL);
url.setPortletMode(PortletMode.VIEW);
FacesContext.getCurrentInstance().getExternalContext().redirect(url.toString());
I've been trying to cache and handle viewExpiredexception where if a `viewExpiredexceptionviewExpiredexception is throw, i have written a custom viewExpiredexception Handler which is suppose to redirect back to the page where the Exception is thrown, i also insert a boolean into session which is used in the redicted page to show "page was refreshed" message.
Below is the relevant part of my ViewExpiredException Handler:
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable t = context.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
requestMap.put("currentViewId", vee.getViewId());
HttpServletRequest orgRequest = (HttpServletRequest) fc.getExternalContext().getRequest();
fc.getExternalContext().redirect(orgRequest.getRequestURI());
Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
sessionMap.put("refreshedMaxSesion",true);
fc.renderResponse();
}
catch(IOException e){ }
finally { i.remove(); }
}
}
// here queue will not contain any ViewExpiredEvents, let the parent handle them.
getWrapped().handle();
}
and the Navigation case
<navigation-rule>
<navigation-case>
<from-outcome>/app/ord1</from-outcome>
<to-view-id>/jsp/orderHist.jsp</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
I had limited success with the above, it would work in some cases but in other cases the page wouldn't redirect at all. It works mostly in chrome but in IE it didn't work at all.
I tried making few changes such as using
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.sendRedirect(vee.getViewId());
but i was getting the 500 error pages with exception saying View must Exists... so i stopped experimenting to find out what i am doing wrong first. How can this goal of cahcing a ViewExpiredException, and Redirectign back to the page where the error was thrown be archived?
I'm on myFaces (2.1.7) and richFaces (3.3.3). Thanks
There is some work already done inside MyFaces Community to deal with ViewExpiredException in a graceful way. Some issues has been solved in MyFaces Core (see MYFACES-3530 and MYFACES-3531) Maybe you should try the latest snapshot HERE.