Passing request parameters through Javascript - java

I have a struts application, and I am trying to call the Action class with an URL. When I try to pass the request parameters, none of them get appended.
Here is the code I have :
document.myform.action = "mydetails_${firmID}_${empID}.action?id=56";
document.myform.submit();
But this is what I see in chrome console :
mydetails_123_04.action?
For some resaon, the stuff after the question mark is not appended. Am I missing something ?

Don't think you can set params like that in the action. You need to add them as parameters in the form, which involves creating a hidden input node:
var input = document.createElement( 'input' );
input.type = 'hidden';
input.name = 'id';
input.value = 56;
document.forms.myform.appendChild( input );​

Related

Need to get value after Domain name in url using java

We are getting url from JSON Response and which we open in in Chrome.The page loads , there is submit button which we click then it redirect to url as :-
https://www.google.com/AB1234
We need the need to retrieve only "AB1234" value from url.
tried following code to get value ="AB1234"
String url = driver.getCurrentUrl();
int index=url.lastIndexOf("/");
String result = url.substring(0,index);
but here getting initial part of url:https://www.google.com/
You need to call substring function with index +1 .
Try below code :
String url = driver.getCurrentUrl();
int index = url.lastIndexOf("/");
String result = url.substring(index + 1);
To parse a URI, it's likely a good idea to use a URI parser.
Given http://example.com/bar
String path = URI.create(driver.getCurrentUrl()).getPath();
will get you '/bar'.
Given http://example.com/bar/mumble the same code gets '/bar/mumble'. It's unclear from your question whether this is what you want. Nevertheless, you should at least start the parse as above.

How to send content from Freemarker to java by request?

I'm trying send information from a FreeMarker template to my Java model class.
I've tried this:
//my array of string casted in a string
var pais = selected.join();
request.setAttribute(pais, "paises");
Ok, now I'm trying collect this content in my Java class doing this:
String paises = MgnlContext.getAttribute("paises");
But it doenst work. I tried other methods like this:
Stirng paises = MgnlContext.getInstance().getAttribute("paises");
But it always returns null.
SOLUTION (sending info by ajax):
first get the values by javscript :
[#assign cpathx = ctx.contextPath]
[#assign url = model.getUrl() /]
var field = $('#key').val();
var calin = $('#calendarIni').val();
var calfin = $('#calendarFin').val();
var pais = selected.join();
var url = '${cpathx}${url}?paises='+pais+'&palabra='+field+'&calendarini='+calin+'&calendarfin='+calfin;
jQuery.post(url ,function(data) {
jQuery('#ajax').html(data);
});
Now we can collect the info in java:
String paises = MgnlContext.getWebContext().getAttribute("paises");
String queryString = MgnlContext.getWebContext().getAttribute("palabra");
String dateStart = MgnlContext.getWebContext().getAttribute("calendarini");
String dateEnd = MgnlContext.getWebContext().getAttribute("calendarfin");
That first piece doesn't look like freemarker but more as JavaScript, so maybe that is your problem. While freemarker directives are executed server side, html and Js produced by freemarker is executed client side so w/o Ajax call there's no way for Js to talk back to server (and thus to model class).
If you were really interested in passing something from freemarker to java model, model is exposed directly. You can simply add method in java model and call it from freemarker template like
${model.myMethod(someParam)}
HTH,
Jan

Calling a java method with parameter value set from dropdown select in jsp

My task is to select a value in one dropdown, and with that value as a parameter, invoke a java method.
I tried setting a hidden input when via onChange, a javascript function is called, but could not use that value for passing as a parameter. (I have a bean, that has the method which i need to invoke from jsp after selecting value from dropdown)
You can make Ajax call to the servlet with XMLHttpRequest object in JavaScript.
You can make a successful call to servlet as:
<script>
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
var data = req.responseText;
//HANDLE RESPONSE HERE;
}
}
req.open('GET', 'servletName', true);
req.send(null);
</script>
In servlet, handle the parameter passed from dropdown in request and accordingly, call java method and send response text as:
String responseData = "Output for your selection is : " + XXXX + "!";
response.setContentType("text/plain");
response.getWriter().write(responseData);
Test crossbrowser compatibility before using it.

