I want to include javascript list string in template at quarkus app.
I define ConfigProperty like this.
#ConfigProperty(name = "my_list_string")
lateinit var myListStrings: List<String>
And I use this at template like this.
<script type="text/javascript">
var myListString = {myListStrings};
myJSFunc(myListString);
</script>
When I set my_list_string=test, output is below.
<script type="text/javascript">
var myListString = [test];
myJSFunc(myListString);
</script>
The myJSFunc needs list string, so I want to get ['test']
Also, I set my_list_string="'test'", the output is below.
<script type="text/javascript">
var myListString = ['test'];
myJSFunc(myListString);
</script>
If anyone know how to set JavaScript list string at quarkus app, please tell me about it.
Thank you.
Environment
Java 11
Quarkus 1.5.2
The #ConfigProperty happens on the server side (in Java).
You'll need to expose a REST method to get it the value of that property on the client side (in JavaScript).
Something like
#ConfigProperty(name = "my_list_string")
lateinit var myListStrings: List<String>
#Path("/my_list_string")
String getMyListString() {
return my_list_string;
}
And then retrieve that in your .js file, probably in the document is loaded event.
Related
I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.
#RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
public String getRcaResult(Model model, String flight_id) {
...
JSONObject all = new JSONObject ();
...
model.addAttribute("all",all);
return "dfi/rca";
}
I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:
<script type="text/javascript">
var all= "${all}";
</script>
But if I try the same importing a Javascript file in the JSP, it doesn't get anything:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>
In all.js:
var rcaresults = JSON.parse('${all}');
Are there any way to read the Spring model attributes in a Javascript file?
Thanks in advance.
JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.
If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.
e.g <script>var paramOne =<c:out value="${all}"/></script>
when you use src, your browser (and not your backend) will try to fetch the javascript file from
"${pageContext.request.contextPath}/resources/js/all.js"
so the file is not processed by the server as a ModelView.
On my JSP project I've got a .jsp file which contains the following script:
<script type="text/javascript">
$(window).load(function() {
...
options.items = items;
...
});
</script>
The variable items is included in another JavaScript script that is also included in the same .jsp file:
<script type="text/javascript" src="<c:url value="/js/items.js"/>"></script>
items.js has the following structure:
var items = [{...}, {...}, {...}];
Now, the Servlet that implements doGet for this .jsp gathers some data from a database (and this data can be different every time) and uses it to write in the disk the file items.js mentioned above.
The problem is that the server (tomcat7) doesn't see that items.js has changed until it is restarted, but I need to generate that file every time because the data to gather is not always the same. So I'd like to know how to properly provide the first JavaScript function I mentioned with the data on items without having to restart the server. Of course, I want to avoid using scriptlets if possible.
Please note that I can't just delete that piece of JavaScript included in the beginning of this message because that piece of code is using a JavaScript library which I need to use to visualize my data.
Thanks in advance for your help.
Adding a bit modification to your own solution, if you want to avoid scriptlet you can write your above line like this:
instead of
options.items = <%= request.getAttribute("items") %>;
write
options.items = ${requestScope.items}; or options.items = ${items};
I'm replying to my own question to explain how I solved this problem.
I didn't do exactly what Sacho and Christopher Schultz suggested but what they said gave me an idea.
Firstly, on my servlet, I built a StringBuffer containing the data I want. Initially I wanted to use a JSONArray but that would mean using several transformations so that my js script could read (it'd be doable but it wouldn't simply consist of using the standard parser but something a little bit more complex). Then, I added this StringBuffer to the request parameter. This is how it all looks like:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
StringBuffer sb = new StringBuffer();
// Fill the StringBuffer
request.setAttribute("items", sb);
request.getRequestDispatcher("/WEB-INF/myjsp.jsp").forward(
request, response);
}
Finally, I accessed this attribute from my jsp file as it follows:
options.items = <%= request.getAttribute("items") %>;
I wanted to avoid scriptlets but I think this piece of code is okay plus it's quite simple to implement.
Thanks for your help!
Can I assign a javascript variable to a grails object like this?
var newReport = ${report};
report is a grails domain object, which is passed back from controller to the gsp file.
Currently this doesn't work in my page.
Assuming that report is a Grails domain class, you will have to 'translate' this to a valid javascript format. One way is to set this as JSON. Something like:
In the controller
def reportJson = report as JSON
In the gsp
<script type='text/javascript'>
var newReport = $.parseJSON("${reportJson}");
</script>
The parseJSON takes the json string and return a javascript object.
Just render domain object as JSON to gsp, where some javascript code get the json by eval() function. For instance:
domain class - Band:
String bandName //some property
...
controller:
def bands = Band.list()
render(template:"result", model:[bands:bands as JSON]
_result.gsp:
<script>
var bandList = eval(${bands});
for(i=0; i<bandList.length; i++){
var name = bandList[i].bandName;
....
}
....
</script>
I need to generate a JSON object from server containing data to be cached on client. I placed the following:
<script src='Path to js file on server" />
At the server, I generated my json data and placed them inside the JS file.
I can see the generated JSON object on the client-side something as:
var jsonData = [{}, {}];
However, when I try to access jsonData object, it says, undefined!
Is there another way to generate valid javascript from server side?
Thanks
This is the server-side code:
var items = List<myObj>();
string json = JsonConvert.SerializeObject(items, Formatting.Indented);
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendFormat(" var jsonData = {0};", json);
var fileName = Request.PhysicalApplicationPath + "Scripts/Data.js";
System.IO.File.WriteAllText(fileName, sb.ToString());
As for client side:
<script src='#Url.Content("~/Scripts/Data.js")' type="text/javascript"></script>
I tried to use this code on the client:
alert(jsonData[0].Id);
It says, jsonData is undefined!
Regards
ASP part is ok, the problem seemed to lie in javascript variable scoping plane. Possible problems:
You just don't include that js file.
You're trying to access variable before it is initialized;
Variable isn't visible in place, you're trying to access it.
You're not exact in your question and accessing not jsonData, but something like jsonData[0].property
etc.
UPD: Ok, first two options are excluded. Where are you trying to access this variable? Please, show us a portion of code.
Hi I am trying to fetch portlet session in my JS variable. How could I go about it
request.getPortletSession().getAttribute("countryList"); //This is my .java class code
I need to fetch the same in JS?
you can't access to java session via javascript.
One solution is to serialize you java object into json string and save it into session(if object is null, just save a string that equals to "null")
getPortletSession().setAttribute("countryListJson", JSONUtil.toJSON(yourObject));
then you can use
<script type="text/javascript">
var obj = <%=request.getPortletSession().getAttribute("countryListJson")%>;
</script>
Another solution is to provide a json padding controller method for ajax call. and return a string like this :
return "var countryList = " + JsonUtil.toJson(request.getPortletSession().getAttribute("countryList")) +";"
then you should mapping this method to a url such as "/contryList.do"
and in your page:
<script type="text/javascript" src="<%=request.getContextPath()%>/contryList.do"></script>
<script type="text/javascript">
alert(contryList);
</script>
As i understand, you need to place in some JS var the countryList (from controller). You don't need to get portlet session in JS, you should be able to do like follows:
I managed to get some strings from controller to js using scriptlets and usebean. Try something like this:
Let's say i need to alert an error from backend and i have put it in a java string named "error"(in controller).
I'm able to do this(doView):
String error = request.getAttribute("error"); // or it can be simply String error = "sometext"
if ((error != null) || (!error.equals(""))){
request.setAttribute("error", error);
}
else request.setAttribute("error","false");
Then, in your jsp, at the top i'll place an usebean tag like:
<jsp:useBean id="error" class="java.lang.String" scope="request"></jsp:useBean>
Then, between script tags:
var error = "<%=error%>";
if (error != "false") alert(error);
As i noticed, you need to set the var in controller (with setAttribute) using an if / else statement.