Converting a Java object to a Javascript object using velocity - java

If a have a Java object (lets say a User object), and I use velocity to template the page
so I can access a field in the user object like ${user.id}, is there an easy way to convert this into a javascript object (so I can access the fields of the User object)?
I can assign a value to javascript variable like
var id = "${user.id}";
but if i do
var user = "${user}";
this isn't true:
id == user.id;
And I would rather not have to do
var user = { id: "${user.id}" ...}

Maybe you should transform your user object to a JSON.
You can create a utility method that uses reflection and gets each attribute from an object and put in a String. Maybe you can create an annotation to mark which attributes should be included in the JSON.
This way you send to your template something like this
"{id: '1', name:'stevebot'}"
And in you velocity file
var user = ${user};

Related

which is optimized way of using JSONObject sub elements

I have a nested JSON object and I want to access 3 values from it which is the best-optimized way to call it.
'''
item.put(ITEM_COUNT, order.getJSONObject("name").getString("key1"));
item.put(PRICE, order.getJSONObject("name").getLong("key2"));
item.put(ITEM_NAME,order.getJSONObject("name").getJSONObject("key3").getString("key4"));
'''
or I need to create a JSON object name and the i have to get each value like
JSONObject name = order.getJSONObject("name"); and use this object now

How to retrieve an integer URL parameter with JSP? [duplicate]

In JSP how do I get parameters from the URL?
For example I have a URL www.somesite.com/Transaction_List.jsp?accountID=5
I want to get the 5.
Is there a request.getAttribute( "accountID" ) like there is for sessions or something similar?
About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
The interesting parts are in bold :)
So, to answer your question, you should be able to access it like this (using EL):
${param.accountID}
Or, using JSP Scriptlets (not recommended):
<%
String accountId = request.getParameter("accountID");
%>
In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters - - p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request.
This example demonstrates how to include the value of a request parameter in the generated output:
Hello <b><%= request.getParameter("name") %></b>!
If the page was accessed with the URL:
http://hostname.com/mywebapp/mypage.jsp?name=John+Smith
the resulting output would be:
Hello <b>John Smith</b>!
If name is not specified on the query string, the output would be:
Hello <b>null</b>!
This example uses the value of a query parameter in a scriptlet:
<%
if (request.getParameter("name") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request. getParameter("name")+"</b>!");
}
%>
Use EL (JSP Expression Language):
${param.accountID}
If I may add a comment here...
<c:out value="${param.accountID}"></c:out>
doesn't work for me (it prints a 0).
Instead, this works:
<c:out value="${param['accountID']}"></c:out>
request.getParameter("accountID") is what you're looking for. This is part of the Java Servlet API. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html for more information.
String accountID = request.getParameter("accountID");
www.somesite.com/Transaction_List.jsp?accountID=5
For this URL there is a method call request.getParameter in java , if you want a number here cast into int, similarly for string value cast into string. so for your requirement , just copy past below line in page,
int accountId =(int)request.getParameter("accountID");
you can now call this value useing accountId in whole page.
here accountId is name of parameter you can also get more than one parameters using this, but this not work. It will only work with GET method if you hit POST request then their will be an error.
Hope this is helpful.
example you wanted to delete the subject record with its subject_id
#RequestMapping(value="subject_setup/delete/{subjectid}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int subjectid) {
subjectsDao.delete(subjectid);
return new ModelAndView("redirect:/subject_setup");
}
and the parameter will be used for input on your query
public int delete(int subjectid) {
String sql = "update tbl_subject set isdeleted= '1' where id = "+subjectid+"";
return template.update(sql);
}
page 1 :
Detail
page 2 :
<% String id = request.getParameter("userid");%>
// now you can using id for sql query of hsql detail product

Android - Converting string to list to push to firebase realtime database

