I m using primefaces and spring security
the method below inside my backing bean works well.It invokes user details service and authenticates or rejects login attempts.
My problem is with redirection. What is the proper way of redirecting a user to the desired page after auth? Currently I can see that the user is authenticated but still the login form is displayed.
public String login(){
try{
Authentication request = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
}
catch(Exception e){
e.printStackTrace();
return "incorrect";
}
return "correct";
}
<http auto-config="true">
<intercept-url pattern="/web/*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page="/web/login.xhtml"
default-target-url="/main.xhtml"
always-use-default-target="true" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="kullaniciDetayServisi" />
</authentication-manager>
</beans:beans>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body>
<div align="center" style="">
<h:form id="loginFormId" prependId="false">
<div id="loginFieldsPnlId">
<div id="loginFieldUsrContId">
<h:outputText id="outTxtUserNameId" value="Username: " name="outTxtUserNameNm"></h:outputText>
<h:inputText id="userName" required="true" value="#{loginBean.username}" requiredMessage="Please enter username"></h:inputText>
<h:outputLabel id="outLblUserNameId" for="userName" name="outLblUserNameNm"></h:outputLabel>
</div>
<div id="loginFieldPassContId">
<h:outputText id="outTxtPasswordId" value="Password: " name="outTxtPasswordNm"></h:outputText>
<h:inputSecret id="password" required="true" value="#{loginBean.password}" requiredMessage="Please enter password" name="inTxtPasswordNm"></h:inputSecret>
<h:outputLabel id="outLblPasswordId" for="password" name="outLblPasswordNm"></h:outputLabel>
</div>
</div>
<div id="loginBtnPanelId">
<h:commandButton id="btnLoginId" value="Login" action="#{loginBean.login}" ajax="false"></h:commandButton>
<h:commandButton id="btnCancelId" value="Cancel" action="#{loginBean.cancel}" immediate="true" update="loginFormId" ajax="false"></h:commandButton>
</div>
</h:form>
</div>
<div>
<h:messages></h:messages>
</div>
</h:body>
</html>
Looks like you forgot to map the correct and incorrect path inside controller methods.
If I want to redirect than I might use
return "redirect:/correct/" + user.getUserName();
And handle this new request in a new controller method that map this new request.
or
return "redirect:/incorrect"
Return something like that from the controller method that handle login request.
or
Using proper navigation rules in /web/WEB-INF/faces-config.xml for JSF like this:
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-outcome>incorrect</from-outcome>
<to-view-id>/failure.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>correct</from-outcome>
<to-view-id>/sucess.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Related
Issue: I am displaying a button for change of the language on a custom login form
When user clicks on the button there should be a call to a function that changes the language, however, that is not happening because spring security is blocking other calls on that page.
Java spring security configuration that I am using is:
#Configuration
#EnableWebSecurity(debug=false)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("test000").password("test1").roles("USER").and()
.withUser("admin000").password("test1").roles("ADMIN").and()
.withUser("dba000").password("test1").roles("ADMIN","DBA");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login.xhtml","/resources/**","/javax.faces.resource/**").permitAll()
.antMatchers("/views/**","/WEB-INF/template/**").authenticated()
.anyRequest().authenticated()
.and().formLogin().loginPage("/login.xhtml").usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/home.xhtml")
.and().logout().logoutSuccessUrl("/login.xhtml").deleteCookies("JSESSIONID").invalidateHttpSession(true)
.and().exceptionHandling().accessDeniedPage("/accessDenied.xhtml")
.and().httpBasic();
}
}
Note: When I swithch off csrf.disable() then the call to the button works, but then log in stops working.
How should I set this up in order to have both log in and language change in place?
JSF Login page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html" id="fview" locale="#{USManager.locale}">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>#{appMsg['application.title']}</title>
<ui:debug />
<f:metadata>
<ui:insert name="metadata" />
</f:metadata>
<h:head>
<h:outputStylesheet library="css" name="common-style.css" />
<h:outputStylesheet library="css" name="style.css" />
</h:head>
<h:body style="background-image:none; background-color:#253A7C;" styleClass="LoginPage" onload='document.loginForm.username.focus();'>
<p:layout fullPage="true">
<p:layoutUnit position="center">
<h:panelGrid columns="2" id="loginContainer">
<div class="LoginPageLogo"> </div>
<h:panelGroup>
<h:outputText value="#{appMsg['login.title']}" styleClass="LoginTitle" />
<h:form id="loginForm" method="post" prependId="false" action="/login">
<p:growl id="loginMessages" showSummary="true" showDetail="true" autoUpdate="true" life="3000" />
<p:panel header="#{appMsg['login.form.header']}">
<h:panelGrid id="loginPanel" columns="2">
<p:spacer />
<p:spacer />
<p:inputText id="username" size="30" />
<p:spacer />
<h:outputText value="#{rccMsg['login.form.username']}" />
<p:spacer />
<p:spacer></p:spacer>
<p:message for="username"></p:message>
<p:password id="password" feedback="false" size="30" />
<p:spacer />
<h:outputText value="#{appMsg['login.form.password']}" />
<p:spacer />
<p:spacer />
<p:message for="password"></p:message>
<!-- <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> -->
<p:commandButton value="#{appMsg['login.form.submit']}" ajax="false" />
<p:commandButton id="btnSr" value="SR" actionListener="#{USManager.useSr}" rendered="#{USManager.language=='en'}" process="#this" update="#parent">
<!-- <f:setPropertyActionListener value="sr" target="#{USManager.language}"></f:setPropertyActionListener> -->
<!-- <h:graphicImage name="images/flag_sr.png"/> -->
</p:commandButton>
<p:commandButton id="btnEn" value="EN" actionListener="#{USManager.useEn}" rendered="#{USManager.language=='sr'}" process="#this" update="#parent">
<!-- <f:setPropertyActionListener value="en" target="#{USManager.language}"></f:setPropertyActionListener> -->
<!-- <h:graphicImage name="images/flag_en.png"/> -->
</p:commandButton>
</h:panelGrid>
</p:panel>
</h:form>
</h:panelGroup>
</h:panelGrid>
</p:layoutUnit>
</p:layout>
</h:body>
</f:view>
</html>
I am using spring security in my website, but when I used custom login form (JSF form), and user entered bad credentials, authentication-failure-url is not working and user is not forwarded to failed.xhtml, but index.xhtml is appeared
I don't know the reason, please help:
applicationContext.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<context:component-scan base-package="com.myspring" />
<context:annotation-config />
<!-- beans configuration -->
<beans:bean id="userBo" class="com.myspring.user.bo.impl.UserBoImpl" />
<!-- security configuration -->
<http auto-config="true">
<intercept-url pattern="/login.xhtml" access="permitAll" />
<intercept-url pattern="/index.xhtml" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/authenticated.xhtml" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/views/admin/**" access="hasRole('ROLE_USER')" />
<form-login login-page="/login.xhtml" default-target-url="/authenticated.xhtml"
authentication-failure-url="/failed.xhtml" />
<logout invalidate-session="true" delete-cookies="true" logout-success-url="/"/>
<csrf disabled="true" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
login.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body>
<div style="">
<h:form id="loginFormId" prependId="false">
<div id="loginFieldsPnlId">
<div id="loginFieldUsrContId">
<h:outputText id="outTxtUserNameId" value="Username: "
name="outTxtUserNameNm"></h:outputText>
<h:inputText id="userName" required="true"
value="#{loginController.userName}"
requiredMessage="Please enter username"></h:inputText>
<h:outputLabel id="outLblUserNameId" for="userName"
name="outLblUserNameNm"></h:outputLabel>
</div>
<div id="loginFieldPassContId">
<h:outputText id="outTxtPasswordId" value="Password: "
name="outTxtPasswordNm"></h:outputText>
<h:inputSecret id="password" required="true"
value="#{loginController.password}"
requiredMessage="Please enter password" name="inTxtPasswordNm"></h:inputSecret>
<h:outputLabel id="outLblPasswordId" for="password"
name="outLblPasswordNm"></h:outputLabel>
</div>
</div>
<div id="loginBtnPanelId">
<h:commandButton id="btnLoginId" value="Login"
action="#{loginController.login}" styleClass="loginPanelBtn"></h:commandButton>
<h:commandButton id="btnCancelId" value="Cancel"
action="#{loginController.cancel}" styleClass="loginPanelBtn"
immediate="true" update="loginFormId"></h:commandButton>
</div>
</h:form>
</div>
<div>
<h:messages></h:messages>
</div>
</h:body>
</html>
and this is the loginController with login method:
package com.myspring.controllers;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
#ManagedBean
#SessionScoped
public class LoginController {
private String userName;
private String password;
#ManagedProperty(value="#{authenticationManager}")
private AuthenticationManager authenticationManager = null;
public String login() {
try {
Authentication request = new UsernamePasswordAuthenticationToken(this.getUserName(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
} catch (AuthenticationException e) {
e.printStackTrace();
return "failed";
}
return "success";
}
public String logout(){
SecurityContextHolder.clearContext();
return "loggedout";
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public String cancel()
{
return "";
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
also I will add project structure:
Due to the fact that you are using JSF you are basically bypassing the login (and logout) functionality provided by Spring Security. Your LoginController is basically replacing that, due to that your sec:login-form and sec:legato are pretty much useless.
The solution is simple don't use JSF, you can still use Facelets to render your page, but simply include a normal form tag which posts to /login instead of an h:form tag and you can remove your LoginController.
Note: If your application is not the root application (i.e. mapped to /) you need to include the /context-path into your URL. So instead of /login use /context-path/login.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body>
<div style="">
<form id="loginFormId" method="post" action="/login">
<div id="loginFieldsPnlId">
<div id="loginFieldUsrContId">
<label>Username:<label>
<input type="text" id="username" name="username" />
</div>
<div id="loginFieldPassContId">
<label>Password:<label>
<input type="password" id="password" name="password" />
</div>
</div>
<div id="loginBtnPanelId">
<button>Login</button>
</div>
</form>
</div>
</h:body>
</html>
If you still want to use JSF and the LoginController then don't directly use the AuthenticationManager but forward the request to the /login URL that way Spring Security will take over after JSF has done the required validation.
I am trying to insert a popup which has to be lazy-loaded when clicking a h:commandButton. I insert its content via ui:include. However the preRenderView method is not being fired and the PopupPageModel model property is not being initialized so I get a NullPointerException when trying to invoke the business logic method inside PopupPageController.
The idea is having separate Model/Controller beans for both pages involved but I am not sure this is the correct approach, so I would like to know other approaches or the correct way to implement mine.
Thanks in advance.
Invoking page:
<h:commandButton
value="#{msg['jsf.thisScreen.someText']}">
<f:param name="theParameter" value="#{InvokingScreenModel.theParameter}" />
<rich:componentControl target="myPopup" operation="show" />
</h:commandButton>
<rich:popupPanel id="myPopup" modal="true" resizeable="false" autosized="true"
onmaskclick="#{rich:component('myPopup')}.hide()">
<f:facet name="header">
<h:outputText value="#{msg['jsf.anotherScreen.someText']}" />
</f:facet>
<f:facet name="controls">
<h:outputLink value="#" onclick="#{rich:component('myPopup')}.hide(); return false;"></h:outputLink>
</f:facet>
<ui:include src="popupPage.xhtml" />
</rich:popupPanel>
Popup page:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:c="http://java.sun.com/jsf/core">
<f:metadata>
<f:viewParam name="theParameter"
value="#{PopupPageModel.theParameter}" />
<f:event type="preRenderView"
listener="#{PopupPageController.initialize}" />
</f:metadata>
<h:form id="someForm">
//Some things here
</h:form>
</ui:composition>
Popup page controller
#Component("PopupPageController")
#Scope("request")
public class PopupPageController {
#Autowired
private PopupPageModel model;
#Autowired
private SomeService service;
public void initialize(){
if (!FacesContext.getCurrentInstance().isPostback()) {
//Change some model properties via service methods
}
}
public void doSomething() {
}
}
I've been struggling with this for several days and I've been unable to find a lazy-loading solution for the popup so I'm posting a solution I managed to do that doesn't include this feature just in case it's useful for someone.
Invoking page extract
<h:form>
<a4j:outputPanel id="stuffDetails">
//Some ajax-rendered tabs and accordions above the button
.....
.....
<a4j:commandButton
value="Open Popup"
actionListener="#{PopupController.someInitializationListenerMethod}"
oncomplete="#{rich:component('thePopup')}.show();"
render="formPopup">
</a4j:commandButton>
</a4j:outputPanel>
</h:form>
<rich:popupPanel id="thePopup" modal="true"
resizeable="false" autosized="true"
onmaskclick="#{rich:component('thePopup')}.hide();">
<f:facet name="header">
<h:outputText value="Some header here" />
</f:facet>
<f:facet name="controls">
<h:outputLink value="#"
onclick="#{rich:component('thePopup')}.hide(); return false;">
</h:outputLink>
</f:facet>
<h:form id="formPopup">
<ui:include src="popup.xhtml" />
</h:form>
</rich:popupPanel>
popup.xhtml
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<html>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:c="http://java.sun.com/jsf/core">
//Some controls shown inside the popup
......
......
<a4j:commandButton value="Process data and close popup"
actionListener="#{PopupController.someProcessingMethod}"
render=":stuffDetails :formPopup"
oncomplete="#{rich:component('thePopup')}.hide();" />
<h:commandButton value="Cancel"
onclick="#{rich:component('thePopup')}.hide(); return false;" />
</ui:composition>
</html>
The render=":stuffDetails :formPopup" in popup.xhtml is to avoid the infamous JSF spec issue 790 described by BalusC here and here.
Any suggestions welcome.
Could somebody explain me why a4j:commandButton doesn’t reacts at first click in the next scenario?
I have to hit it two times in order to get the action executed…
facelets composite template named principal.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<f:view contentType="text/html">
<h:head>
<meta http-equiv="content-type" content="text/xhtml; charset=UTF-8" />
</h:head>
<h:body>
<div id="heading">
<ui:insert name="heading">
<ui:include src="/adm/includes/menu.xhtml"/>
</ui:insert>
</div>
<div id="content">
<br />
<a4j:outputPanel ajaxRendered="true">
<ui:insert name="content"/>
</a4j:outputPanel>
<br />
</div>
<div id="footer">
<ui:insert name="footer">
<ui:include src="/adm/includes/footer.xhtml"/>
</ui:insert>
</div>
</h:body>
</f:view>
</html>
The JSF page with the problematic ajax button:
<ui:composition template="/adm/templates/principal.xhtml">
<ui:define name="content">
<rich:panel header="#{msgs.usuariosNuevo}">
<h:form id="formUsuariosNuevo" prependId="false">
<h:panelGrid columns="3">
<h:outputText value="#{msgs.email}" />
<h:inputText value="#{usuarioCtrl.mdl.email}" id="email" />
<h:outputText value="#{msgs.pwd}" />
<h:inputSecret value="#{usuarioCtrl.mdl.pwd}" id="pwd" />
</h:panelGrid>
<a4j:commandButton value="#{msgs.guardar}" action="#{usuarioCtrl.guardarUsuarioAction}" />
</h:form>
</rich:panel>
</ui:define>
</ui:composition>
... and the 'top' toolbar menu menu.xhtml:
<h:form prependId="false" id="formMenu">
<rich:toolbar height="26px">
<rich:dropDownMenu mode="ajax">
<f:facet name="label">
<h:panelGroup>
<h:graphicImage value="/resources/img/icon/usuarios.png" styleClass="pic" width="20" height="20" />
<h:outputText value="Usuarios" />
</h:panelGroup>
</f:facet>
<rich:menuItem label="Nuevo" action="#{menuCtrl.usuariosNuevoAction}" icon="/resources/img/icon/nuevo.png" />
<rich:menuItem label="Gestión" action="#{menuCtrl.usuariosGestionAction}" icon="/resources/img/icon/gestion.png" />
</rich:dropDownMenu>
<!-- Others dropDownsMenu's here ... -->
</rich:toolbar>
</h:form>
thanks!
I think the problem happens when you're using JSF #ManagedBean. You need declare that form bean variable in current flow.
I'm using Richfaces 4.2, Spring-web-flow 2.3.0, Spring 3.1.1
formbean
#RequestScoped
#ManagedBean
public class SearchForm implements Serializable {
private static final long serialVersionUID = 1L;
private String pattern = "Please insert";
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
home-flow.xml
<var name="searchForm" class="com.inhouse.web.form.SearchForm"/>
<view-state id="home" view="home.xhtml" model="searchForm">
<transition on="search">
<evaluate expression="searchController.search(requestParameters.pattern)" result="flashScope.searchResults"></evaluate>
</transition>
</view-state>
home.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:sf="http://www.springframework.org/tags/faces"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<ui:composition template="/WEB-INF/layouts/template.xhtml">
<ui:define name="content">
<h:form>
<h:inputText value="#{searchForm.pattern}" />
<a4j:commandButton action="search" value="Search" render="searchResult" immediate="true">
<f:param name="pattern" value="#{searchForm.pattern}"></f:param>
</a4j:commandButton>
</h:form>
<h:panelGroup id="searchResult">
<h:outputText value="#{searchResults}" />
</h:panelGroup>
</ui:define>
</ui:composition>
</html>
Controller
#Controller
public class SearchController {
public String search(String pattern) {
return "this is the search results";
}
}
I've tried to follow different posts on how to handle the ViewExpiredException in Mojarra 2.1.0 (with RichFaces 4) on GlassFish 3.1. But what I define in web.xml doesn't seams to have any effect. I use form base security and the user has to logon to access the content. I just want Glassfish (catalina) to redirect the user to a simple JSF page when the session times-out, with a link back to the login page.
I always get the the following error message;
javax.faces.application.ViewExpiredException: viewId:/app_user/activity/List.xhtml - View /app_user/activity/List.xhtml could not be restored.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:202)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:113)
Who can I redirect the user when the user session has timed-out and trap the exception in the server log ?
Greetings, Chris.
layout.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- Had no effect
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
-->
<h:outputStylesheet name="css/default.css"/>
<h:outputStylesheet name="css/cssLayout.css"/>
<title>
<h:outputText value="Partner Tapestry - " /> <ui:insert name="title">Browser Title</ui:insert>
</title>
</h:head>
<h:body>
<div id="top" >
<ui:insert name="top">Top Default</ui:insert>
</div>
<div id="messages">
<rich:messages id="messagePanel"/>
</div>
<div id="content">
<ui:insert name="content">Content Default</ui:insert>
</div>
</h:body>
</html>
web.xml
...
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
2
</session-timeout>
</session-config>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/faces/resources/sessionExpired.xhtml</location>
</error-page>
...
login.xhtml
<ui:composition template="/resources/masterLayout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:a4j="http://richfaces.org/a4j">
<ui:define name="title">
<h:outputText value="Login"></h:outputText>
</ui:define>
<ui:define name="top">
<h:outputText value="Welcome" />
</ui:define>
<ui:define name="content">
<h:form>
<h:panelGrid columns="3">
<h:outputLabel for="username" value="Username" />
<h:inputText id="username" value="#{userController.userAuthentication}" />
<br />
<h:outputLabel for="password" value="Password" />
<h:inputSecret id="password" value="#{userController.passwordAuthentication}" />
<br />
<h:outputText value=" " />
<a4j:commandButton action="#{userController.login()}" value="Login"/>
</h:panelGrid>
</h:form>
</ui:define>
</ui:composition>
finally sessionExpire.xhtml
<ui:composition template="/resources/masterLayout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:a4j="http://richfaces.org/a4j">
<ui:define name="title">
<h:outputText value="Session Exired"></h:outputText>
</ui:define>
<ui:define name="top">
<h:outputText value="Session expired, please login again" />
</ui:define>
<ui:define name="content">
<h:form>
<a4j:commandLink action="/resources/login?faces-redirect=true" value="Login" />
</h:form>
</ui:define>
</ui:composition>
Your approach should work perfectly fine for synchronous POST requests. However, you're using asynchronous (ajax) POST requests. Exceptions on ajax requests needs to be handled by either the jsf.ajax.addOnError init function in JavaScript or a custom ExceptionHandler.
See also
javax.faces.application.ViewExpiredException and error page not working
JSF: Cannot catch ViewExpiredException
Solved the problem by following this link on implementing a ExceptionHandlerFactory. A nice solution where you can have an exception navigation rule, but maybe a bit long. Thanks for the help #BalusC.