how to share constants between Java and Javascript - java

I have in my java classes static variables CONSTANT_1, CONSTANT_2...
What is the best way to share these constants with my javascript functions or if there is a JQuery plugin for this.
Till now the only solution I can think of, is an ajax call in the beginning, to send these static variables to the client.
Thanks

I dont know whether this the best way or not, but it works.
var constant1=<%=class.CONSTANT_1%>;

you can set this static variable in a hidden field, then you can access it by javascript using this hidden field
<input type="hidden" value="<your static variable>" id="staticVariable" />
<script type="text/javascript">
function getStaticField(){
return document.getElementById("staticVariable").value;
}
</script>

I have faced this problem before. what i did is simply i declared hidden input field that i can access on the server side and set it's value with whatever i want.
<input type="hidden" runat="server" id="hiddenInput" />
then using the programming language(I use c#):
hiddenInput.Value = ValueOnServerSide;
Then using jQuery i get the value of this input on the client side.
$("[id$='hiddenInput']").val();

There is Technology called 'DWR' (directwebremoting).
By using this we can access Java classes directly in Javascript.
Try this, it may helpful to you.
Refference Links:
http://directwebremoting.org/dwr/introduction/getting-started.html
http://directwebremoting.org/dwr/introduction/scripting-dwr.html

You can use AJAX calls to get the value of the constants if you dont want to keep reloading the page.
If you are fine with the value only updating on refresh you can do what Sainath has told, this way you are not making unnecessary AJAX calls:
var constant1=<%=class.CONSTANT_1%>;

Related

Javascript code to read java variable value

I have a session variable in java file.(TestConnection.java)
session.setAttribute("CONNECTION_DBNAME", dbName);
How to read CONNECTION_DBNAME value into javascript file.(utility.js)
First access the variable in scriptlet.
<%
String param= (String)session.getAttribute("CONNECTION_DBNAME");
%>
Then use like this.
<script>
var X = '<%=param%>';
</script>
then you can access the name using x.
<script>
<%
String dbname=(String)session.getAttribute("CONNECTION_DBNAME");
%>
</script>
this code is usefull to you..
You can use hidden element in JSP to get the value from session like:-
<textarea id="txtData" style.display='none'><%=session.getAttribute("CONNECTION_DBNAME") %></textarea>
afterwards you can get the value in your javascript by var dbConnName=document.getElementById("txtData").value;
and you are done.
Scriptlets were OUTLAWED more than a decade ago!
A better way...
in jsp, include the values in a hidden div:
<div id="javaValues" style="display: none;">
<div id="employee">${employee}</div>
<div id="dept">${dept}</div>
</div>
Use <div>'s rather than <input type="hidden">, since they will not interfere with your form-postings.
In javascript (assuming jQuery) you can then access the values, for example:
var employee = $("#employee").html().trim();
var dept = $("#dept").html().trim();
You cannot access variables in the session from the client. You could provide an Ajax call for the client to dynamically retrieve the value, or leave the value set in a script block.
JSF:
<script>var dbName = "#{myBean.value}";</script>
(Literally from session, the key is the quotes need to be there if it's a string):
<script>var dbName = "#{session.getAttribute('CONNECTION_DBNAME')}";</script>
However, you should reconsider before going in this direction because it makes little sense to give JavaScript access to your database through such a mechanism. Unless your database is publicly exposed, then you appear to be down the path of exposing your database connection details, which the client should not need or have. Your server/page should serve as a relay to get this information.
Now, if this is an admin console, then you probably still don't want it in JavaScript, but displaying the settings is acceptable. Regardless, you probably don't need them in the Session unless the connection details are user specific.

Websphere Commerce-TypedProperty

Can anyone help me to understand the usage of TypedProperty in websphere commerce?
ie,How to pass values from one jsp to other using TypedProperty without a command class.I would prefer to handle it in my client side itself without invoking Command class..can anyone help me to sort out it?
Typed property is usually used to pass values from controller commands to JSPs. If you just want to pass values from one JSP to another, create a form in your first JSP and submit it to the second.
If this is a form submit, set the values you need to pass in element. In the results jsp you can get those values using ${WCParam.xxx} .
FYI - To list out all the values in WCParam object try to print the below in JSP :
${WCParamValues}
We use typedProperty when we need to send anything from the command. For example, you give an order ID from the first JSP and want to get the final amount to be passed the result JSP. Here in the command we use the orderID from the request object -> Then we use the OrderAccessBean to get the OrderTotal -> then we set this to a TypedProperty object -> we then set this TypedProperty object to request properties using setRequestProperties() OOB method in a controller command.
Hope this makes it clear !
TypedProperty is a class in Java which can be compared to Hashmap in Java for better understanding. It is a name value pair combination.
I just wanted to understand the problem before answering further.
Why do you want to use TypedProperty in Jsp to pass the value from one jsp to another?
Are you importing the second jsp or including the second jsp to which you have to pass the values to?
If you are importing, you can use c:param tag to pass the values to the second jsp.
For included jsps, the values are already available in the second JSP.
Please include code snippets to explain your problem so that it can be answered clearly.
You can pass parameters from one jsp to another by using the following code snippet:
<c:import url="child.jsp">
<c:param name="name1" value="value1" />
<c:param name="name2" value="value2" />
<c:param name="name3" value="value3" />
</c:import>
Within the child.jsp you can read the parameters by using:
<c:out value="${param.name1}" />
<c:out value="${param.name2}" />
<c:out value="${param.name3}" />
A TypedProperty is nothing but a Wrapper to HashMap. So that's nothing to do here with passing values from one JSP to another JSP. Without invoking a command, you can't pass a Java object to another JSP.
And that is the very basic of Command Framework. I would prefer to go with the first answer.

JSF 2.0 AJAX: Call a bean method from javascript with jsf.ajax.request (or some other way)

Some background: I am building a custom JSF component. The component is basically a text editor and it should have a "Save" -button for saving the content string of the editor. As I am using the CodeMirror library, I need to fetch the content (string) from the editor with javascript and send that to the server. Therefore, in this case I cannot use XML-based JS invocation such as f:ajax.
The question: I was planning to send the string with jsf.ajax.request, but it doesn't directly support calling methods on beans. How can I invoke a method in a bean with JSF in AJAX manner?
There at least two ways to get around this:
Include a hidden form to page with hidden inputfield. Update that inputfield from javascript and then call jsf.ajax.request to post that form. Custom actions can be invoced in the property's getter or setter if needed.
Do the request with raw XMLHttpRequest (or maybe with help from some other JS library). Create a servlet and call that.
Both ways are clumsy and the latter also breaks out of JSF scope.
Am I missing something? How do you do these?
There is a quite similar question, but the answers given only refer to XML-based AJAX invocations. There is also another similar question, but that refers to XML-based AJAX calls as well.
I couldn't find out how to call beans direcly with javascript, but here is a hack around calling f:ajax-declaration from javascript:
1) Create a hidden form with fields for all the data that you want to send to the server. Include a h:commandButton as well:
<h:form id="hiddenForm" style="display: none;">
<h:inputHidden id="someData" value="#{someBean.someData}" />
<h:commandButton id="invisibleClickTarget">
<f:ajax execute="#form" listener="#{someBean.myCoolActionOnServer()}" />
</h:commandButton>
</h:form>
As usual, listener attribute, #{someBean.myCoolActionOnServer()} in this case, refers to the method that you want to execute on the server.
2) In some other button use onclick to call for your special javascript AND click the trigger-button via javascript:
<h:commandButton value="Click me" onclick="populateTheForm('hiddenForm'); document.getElementById('hiddenForm:invisibleClickTarget').click(); return false;" />
populateTheForm() should actually fill the data into hiddenForm's fields.
This is a simplification of my case but should work. Still looking for more conventient approach, though.
I did this task several times. Yo don't need multiply hidden fiels. You can use only one hidden field, convert all input values to JSON object via JSON.stringify and set into this field. On the server side - deserialize JSON object (there are many Java libs for that) to an Java class. That's all.

