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
Related
I have a string that i'd like to stringify in Kotlin (Android), but it seems that org.json.* doesn't support taking a string and re-stringifying it, instead it always tries to parse it first.
val str = "test=\"123\""
val stringified = JSONObject(str).toString() // JSONException: Value a of type java.lang.String cannot be converted to `JSONObject`
The use case for this ability is passing data to JS inside a Webview in a secure manner.
val json = "test=\"123\""
webview.evaluateJavascript("window.onData(${json})")
// on the JS side it will look like this: window.onData(test="123")
// this is both invalid and insecure since it opens the door for raw JS injection
Any attempt to do it manually will result in an insecure and possibly invalid JS string
This example should NOT be used:
val insecureJSON = "'${str.replace("\\", "\\\\").replace("\"", "\\\"").replace("'", "\'")}'"
The desired behavior:
val json = jsonStringifyString("test=\"123\"")
webview.evaluateJavascript("window.onData(${json})")
// rendered JS: window.onData("test=\"123\"")
Is there an easy method for stringifying a string in Android?
Ended up using the JSONArray class and removing the array wrapping to trick the class to stringify a plain string
fun jsonStringifyString(str: String): String {
val jsonStr = JSONArray().put(str).toString()
return jsonStr.substring(1, jsonStr.length - 1) // remove first and last char
}
val serializedData = jsonStringifyString("test=\"123\"");
webview.evaluateJavascript("window.onData(${serializedData})")
// rendered JS: window.onData("test=\"123\"")
The following code produces a string that has question marks as the display name when I insert an Iranian address(?????, ???????). However if I put the same url into my browser, it returns Tehran, Iran instead of question marks. I know that it has something to do with encoding but how do I get the English text as the browser returns in my java application?
String rawAddress = "Tehran";
String address = URLEncoder.encode(rawAddress, "utf-8");
String geocodeURL = "http://nominatim.openstreetmap.org/search?format=json&limit=1&polygon=0&addressdetails=0&email=myemail#gmail.com&languagecodes=en&q=";
String formattedUrl = geocodeURL + address;
URL theGeocodeUrl = new URL(formattedUrl);
System.out.println("HERE " +theGeocodeUrl.toString());
InputStream is = theGeocodeUrl.openStream();
final ObjectMapper mapper = new ObjectMapper();
final List<Object> dealData = mapper.readValue(is, List.class);
System.out.println(dealData.get(0).toString());
I tried the following code but it produced this: تهران, �ايران‎ for the display name which should be Tehran, Iran.
System.out.println(new String(dealData.get(0).toString().getBytes("UTF-8")));
Use "accept-language" in the URL parameter for Nominatim to specify the preferred language of Nominatim's results, overriding whatever default the HTTP header may set. From the documentation:
accept-language= <browser language string>
Preferred language order for showing search results, overrides the
value specified in the "Accept-Language" HTTP header. Either uses
standard rfc2616 accept-language string or a simple comma separated
list of language codes.
I am trying to pass an array collection from flex page to my backend java.Here is the code,
private function getItems():void{
myObj = new Object();
myObj['dId']= dId.value.toString();
myObj['itmList']=JSON.encode(itmList);// trying to pass like this..
var url:String = URLManager.baseURL;
url = url+"myController/ReportController?do=getItems";
url = url+"¶meter="+ escape(JSON.encode(myObj))
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest,"_blank");
}
My itmList is an array collection, how can I pass it from JSon to Java controller? And how to get that in Java?
JSON.encode the itmList source array instead. (i.e. itmList.source is an array)
Then use HTTPService instead:
HTTPService AsyncToken and AsyncResponder example
Another option is to use JSON.stringify instead (Flash has had native JSON support since FP 11). Just make sure you remove the import com.adobe.serialization.json.JSON; from the top of your file.
myObj['itmList']=JSON.stringify(itmList);
Or, since you're encoding your whole data object,
myObj['itmList']=itmList.source;
var url:String = URLManager.baseURL;
url = url+"myController/ReportController?do=getItems";
url = url+"¶meter="+ escape(JSON.stringify(myObj))
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest,"_blank");
I am trying to query Solr using certain fields and I want the response in XML format. Somehow I am not able to get the response in XML format even though I have set the parser to XMLResponseParser. Please check the code and let me know what is wrong in here:
HttpSolrServer solr = new HttpSolrServer(urlString);
String queryString ="*:*";
SolrQuery query = new SolrQuery(queryString);
query.setQuery(queryString);
query.setFields("type", "typestring");
query.addFilterQuery("id");
query.setStart(0);
query.setRows(100);
solr.setParser(new XMLResponseParser());
QueryResponse resp = solr.query(query);
SolrDocumentList results = resp.getResults();
for (int i = 0; i < results.size(); ++i) {
// I need this results in xml format
System.out.println(results.get(i));
}
Your code is using SolrJ as a Solr client. It's precisely done to avoid dealing with XML responses, and it provides a clean way to get Solr results back in your code as objects.
If you want to get the raw xml response, just pick up any java HTTP Client, build the request and send it to Solr. You'll get a nice XML String...
NOTE : You can use ClientUtils.toQueryString(SolrParams params, boolean xml) to build the query part of your URL
As Grooveek already wrote, SolrJ is intended to take XML parsing away from you as a user of the library. If you want to see the XML, you need to fetch the response on your own.
SolrQuery query = new SolrQuery("*:*");
// set indent == true, so that the xml output is formatted
query.set("indent", true);
// use org.apache.solr.client.solrj.util.ClientUtils
// to make a URL compatible query string of your SolrQuery
String urlQueryString = ClientUtils.toQueryString(query, false);
String solrURL = "http://localhost:8080/solr/shard-1/select";
URL url = new URL(solrURL + urlQueryString);
// use org.apache.commons.io.IOUtils to do the http handling for you
String xmlResponse = IOUtils.toString(url);
// have a look
System.out.println(xmlResponse);
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 );