Is there any way to convert the string below to a list?
This string is retrieved after scanning a QR code.
CashRequest{
orderid='0',
user_id='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
userName='username',
userEmail='whateveremailthisis#email.blabla',
fullName='full name',
phoneNumber=0,
totalCash='$304.00',
totalRV='$34.00',
foods=[
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='-LMDiT7klgoXU8bQEM-4',
ProductName='Coke',
Quantity='4',
Price='1',
RedemptionPrice='10',
RedemptionValue='1'},
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='1000',
ProductName='Kunau Ring Ring Pradu',
Quantity='3',
Price='100',
RedemptionPrice='10',
RedemptionValue='10'
}
]
}
The desired output is to store it in firebase realtime database as below :
Well you have a few options. Since it is newline between values, you could use simple newline reads and compare if it starts with "reserved word that you are looking for" then substring from there, but that can get messy and a lot of bloat code.
The simplest way would be to do the known replace first.
Make a method that replaces all bad json keys with quote surrounded json keys like:
val myJsonCorrected = yourStringAbove.replace("Order", "\"Order"\")
repeat for all known entities until you have made it into valid json. Single ticks are fine for the values, but the keys need quotes as well.
Then simply create an object that matches the json format.
class CashRequestModel{
#SerializableName("orderid")
var orderID: Int? = null
etc.....
#SerializableName("foods")
var myFoods: ArrayList<OrderModel>? = null
}
class OrderMode {
#SerializableName("userID")
var userID: String? = null
#SerializableName("ProductID")
var userID: String? = null
etc..
}
Then simply convert it to JSON
val cashRequest = getGson().fromJson(cleanedUpJson, classTypeForCashRequest);
and your done. Now just use the list. Of course it would be better if you could get valid JSON without having to clean it up first, but it looks like the keys are known and you can easily code string replaces to fix the bad json before casting it to object that matches the structure.
Hope that helps.

repeat control, have a dynamic column

I have made a utility custom control to have a quick, generic view. the custom control has as properties a property names collection which is of type object and received an arraylist of java objects (e.g. a Customer object).
Then on the cc a repeat control is using this:
<xp:repeat id="rptObjects" var="obj" indexVar="idx" value="#{javascript:compositeData.collection}" >
I would like to make the columns more dynamic. So I defined a new property called linkName, also of type object.
The in my repeat control I have setup a div with a xp:link control:
<xp:link escape="true" text="#{javascript:compositeData.linkName}">
However I am struggling on the page that contains this cc to compute the value for the linkName property.
If for example I would like to use the name field on a Customer java object how should I compute the valeu for the linkName property?
on my cc I set the text for the link:
<xp:link escape="true">
<xp:this.value><![CDATA[#{javascript:return compositeData.pageLink + "?unid=" + obj.unid}]]></xp:this.value>
<xp:this.text><![CDATA[#{javascript:var lbl = compositeData.linkName;
obj[lbl]}]]></xp:this.text>
</xp:link>
on my xpage i could set:
<xc:ccUtilsGenericView pageLink="customer.xsp"
header="Customers" icon="fa fa-user" linkName="custName">

DCM4CHE retrieve value based on tag in a sequence

Using DCM4CHE to retrieve values based on the tag name in plain xml is pretty straightforward.
For example if I want to retrieve the value of the attribute AccessionNumber:
String accessiongNumber = attribute.getString(Tag.AccessionNumber);
But what is the best approach when dealing with Sequence? I want to retrieve a value using its Tag name, but the value is 5 layers deep inside a Sequence.
In this case, I can get to the Sequence I want with:
Sequence recordSequence = attribute.getSequence(Tag.RecordSequence);
Is there a way to retrieve a value by its tag directly once I have the sequence that the value is embedded in?
Try using the Attributes.getNestedDataset methods. These will get you the attributes in the sequence. Something like:
Attributes refStudy = attribute.getNestedDataset(Tag.ReferencedStudySeequence, 0);
String refSopiuid = refStudy.getString(Tag.ReferencedSOPInstanceUID);

Categories

Resources