session attribute not being set until I refresh thepage - java

I have some code:
$(document).ready(function(){
$(":button").click(function(){
var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", formData, function(response){alertHere(response)});
})
})
function alertHere(response){
alert("Post successful");
alert(response);
renderResults();
}
that posts form data and queries for the data and sets the session attribute with
session.setAttribute("directoryString", xml);
when a button is clicked. In the response function, renderResults is called, which grabs the returned xml:
function renderResults(){
alert("inside renderResults()");
element = document.getElementById("person");
xmlString = '<%=session.getAttribute("directoryString")%>';
console.log('XML String: ' + xmlString);
The rest of the function is written to parse out the xml and display it on the page.
My problem is that when I first go to the page and post data, the xmlString variable is null. When I refresh the page and go back to "Page Source" in my web console, the variable is set correctly. I'm not exactly sure what's going on. Is it possible that my function is trying to call the session attribute before it's set?
P.S. I know that scriplets aren't the best way of doing it, but that's the way we do it around here.

<%=session.getAttribute("directoryString")%> will only be evaluated when the JSP is rendered into the HTML page. Once the rendered HTML is in the browser, it can only be changed either by:
reloading the page
JavaScript.
Make an ajax call to get the updated value of the attribute and update the variable (for example, you can set document.myXmlString = '' and use that value in your renderResults.

Related

Grails get url of originating controller

I have a URL say abc.com/somecontroller?someparam=1 which renders a form. Form on submit sends the form params to /ajaxAction
Is there a way I could get this abc.com/somecontroller?someparam=1 (i.e. the form URL?)
I am more interested in getting the someparam value from the URL of the form.
PS: the above URL abc.com/somecontroller?someparam=1 is dynamically generated, so I can not access it otherwise.
And request.forwardURI will give me /ajaxAction (i.e. the URL of the action in form and not the url of the form itself).
EDIT:
I have no control over form as it is also dynamic and user has hundreds of templates to select from. Each template has different no. of fields.
So if I would prefer some other way to get the URL.
Why don't you use javascript in form and add to ajax request array with GET params? (or with the url of the action which generated form)
You can get them from original request f.e. by this script.
While rendering the GSP of your form, you can do like this:
myaction.gsp
<html>
<body>
<!-- Your content -->
<script>
var paramsString = '${params.collect { k, v-> "$k=$v" }.join​​​​​​​​​​​​​​​​​​​​​​("&")​​​ }';
</script>
</body>
</html>
So, when you GSP is rendered, the script tag will have something like this (for a URL abc.com/somecontroller?someparam=1&foo=2:
var paramsString = 'someparam=1&foo=2';
Now, in your AJAX code, you can pass that string as the query arguments:
$.ajax({
url: '/ajaxAction?' + paramsString
/* rest of the AJAX code */
});
Now, in your ajax controller action, you can simply do the params.someparam.
EDIT
Well, I just realized that you don't have to any GSP stuff I mentioned above. Simply do the AJAX call like this:
$.ajax({
url: '/ajaxAction' + location.search
/* rest of the AJAX code */
});
The location.search will give you the direct string: ?someparam=1&foo=2
I ended up using flash to store the someparam
In my controller which is being used to render the form at abc.com/somecontroller?someparam=1 I use flash as this:
flash.put("someparam", params.someparam)
This worked as a quick workaround to the issue. I feel this would work well in situations where I have no control over the gsp.
If anyone finds any issue, please comment otherwise I will mark this as the answer.

Can we use jQuery to work with Java objects OR does it manipulate DOM model only?

I have a very complex scenario where i need to change the java objects(basically HashMap ) from jquery get Request and get the response and print that in the jsp. User can send number of request and get seperate response from servlet based on request and display the data.
after every request i have to put the map in session and than in another request i get the same in session and do the updates and put it back in session.
JqueryGet(parameter) to Java.
Updating Hashmap according to parameter.
Putting hashmap in session . ( session.setAttribute("map",map))
sending response back to Jsp in jquery and print results in jsp.
Than another request send to Java .
it will get the map from session session.getAttribute("map",map) and than update the map based on new request .
Put the map again in session and so on....Than i have a submit button finally which will show the new data on the page and than update the server.
Is this the right approach ? My functionality is working fine as of now in Dev environment. But i am worried whether i should use DOM. if i will use DOM it will be very complex since i have to manipulate much values of Hashmap based on request.
Here is the jquery code :
$.ajax({
url: '<%=portalContext.createTemplateProcessURI()%>'
+'?s1='+ $("#networkBox1").val()+'&box1=Box1&tick=add&val1='+ allvs+'&s2='+ $("#networkBox2").val()+'&box2=Box2&val2='+ allvs,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {
Processbox(data); // This function displaying the result.
}
});
dude, first of all, I think after you get your data from back end side, your java object has already changed to json object. I think your flow has no problem, because once you change to DOM, then all the data is send through front side but not back end side, if you use session, actually you handle your data at back end side, for me, I prefer the second one.
Here is my idea:
1.set a dom object in your page with the data get from your ajax
$(domId).val(value get from ajax);
2.If your don't want to show the data, use hidden type input in your jsp form
<input type="hidden" id="domId" name="domName">
3.once you click submit button, handle your data in your servlet
String data = request.getParameter("domName");
session.setAttributes("sessionData", data);
Hope this will help you.

HTML from servlet response using ajax is not being executed in JSP page

My problem is kinda weird. I have a JSP page that calls servlet using JQuery/ajax on combobox change. Everything works fine, I get the response but html is displayed as text. Other thing worth mentioning is when I call servlet directly by URL, everything is fine.
Servlet response code:
for(int i=0;i<tabstr.length;i++){
wyjscie.println(i+": "+tabstr[i]+" <br>");
}
JSP ajax call:
$('#com2').change(function() {
$.get('filtr', function(responseText) {
$('#result').text(responseText);
});
});
result is an ID of a DIV inside JSP page. I've done some servlets without ajax in the past and I didn't encounter this problem before. Any idea how to deal with it?
you have to set as html not text try this
$('#result').html(responseText);
I think your server doesn't specify the mime type of the response. So you have to specify it or you can specify dataType in you ajax call.
$.ajax({
url : "myUrl",
dataType : "json",
data : {
param1 : value1,
}
});
ajax api:
dataType: The type of data that you're expecting back from the server. If none
is specified, jQuery will try to infer it based on the MIME type of
the response...

How to respond to a client request from a servlet without reseting the controls in jsp form

I am a building project in which I am using java-beans,jsp and servlets. I need to send the response to the client on the same page from where request was made with a slightly modified html. But when I(server) sent the request to the jsp page, the controls in the form are getting reset to their original value. But I don't want to override the user's input after the request was made. One way to achieve this is to take value of the property for each control in the form when request is made and then set them again while responding. Actually there are a large number of controls in my form, taking values of each doesn't seem efficient.
So is there some other way to keep the form in the jsp file unchanged while responding to the client.
you can use ajax for what you are asking, or you have to save the data on form submit, in session or some place and set them back again while responding. Apart from that I think there is no other way you can retain form data even after page reload.
Thanks
Chakri
Why dont you use iframe ? so you dont have to refresh the whole page when the request is made to the same page.
Instead of making the action of the form to the same page, call a javascript function that set the parameters in the link and then
var f = document.getElementById('iframe');
f.src = 'newlink';
f.contentWindow.location.reload(true);
This populated the iframe with the latest content
function openOffenderInfo(i)
{
$.ajax({
url:'../loginServlet',
type: 'POST',
success: function(data)
{
alert("reset your div values in this block");
.... for example .....
documnet.getElementById('reloading Div').innerHTML=data;
},
error: function(data)
{
alert("error");
}
});
}
URL : c=name of the servlet you want to call
this servlet calculates the data and gives the new data you want to reset in your div
success : this is the function which will be executes if your ajax call is made successfully
so you can set the values of your reloading part inside this function
I hope this might serve you the purpose

problem with passing bean data from servlet to jsp

I have 2 jsp pages, one called as MyPage.jsp and other as View.jsp. View.jsp has a tree structure. MyPage.jsp has some text fields called as number and design which need to be populated through a bean via servlet. On click of any of the tree node in View.jsp, MyPage.jsp should be rendered with the text fields values set. Now what is happening is since MyPage.jsp is being called twice, i.e. once in View.jsp(in ajax function) and second in the request dispatcher in the servlet so the bean values being set in the servlet are lost. Please suggest a better way so as to retain the values throughout and that on click of the tree node MyPagejsp is rendered with the field values set.
responseBean.setNumber("220");
responseBean.setDesign("xyz");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setAttribute("responseBean", responseBean);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/MyPage.jsp");
requestDispatcher.include(request, response);
response.getWriter().write("Success");
The jsp page from where MyPage.jsp is called with the bean values set has following code
View.jsp
$.ajax({
url : AJAX_SERVLET,
type: "GET",
data: "Number="+node.data.title,
success : function(output) {
$("[id=content]").attr("src", '/Test-portlet/MyPage.jsp');
}
});
}
MyPage.jsp
<jsp:useBean id="responseBean" class="com.web.bean.ResponseBean" scope="request">
<jsp:setProperty name="responseBean" property="*"/>
</jsp:useBean>
<body>
<%System.out.println("Values"+responseBean.getNumber()); %>
</body>
In the above MyPage.jsp code, System.out.println is printing the value twice; once as
Values 202
and second as Values null. Since it replaces the original value with null just because MyPage.jsp is called twice and so the second time value is lost. Please help
I believe that you're confusing/misunderstanding some basic concepts, particularly how HTTP works and how Ajax is supposed to work.
What is happening here is that you're effectively firing two HTTP requests. One by $.ajax() and other by element.attr('src', url). Each request results in a fully distinct bean instance being created and set. You're completely ignoring the bean data in the callback of the $.ajax() request. I am not sure what HTML element [id=content] represents, but I guess that it's an <iframe>. That's not entirely the right way.
You should end up with effectively firing one HTTP request. There are basically 2 solutions:
Forget the $.ajax() and send the request by element.attr('src', url).
$("[id=content]").attr("src", "/Test-portlet/MyPage.jsp?number=" + encodeURIComponent(node.data.title));
You can also change the URL to be a servlet one so that you have a bit more preprocessing control and finally use RequestDispatcher#forward() instead of include(). Do NOT write HTML to the response in the servlet. Let JSP do it.
Forget the <iframe> thing and process the response fully by Servlet/Ajax without intervention of JSP. You would need to convert the bean into other data format which is easily parseable by JavaScript/jQuery. I would suggest to use JSON for this.
$.get(AJAX_SERVLET, { "number": node.data.title }, function(response) {
$("#number").text(response.number);
$("#design").text(response.design);
});
with in HTML for example
<div id="number"></div>
<div id="design"></div>
and in servlet
// ... (create ResponseBean the way as you want)
String json = new Gson().toJson(responseBean);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
See also:
How to use Servlets and Ajax?

Categories

Resources