Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsp response.redirect causes problems with jquery.mobile

Tags:

java

jquery

jsp

My application is build with jsp pages and jquery.mobile. I use a Java function to check login status and do a redirect when that's not OK from within a Bean like this:

public String getMenu(HttpSession session, HttpServletResponse response, MenuType menuType, CurrentPage currentPage)
{
    if (session.getAttribute("state") == LoginChecked.UNDEFINED))
    {
        response.sendRedirect("../index.jsp");

        return null;
    }
    else
    {
        ...

The problem is that the redirect to index.jsp is handled by jquery.mobile as an ajax reload of the content of the page, and not a complete redirect.

How can I force a complete reload of the browser of the index.jsp page?

-- ADDED --

Within html this would be solved with the "rel" attribute like this, so I would need some kind of method to use this rel from within my Java sendRedirect:

<a href='../index.jsp' data-role='button' data-icon='plus' rel='external'>
like image 762
Frank Avatar asked Mar 06 '26 02:03

Frank


2 Answers

I was looking at solving a similar problem myself recently (actually redirecting when an AJAX request is redirected), and found a very good answer on here that I apparently didn't bookmark. However, having successfully implemented it for myself, I'll share the approach I took based on that answer.

The first stage was to identify AJAX requests so they can be handled differently to standard requests. This can be done by checking the value of the X-Requested-With request header; a value of XMLHttpRequest indicates an AJAX request. In the case of a standard request, we proceed with the redirect as normal. In the case of handling an AJAX request, rather than proceeding with the redirect, what I did is set a response header to signify that a redirect would have occurred, and set its value to the URL that I want to redirect to.

Then, I used the following jQuery code to check all completed AJAX requests, and redirect when appropriate:

$(document).bind('ajaxComplete', function(event, xhr, options) {
    var redirectHeader = xhr.getResponseHeader('YourHeader');
    if(xhr.readyState == 4 && redirectHeader != null) {
        window.location.href = redirectHeader;
    }
});
like image 97
Anthony Grist Avatar answered Mar 07 '26 14:03

Anthony Grist


within ajax you will have to do like this :

success: function(data, textStatus) {
        if (data.redirect) {
            // data.redirect contains the string URL to redirect to
            window.location.href = data.redirect;
        }
}

this will redirect you to webpage specified within data by the server

like image 42
Harmeet Singh Avatar answered Mar 07 '26 15:03

Harmeet Singh