Two pass JSP page rendering

Suppose an example. I have following interface:
public interface DataSource<T> {
Future<T> fetch();
}
This datasource can do asynchronous data fetching. And we have following tag for using datasource in JSP:
<html>
<d:fetch from="${orderDS}" var="orders">
<c:foreach in="${orders}" var="order">
<div class="order">
<c:out value="${order.title}" />
</div>
</c:foreach>
</d:fetch>
</html>
So, what I want? I want JSP rendering engine to call my custom tag (FetchTag in this example) twice. On first call FetchTag will do DataSource.fetch() call and save Future locally as a object field. On second call FetchTag do Future.get() call and will be blocked until data becomes available.
Is there any way to do such a thing?
I think a better design would not try to alter JSP rendering. Put all that database code on the server side, where it belongs, and use an AJAX call to get that data from a server-side component.
In general, I've found that embedding stuff in custom tag libraries is a bad idea. JSTL and/or Spring tag libraries are all that I need. If I feel like my UI needs to do more, I'm thinking about it incorrectly.
For JS disabled clients, I'd just make them do the round trip for the data and not try to do it in the background. Give them a choice: wait or turn on JS.

Use AJAX instead of TagLib?

I was thinking about the idea of using Ajax instead of TagLib. The most elegant way would be: Using Java Annotation.
The idea is, designers or anybody can make the HTML without any taglib ,just using the "standard" HTML tags with id or name, and call the Javascript. That way any WYSIWYG can be used, developer don't have to care about HTML format or the way it's designed.
In many (at least open-source) WYSIWYG don't show the taglibs in that final result (or have a template of it), so it's hard to "preview". Other reason is, developer should know Java and HTML/TagLibs should not be a must-have, since we got CSS and AJAX.
It should work just like that:
MyClass.java:
import ...
// Use the ResourceBundle resource[.{Locale}].properties
#Jay2JI18n(resourceBundle="org.format.resource",name="MyClassForm")
public class MyClass {
private Integer age;
private String name
private Date dob;
private salary;
#Jay2JLabel(resource="label.name")
#Jay2JMaxLength(value=50,required=true,)
#Jay2JException(resource="exception.message")
public String getName() {
...
}
public void setName(String name) {
if ( name.trim().equal("") ) {
throw new Exception("Name is required");
}
}
/* Getter and setter for age */
...
#Jay2JLabel(message="Salary")
#Jay2JFormat(format="##,###.00",language="en")
#Jay2JFormat(format="##.###,00",language="pt_BR")
// or you could use that to access a property of the ResourceBundle
//#Jay2I18nResource(resource="money.format")
public Date getSalary() {
...
}
/* Setter for salary and getter/setter for the rest */
...
}
Page.html:
<html>
<head>
<SCRIPT>
</SCRIPT>
</head>
<body>
<form onload="Jay2J.formalize(this)">
</form>
</body>
</html>
of it can be a HTML with the fields filled;
PageWithFields.html:
<html>
<head>
<SCRIPT>
</SCRIPT>
</head>
<body>
<form action="myfavoritewaytopostthis" onsubmit="return Jay2J.validate(this)" onload="Jay2J.formalizeExistField(this)">
<label>Name</label><input type="text" name="name" id="name" />
<label>DOB</label><input type="text" name="dateOfBirth" id="dob" />
<label>Salary</label><input type="text" name="salary" id="salary" />
<input type="submit" />
</form>
</body>
</html>
That way the Annotation (no XML, it's like HTML in the way that it's only another file modify and XML is not Java) will define how the HTML will be treated. That way developer can stop developing in HTML and use just JAVA (or JavaScript), do you think that's a valid idea?
When i see your topic title i thought:
You cant use Ajax in stead of a taglib. AJAX is javascript on the client and the taglib is java code on the server.
After reading your post i thought, ah he whats to do what [link text][1] does
But then not entrily the same.
[1]: http://code.google.com/webtoolkit/ GWT
First impression is ... yuck, someone who picks this up will have no idea what they're looking at without learning your (new, different, non-standard) way of doing things. You could do something similar by implementing a tag that takes a bean (value object) and maybe does some minor reflection/annotation inspection to emit the proper html, and you'll save yourself a lot of heartache down the line.
Make your value objects implement a simple interface that your tag will use to extract and format the html, and you can probably get 80-90% of where you're trying to go with 1/2 the work or less.
First impression was, WTF. After reading further, I get a impression that you are trying to address the 'separation of concerns'problem in a different way. Some observations on your approach.
Requires client side scripting to be enabled and hence fails accessibility guide lines.
Reinventing the wheel: Many web frameworks like Tapestry, Wicket try to address these issues and have done a commendable work.
On your comment on binding Java to HTML, the code example doesn't convey the idea very clearly. formalize() seems to create the UI, that implies you have UI (HTML) coded into java (Bad Idea? probably not NakedObjects attempts to you domain models for UI, probably yes if one were to write a page specific code)
validate() is invoked on onSubmit(), Why would I want it to be processed asynchronously!! That aside, using obstrusive java script is way out of fashion (seperation of concerns again)
Your argument on taglibs preventing WYSIWIG, though justifiable, is not entirely valid. Tags cannot be used to compose other tags, each tag is a unique entity that either deals with behaviour or emits some html code. Your argument is valid for the second case. However, if I understand your formalize() correctly, you are doing the same!
Nice to hear some new ideas and Welcome to SO. Also, please use the edit question option until you earn enough reputation to add comments. Adding answers is not the right way!
This idea has some merit, if I understand it correctly.
You could use AOP to modify a servlet that would actually be called for the page. The servlet would then return the html, using the annotations.
This way the programmers don't see the html generation, and if you have a standard javascript library for it, then it may work.
But, just because it works doesn't mean that you should do it.
As was mentioned, there are many frameworks out there that can hide the javascript from programmers, such as JSF, which is basically taglibs and a different navigation scheme.
I remember using the beehive project to do something similar, it was annotation driven so I could basically do everything in java and it generated the javascript, years ago. :)

Categories