Re: Redirect to the saved first requested url after loggin.

Splash Forums PrettyFaces Users Redirect to the saved first requested url after loggin. Re: Redirect to the saved first requested url after loggin.


I don’t think this is the best way to handle such a requirement.

Here are some code examples taken from my project. Perhaps they will help you:

My Filter:

public class AuthenticationFilter implements Filter {

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;

String uri = request.getRequestURI();

/* TODO: authentication */
boolean authenticated = .....

if(authenticated) {

chain.doFilter(servletRequest, servletResponse);


// redirect to login page
response.sendRedirect(request.getContextPath() + "/login?url="+URLEncoder.encode(uri, "UTF8"));


/* .... */


So this filter will redirect all users that are not authenticated to the login page and adds the original URL to a query parameter named url.

Here is my LoginBean that handles the authentication on the login page:

@URLMapping(id = "login", pattern = "/login", viewId = "/login.jsf")
public class LoginBean {

private String username;

private String password;

private String redirectUrl;

public String login() {

User user = userDao.getUserByUsernameAndPassword(username, password);

if(user == null)
MessageUtils.addLiteralErrorMessage("Invalid username or password.");
return null;

if(redirectUrl != null) {

try {

// redirect to 'redirectUrl'
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
return null;

} catch (IOException e) {
throw new IllegalStateException(e);

} else {
return "pretty:home";


/* .... */


So after a successful login the bean will simply do a redirect to the URL found in the query parameter. If the query parameter does not exist for some reason, the user is redirected to a default page.

I think this is the most elegant way of handling such things.