hi I am querying database to load all items based on some criteria and setting this result in session as
data = service.getData();
session.setAttribute("data", data);
now I am trying to access this data via an Ajax call and my Ajax call is served by a different servlet rather then which fetched the data from DB.
Ajax call using jquery
$.ajax({
type: "POST",
url: "/com/tp/AjaxXML.jsp",
data: ({cmd: "report"}),
dataType: "xml",
success: function(xml) {
$(xml).find('site').each(function(){
var url = $(this).attr('url');
});
}
});
in my AjaxXML.jsp
I am doing
if("report".equals(cmd)){
List<Object> data = (List<Object>)request.getSession().getAttribute("data");
if(data == null){
System.out.println("data is null ");
}
}
every time I am getting the data as null via the Ajax call how ever I try to access the session data normally from my first servlet it works.
could someone let me know if I am doing something wrong?
I noticed one more thing when we do session.getId(); and pageContext.getSession().getId();
both of them are returning different Id's? Is this expected to me they should be same anyone differ on that?
I noticed one more thing when we do session.getId(); and pageContext.getSession().getId(); both of them are returning different Id's? Is this expected to me they should be same anyone differ on that?
No, they should definitely not differ. I however assume that you have examined them within the same request. If you examined them in different requests, then the difference can be explained by the absence of the proper JSESSIONID cookie. Cookies are domain and context specific. You're apparently sending the ajax request to a different domain/context. The leading slash / in the ajax URL also confirms this less or more. Make sure that you're sending it to the same domain/context. Use a context-relative URL, something like as url: "AjaxXML.jsp" and move the code to the same domain/context, or turn on session sharing between different contexts at server level.
Unrelated to the concrete problem, doing the Ajax response handling in a JSP is a bad idea. Rather do it in a servlet.
Replace
url: "/com/tp/AjaxXML.jsp",
by
url: "/com/tp/AjaxXML",
and put the code in doPost() method of the servlet which is mapped on that URL pattern.
See also:
How to use Servlets and Ajax?
Related
I'm new to Stripes and I'm trying to do like this: pass data from JSP1 using Ajax to the actionBean2 which belongs to JSP2 and then display the data on JSP2.
I do like this because JSP2 provides common interface for everything, and I want to redirect the user to JSP2 so that he/she could see the items that were selected in JSP1 using the standard interface of JSP2.
So, the problem occurs when I'm trying to pass the data from ActionBean2 to JSP2. Even though my return statement of actionBean2 looks like this:
return new ForwardResolution("/jsp2.jsp");
It actually doesn't redirect me from JSP1 to JSP2. RedirectResolution doesn't work as well.
I see the AJAX request from JSP1 being sent, the event handler in ActionBean2 receives it but doesn't redirect me from the JSP1. JSP1 even gets GET request for JSP2 url, but still the page doesn't reload. So, it looks like even though I'm in ActionBean2, it still uses JSP1.
My question is - should ForwardResolution redirect me to another page immediately (and reload the browser page)? And also - it my idea of passing data between these pages and actionBeans correct?
OK, I had to use a workaround, which I don't like at all. Still, it works. but if you have any suggestions, please, write.
I passed the parameters from JSP1 to JSP2 in URL using JavaScript redirect. Straight-forward method, but it solved the problem (JSPs didn't redirect when I tried to redirect using Resolution):
window.location.href ="jsp2.jsp?myparameters"+$.param(myparameters);
In JSP2 I used AJAX to call JSP2 actionBean.
if (window.location.search.indexOf("myparameters") != -1){
values = window.location.search.substr(window.location.search.indexOf("myparameters"), window.location.search.length);
values = decodeURIComponent( values );
//some parsing here, didn't include it
$.ajax({
url: "JSP2.action?from_redirect=",
data: {values: values},
type: "POST",
success: function(data) {
displayValues(data)
}
});
And in JSP2.action I made the from_redirect listener return:
return new StreamingResolution("application/javascript", data);
So, this method works, but I don't like 1 extra redirect.
if you have any suggestions, how to solve the problem with Resolutions, please write them. Also I would appreciate any help concerning removing extra redirects in this method.
I am using Jquery Ajax calls to access REStful webservices as below. The webservice is hosted on different domain.
$.ajax({
type: "GET",
url: "some url hosted on differnt domain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(responseJson) {
alert("json"+responseJson);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
Am not sure whether it is not hitting the webservice.It is going to error block but no alert is displayed. Am i doing anything wrong here?
Thanks!
You got to change the Header at you server side http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
Since it will cause forgery. For more of cors understanding http://enable-cors.org/server.html
You can't make cross domain request just like that. It might cause cross-site forgery. Check this-
http://en.wikipedia.org/wiki/Cross-site_request_forgery
Basically, to be able to do so, the server should allow you to do that. If you access some resource on a cross domain server. The server responds back with a list of allowed users for that resource. The browser reads that list. If you are not listed in that list then the browser won't show the resource to you.
Solutions:
1- You should have control of the server side.
2-you can try 'script' tags in HTML for your purpose. They are an exception to this. You can make cross-domain requests using 'script' tags and then parse the response as json.
3-Jsonp callbacks.
I haven't actually implemented in much detail because I have control over server side whenever I need. And, CDNs are open to all. So, you might want to do some reading now to figure out more.
I have a home-grown MVC implementation. A ControllerServlet like so:
/controller?cmd=EditUser&userid=55
From this URL, the controller creates a EditUserCommand.class instance and calls an execute() method which returns the result page (ex. user.jsp) to display.
The controller servlet then does a ...
getRequestDispatcher(resultPage).forward(request, response);
... and the resulting page is shown.
One of the things the controller does is set messages (error, info, and so on) as request attribtues. For example:
request.setAttribute("infoMessage", "User was edited successfully.");
And that message gets pulled out of the request in the user.jsp page and displayed.
Works fine.
Now here comes my problem.
Sometimes my commands don't return a page like user.jsp but return a URL like cmd=ShowUser&userid=55 for the result. This is because there might be things I want to check before displaying the final page, like permission to view the user and so on.
When I do this the "infoMessage" I placed in the request never appears because the result is a URL that makes a new call to the servlet, which is a new request. The new request doesn't maintain the request attributes from the first request; which makes sense, I just didn't forsee this happening.
How can I make my request variable "stay alive" until it's actually displayed on the final page that results from the original request?
Any suggestions or advice are appreciated. Just FYI, I can't re-write the entire app to go to something like Struts, Spring MVC, of JSF. It's not an option.
Thanks!
Rob
redirect generally looses request data because of brand new request from browser. One possible approach may be append your message to url string as attribute and read it when you need.
Based on your EDIT: After your edit also, my answer make sense. But, only one correction is, it is not brand new request because forward happens on server side.
Have you tried using a RequestDispatcher instead of a Redirect?
RequestDispatcher dispatcher = request.getRequestDispatcher("/myNextPage.jsp");
dispatcher.forward(request, response);
You may be giving a simple example, but your control flow causes the "Resend" Error, perhaps? Basically, after making any change to the data, the controller must immediately do a "Get" via a redirect and the screen should be displayed completely stateless.
Please take a look:
http://en.wikipedia.org/wiki/Post/Redirect/Get
As such, Attributes are not a great help. What you may want to consider is, maintaining a Bean/Object for every login user, and persist this object in a LRU cache (JCache or MemcacheD), and retrieve it on every entry to the application. Once you have that, you can maintain a pseudo-state such as previous results in that object.
In any case, using Attributes to retain state will severely constrain your options. You need to have a more generic flexible routing-independent mechanism.
I am working on a Web application and need to pass data across HTTP redirects. For example:
http://foo.com/form.html
POSTs to
http://foo.com/form/submit.html
If there is an issue with the data, the Response is redirected back to
http://foo.com/form.html?error=Some+error+message
and the query param "error"'s value is displayed on the page.
Is there any other reliable way to pass data across redirects (ie HTTP headers, etc.).
Passing the data as query params works but isn't ideal because:
its cleartext (and in the query string, so SSL cant be relied on to encyrpt) so I wouldn't want to pass sensitive data
URIs are limited in length by the browser (albiet the length is generally fairly long).
IMPORTANT: This platform is state-less and distributed across many app servers, so I can't track the data in a server-side session object.
From the client-server interaction point of view, this is a server internal dispatch issue.
Browsers are not meant to re-post the entity of the initial request automatically according to the HTTP specification: "The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD."
If it's not already the case, make form.html dynamic so that it's an HTML static file. Send the POST request to itself and pre-fill the value in case of error. Alternatively, you could make submit.html use the same template as form.html if there is a problem.
its cleartext (and in the query string, so SSL cant be relied on to
encyrpt) so I wouldn't want to pass sensitive data
I'm not sure what the issue is here. You're submitting everything over plain HTTP anyway. Cookie, query parameters and request entity will all be visible. Using HTTPS would actually protect all this, although query parameters can still be an issue with browser history and server logs (that's not part of the connection, which is what TLS protects).
I think using cookies would be a reasonable solution depending on the amount of data. As you can't track it on the server side (by using a sessions for example, which would be much simpler)
You can store error message in database on server and reference to it by id:
http://foo.com/form.html?error_id=42
If error texts are fixed you even don't need to use a database.
Also, you can use Web Storage. Instead of redirection with "Location" header you can display output page with this JavaScript:
var error_message = "Something is wrong";
if( typeof(Storage) !== "undefined" ) {
localStorage.error_message = error_message;
else {
// fallback for IE < 8
alert(error_message);
}
location.href = "new url";
And after redirection you can read localStorage.error_message using JavaScript and display the message.
I have one application where i have three jsp pages, from index.jsp , control goes to process.jsp and after execution control goes to result.jsp to display data. But i want that instead of displaying data in result.jsp, control will go to another url so that that receiver url will get the requested data. that is: my url is 100.20.3.45:8085/myproject/index.jsp then after processing data i want that result should go to a different url of my same network i.e. 100.20.3.46. How can I send the requested data to this different url?
Ex:
100.20.3.45:8085/myproject/index.jsp
goes to
100.20.3.45.8085/myproject/process.jsp
after processing control will go to 100.20.3.46.
How can I send this data to a different url? what is this mechanism called?
It's called "redirecting". It's to be achieved by HttpServletResponse#sendRedirect().
response.sendRedirect(url);
If you want to send additional data along, you'd need send it as request parameter(s) in a query string, but they will be visible in the URL in browser's address bar. If that isn't affordable, consider storing it in a shared datastore (database?) and then pass alone the unique key along.
Alternatively, you can also just let the <form> action URL point to that different host directly without the need for an intermediate JSP. As another alternative, you could also play for proxy yourself with help of for example URLConnection.
Unrelated to the concrete problem: having controller/business logic in JSPs is a bad practice. I suggest to take some time to learn about servlets.
Redirect to URL
window.location.href = "url"
Examples of use
window.location.href = "/process_payment";
var username = #json($username);
window.location.href = '/' + username;
window.location.href = '/{{ $username }}';