How to let my configured session work in AJAX - java

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:
How to manage a redirect request after a jQuery Ajax call
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);
});

Related

Sending Request to JSP file based upon AJAX POST [duplicate]

This question already has an answer here:
JSP not returning data to JQuery AJAX
(1 answer)
Closed 4 years ago.
I am trying to send a post request to Java servlet, execute a query based upon this value, and send the information to a jsp file. The query in entered from a text box, and when the user hits enter, I need to jump to a new page to display the value of the query.
This is my post request to the servlet:
$.ajax({
"type": "POST",
// generate the request url from the query.
// escape the query string to avoid errors caused by special characters
"url": "Search",
"data": {query : query},
"success": function(data) {
console.log("normal search successful");
},
"error": function(errorData) {
console.log("lookup ajax error")
console.log(errorData)
}
})
I get the AJAX post with:
String title = request.getParameter("query");
//peform action to get results...
then forward request to JSP page with:
request.getRequestDispatcher("movielist.jsp").forward(request, response);
I am getting no errors but the screen doesn't redirect to the new page in my app...
Am I missing something major here?
Nothing happens because you do AJAX call - the request happens in the background of the page, and therefore when ajax receives response from JSP - it stays "in the background" - the success handler is triggered.
What you could do - is to do regular form submit - then navigate from JSP as you mentioned.
Otherwise - if you prefer to keep AJAX, you can do a redirect manually in the success handler with:
"success": function(data) {
window.location = "<your URL here>";
...
The URL to redirect to you can pass from JSP that can return json object with it. Hope this helps.
AJAX works correctly, if you look # console it should be print a line. Do your redirect part in your success block.

Render page after ajax request

I'm using HightCharts library to draw some charts under Play Framework. I've set up an ajax request when the user click on the chart. The request returns a Result with a page rendered. I'd like to perform a redirect to the rendered page.
This is the snippet code of my request:
plotOptions:{
column:{
colorByPoint: true
},
series: {
cursor: 'pointer',
point: {
events: {
click: function (event) {
var jsonMsg = JSON.stringify({category: data.categories[event.point.y], product: data.products[event.point.x]});
$.ajax({
type: 'POST',
url: '#namespace.controllers.modules.routes.MailchimpController.createSegmentByCorrelation()',
data: jsonMsg,
contentType : 'application/json; charset=utf-8',
dataType: 'json'
});
}
}
}
}
}
And this is my return statement:
return ok(template.render(
RolesDao.getRole(session().get("role")),
session("email"),
Template.getList(apikey),
segmentId.toString()));
Any ideas about how I can do it?
With your ajax action you don't can't return the rendered page (HTML code de facto), instead just create link to the page which will render as common Result.
Note: if parameters can contain sensitive data like some credentials, it's worth to add some effort, i.e. in AJAX action save the parameter set in DB or Cache with some unique ID and random security token and return the redirect URL with this ID and security token, later you'll be able to retrieve these credentials using given ID and render the view in your target action. Security token is to prevent the crawlers from unauthorized access.
De facto using built-in cache API you can just put the Result within the cache, so it could be quite fast solution.

Struts 2 Interceptor redirection not working with Ajax

I have configured Struts 2 Interceptor for validating the user session. On invalid session I am redirecting to an error page.
The Interceptor is working fine for the normal calls to the action classes but the error page redirection is not working when I am calling an action class through ajax call.
What I am currently doing for this is sestting a request attribute in the interceptor and on the JSP based on that attribute value redirecting from the JSP.
But instead of what I am doing is there any way by which I dont need to write any thing in JSP for error page redirection to work in the similar way when calling the action class in a normal way and in the form of Ajax
Thanks,
Vinay
In the interceptor, set the response status to UnAuthorized just before we return the errorpage.
httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
return "errorPage";
In the ajax call where we make a request that ends up in session timeout and redirect, put a error handling block and redirect to the page directly here.
$.ajax({
url : "some.action",
data : {
"query" : inputText
},
type : 'GET',
dataType : 'json',
success : function(data) {
//code
},
error : function(data) {
if (data.status == 401 ){
console.log("UnAuthorized. Redirecting to Error");
window.location.replace(contextPath +"/error.jsp");
}
}
Have a struts entry for the errorpage to avoid any config issues.
<result name="errorPage">errorPage.jsp</result>

Calling servlet to load the data using jquery ajax?

I am new to JQuery. I have a servlet which will fetch data from the database and the result is kept is request and the same result is retrieved in jsp file. Now i have to call the servlet using ajax jquery to load the data. I am doing as below. But it is not loading. Please help me.
$('#myForm #revert').click(function() {
$.ajax({
type: "GET",
url: "./myController",
success: function(msg) {
<span style="color:green;font-weight:bold">Successful</span>');
},
error: function(ob,errStr) {
//Todo
}
});
});
Servlet code:
//Service call gets data and the result is kept in request scope as below
request.setAttribute("myresult", result);
request.getRequestDispatcher("/WEB-INF/myScreen.jsp").forward(request, response);
Thanks!
Ajax is not a normal HTTPRequest,You canot Forward or sendRedirect a Ajax request
Since it is Asynchronous,you need to write the response for Ajax request
PrintWriter out = resp.getWriter();
out.println(resultString);
return;
Please read #Balusc great answer :How to use Servlets and Ajax?

What if targeting URL is not returning back

This is the sample code I am using to hit a URL with fixed time interval.
$(document).ready(function() {
var counter = 1;
$.doTimeout( 1000, function() {
$.ajax({
type: "GET",
url: "<%=encodeUrl%>",
timeout: 10000,
dataType: "text",
complete: function(resp) {
if (resp.status == 200) {
$("#msg").html(counter++);
} else {
$("#msg").html("Failed");
return true;
}
}
});
});
});
Target URL is a servlet which is forwarding the control to another JSP. As per my understanding I must be redirected to new page. But it is showing the same page with the counter value 1. Means, redirect from target servlet is not working. And response is coming back to the same page.
When your AJAX response is a redirect to another page, the redirected page will be fetched as the response of your AJAX request, that's why your are getting only 200 as HTTP status.
You cannot handle redirects based on the HTTP Status codes that you receive with AJAX.
An AJAX response cannot redirect you to a different page unless you program it to do so.
So if you want to redirect based on your AJAX response, you should modify your server side code to send you the redirect URL as a response, rather than redirecting.
Refer one of answers with example solution
AJAX isn't meant to redirect. These headers don't get executed by your browser thus letting you stay on that page!
What is the exact code your servlet gives back?
The code is doing exactly what its written to do. You are firing an ajax call, and on response 200 you are setting counter as html for #msg. There is nothing in the code that'll make you redirect to the New Page.
You do not need ajax here if you want to redirect. Else, if your redirect is based on response returned by the servlet, capture it in complete and set window.location.href = 'your/redirect/url/' to load the New Page.

Categories

Resources