jQuery Address - redirect after form submit - java

I use jQuery and AJAX to load content from links and forms into a content div. In addition I use the Address plugin to enable the back button and refresh. On the server side I use Java and Spring MVC.
Since I'm using jQuery Address and AJAX the only page that is directly loaded is "index.html". Everything else is loaded into a content div, and what page to load is specified in the hash, ie. "index.html#/users/add.html" will load "users/add.html".
Now, "users/add.html" contains a form for creating a new user. When the form is submitted and everything went OK, the controller redirects to "users/index.html". The problem is that jQuery Address doesn't know about the redirect, so the url will remain "index.html#/users/add.html". And this is a problem when you refresh the page and then get sent back to the form, instead of the index page.
Is there a way to fix this problem?
Thanks,
Stian

Take a look at the new Form Sample. It's very basic but will be probably usable.
http://www.asual.com/jquery/address/samples/form/
In your case you won't be able to use $('form').address() function because you will want to change the address after the server response comes back.
You can use a data.redirect property to detect potential response redirects:
How to manage a redirect request after a jQuery Ajax call

I realize my description of the problem wasn't the best, apologies for that.
I reformulated the problem in another question, got no answers but I found a solution myself. :)
AJAX - Get response URL after redirect

First I init my form like that :
$('FORM').submit(function () {
shareData = $(this).serializeArray();
$.address.value($(this).attr('action'));
})
after I have in my change method something like that :
$.address.change(function(event) {
if (event.path != '/' && event.parameters.layout_to_use != undefined) {
// if no json, load don't do a post request
shareData = _arrayToJson(shareData);;
$('#areatoreload')
.html('<span style="background-color:red;">loading...</span>')
.load('myscript.php', shareData, function() {});
}
return false;
});
And i manage my link in the same way. I hope it can help you. shareData is not a very good way, but i don't find something else for the moment. this code is not tested, I just extract some part of my own code.

Related

Why doesn't forwardResolution redirect?

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.

Java play onRouteRequest - how to return an answer?

I'm using java-play 2.2.1.
I created JS code that send AJAX GET request with a url address that doesn't exist in the conf/routes file. It would be complicated to describe why i don't want to declare this URL at the routes file, so just take it as fact :) .
I catch this request by overriding OnRouteRequest
function (by creating Global object..), and i pull the get params from the request query string (because it's a GET request) and create an object (hashtable) i want to return to the AJAX code at the client-side. Unfortunately, OnRouteRequest function returns Handler.
I'm really desperate right now from this issue, if anyone has any idea how can i do it, it would be really great. Even if anyone knows how to redirect from OnRouteRequest to another action which will return after to the AJAX it would be great. Thanks !

Establish Connection First, Redirect User Second

I have an idea to make something pretty sweet but I'm not sure if it's possible. Here is an example of a very basic ajax function that I might use to establish a connection a server...
function getFakePage(userId)
{
var ajaxObject, path, params;
ajaxObject = getAjaxObject();
params = "?userId=" + userId
path = getInternalPath() + "someServlet" + params;
ajaxObject.open("GET", path, true);
ajaxObject.send();
// On ready state change stuff here
}
So let's say I have a URL like this...
https://localhost:8443/Instride/user/1/admin
And I wanted to use javascript to redirect the user to this this URL. Normally I would just do this...
window.location = "https://localhost:8443/Instride/user/1/admin";
But my idea is to create a javascript (no js frameworks please) function that could combine the ajax code with the window.location code. Basically what I would like to accomplish is to create a connection with the server via ajax, send a servlet on that server the url I would like the user to be redirected to, and then redirect the user to that URL. So that for however long it takes the user to connect to my server from wherever they are in the world they see a loading icon instead of a blank white page.
So to clarify exactly what I am trying to accomplish; I do not want to put window.location within the success of my ajax function (because that would be encompass two round trips), and I do not want to return a huge chunk of HTML for the requested resource and add it to the page. I want to establish a connection to the server with ajax, send a servlet the URL the user wants to go to, and then somehow override the ajax function to redirect that user. Is this possible?
And I know some of you might think this is stupid but it's not when you're talking about overseas users with slow dial up connections staring at white pages. If it's possible, I'd love to hear some insight. Thank you very much!
First, let me say that the best solution is finding what is causing the slowness and fixing it.
Now as to your question, yes you could do it. You could even shoehorn it onto an existing application. But it wouldn't be pretty. And it comes with it's own set of problems. But here are the steps:
Browser calls ajax cache service requesting "somepage.html"
Browser loads loading icon
Server creates somepage.html and caches it in a temporary cache, (ehcache or other library would be good, probably with file backing for the cache depending on size)
Server responds to ajax request with ID for cached page
Browser now redirects to "somepage.html?cacheId={cacheId}" where the id is from the ajax call.
Server uses a filter to see if any cache can be served up for the page instead of the actual page, thus speeding up the request.
Having said that, it would be better to just have the new page load quickly with a loading icon while it did any of the heavy lifting through ajax.
You can't do an AJAX request and a location change in one. If you want to do only one request you have to choose one of those methods. ie. return some data and replace content on your current page, or load a completely new page.
It doesn't make any sense to want to want to do both. What you could want is stateful URLs; where your URL matches the content displayed, even if that content comes from an AJAX request. In that case an easy solution is the use the # part of the URL which you can change freely (window.location.hash). Some modern browsers support changing the whole URL without causing the page to reload. I've used # with great success myself.

Java Servlets, how to keep request attribute alive across several forwards?

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.

how do i know whether my html link is clicked or not from Servlet?

My Servlet response type is html and my response contains a hyperlink to another web site.So, now i want to capture the information about whether the user clicked the link or not? and also calculate the total clicks? i am using Tomcat 7 as a server.
Is this possible in setting response header (302 or 404)?...
Please Guide me to get out of this issue?
Yes, you can use a 302: instead of providing the link to the other website, you provide a link to your own servlet, do your accounting and then send back a redirection (301/302) http status with the other web-site URL in the response Location header.
This maybe a bit simplistic though, since the user will leave your original page (is this what you want ?) and search engines may not like this if your web app is public.
I think right now you are redirecting the request(link for another website) at client side.In this approach your server cannot get the information about the click.
What you can do create a servlet and call this servlet on click now this servlet is responsible to redirect the request to another website. Add an static integer counter and increment this when servlet call each time.
Use the method setStatus():-
setStatus(HttpServletResponse.SC_FOUND);
or
setStatus(HttpServletResponse.SC_NOT_FOUND);

Categories