Strange parsing issue

I'm trying to send some data to a servlet and then to get back a .xls file from it. In order to do this, I'm using jquery, but I'm facing some strange issues. Let me explain.
Here is how I'm sending the data to the servlet and how I'm supposed to get the generated file back:
jQuery.download = function(url, data, method){
//url and data options required
if( url && data ){
//data can be string of parameters or array/object
data = typeof data == 'string' ? data : jQuery.param(data);
//split params into form inputs
var inputs = '';
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
});
//send request
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove();
};
};
download = function () {
var a = this.mainData();
var b = JSON.stringify(a);
console.log(b);
what = "test",
obj = $.extend({WrJOB: "xlsExport", mainData: b}, tJS.getCommonPostData());
var data = $.param(obj); //.replace(/\+/g, '%20'); its just a test
$.download('/myapp/AppProxy', data);
},
A button in my html is calling the download function wich is sending some JSON data to the servlet. In my case it is var b.
I'm pretty sure that there is an encoding issue, but I have no idea how to fix it.
Please, help me with this strange problem, I'm already working many hours on it and I can not find a solution.
You should unescape your output at some point. I would advise to do it on servlet side.
It looks like the servlet is receiving it encoded for a URL. You might be able to decode it on the servlet side if you have control over the code on the servlet.
For instance, in PHP, using urldecode()
Hope this helps.
like this
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}});
jQuery.each(data.split('&'), function(){
var pair = this.split('=');
inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ jQuery.URLDecode(pair[1]) +'" />';
});
The problem is that you urlencode your data twice. First explicitly in your javascript, then implicitly when creating the form. The browser will be "nice" to you and urlencode the input parameters before doing the request.
Either decode the parameters before adding them as input values or change the way you build your data to avoid the explicit encoding.

How to call java method using javascript in ZK MVVM?

I am using Edraw Office Viewer component to open & edit the file. I want to save my file to my destination point so I am using JavaScript to save the file. But I am stuck at a point. I am showing my code below to save document using JavaScript.
function f_saveDocument(){
if(document.OA1.IsOpened)
{
var saveAsFileName = document.getElementById('hdnFileName').value;
alert(saveAsFileName);
var fileFormat = saveAsFileName.substring(saveAsFileName.lastIndexOf("."));
if(fileFormat == '.docx') {
var toUnLockFile = 'MergeTest'+fileFormat;
var tempFileLocation = document.OA1.GetTempFilePath(saveAsFileName);
var tempToUnLockFileLocation = document.OA1.GetTempFilePath(toUnLockFile);
document.OA1.SaveAs(tempFileLocation,12);
document.OA1.SaveAs(tempToUnLockFileLocation,12);
document.OA1.HttpInit();
document.OA1.HttpAddPostFile(tempFileLocation);
document.OA1.HttpPost("");
document.OA1.ClearTempFiles();
} else {
alert("asdsa");
document.OA1.HttpInit();
document.OA1.HttpAddPostOpenedFile(saveAsFileName);
**zAu.send(new zk.Event(zk.Widget.$('$btnSave'), "saveFile", {'' : {'data' : {'nodeId': ''}}}, {toServer:true}));**
alert("moved");
}
}
In case of JSP page I can put my JSP URL in HttpPost but in case of ZK how to move from this JavaScript to Java method. So to overcome this problem I am using Widget to call saveFile() method which is in my viewmodel class. But zAu.send is not working fine. Can any body tell other solution to call my Java method from JavaScript in ZK MVVM.
Your code is simply wrong
zAu.send(new zk.Event(zk.Widget.$('$btnSave'), "onSaveFile", {'' : {'data' : {'nodeId': ''}}}, {toServer:true}));
Event names must start with on so this will fire a onSaveFile
event to the Component with id btnSave. Just listen to it.

Categories