简体   繁体   中英

How to let my configured session work in AJAX

I have this interceptor function where I configure my session.

if (request.getRequestURL().indexOf("profile") > 0) {
    if (session.getAttribute("access").equals("sub-admin")) {
        System.out.println("This is request to profile - admin");
    } else {
        System.out.println("This is request to profile - user");
        response.sendRedirect(request.getContextPath() + "/error"); //ERROR HERE YOU ARE JUST A USER NOT AN ADMIN, I WILL REDIRECT YOU TO ERROR PAGE
    }
}

Now I am using jQuery and AJAX in my front end.

If I am just a user and I will access localhost:8080/sample/profile , It will work. It redirected me to the error page.

But, when I access it in my menu in the home page and click profile, it doesn't work.

I think it is because I am using AJAX and the path doesn't change, the view only.

$.ajax({
    url: ROOT_URL + '/sample/profile',
    type: "get",
    dataType: "text"
}).done(function(data) {
    $('#idcontainer').html(data);
});

How do you let the session work in my AJAX front end?

If you'd like to handle the redirect from an AJAX call, you can take a look at the following question:

A better solution might be to check if the request is AJAX, and send a JSON response with an HTTP status that you can handle on the frontend:

JSON Response:

{
    "error": "Unauthorized",
    "message": "You must be logged in to view this content",
    "code": 401
}

And in your interceptor:

boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
if (ajax) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.getWriter().write(responseToClient);
    response.getWriter().flush();
    response.getWriter().close();
} else {
    response.sendRedirect(request.getContextPath() + "/error");
}

Note that not all AJAX libraries include the X-Requested-With header, but jQuery along with most other modern libraries do.

Then in your JavaScript function:

$.ajax({
    url: ROOT_URL + '/sample/profile',
    type: "get",
    dataType: "text"
}).done(function(data) {
    // handle success HTML
}).fail(function (data) {
    // parse JSON and alert error message
});

In addition, it seems that you're using the AJAX request to replace the contents of the page with the HTML returned from the AJAX request. Instead of using a JSON response, you could also just return the error HTML instead and display that in the same way that you are returning the profile HTML content:

HTML response:

<h1>Error</h1>

<p class="error">You must be logged in to view this content.</p>

And set the HTML the same way as in your done callback:

.fail(function (data) {
    $('#idcontainer').html(data);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM