JSP send data to Java class - java

I'm looking to send information after each link click to my java class to help increment a counter and to change an object which is held in my bean (myGame) which holds an array of 'cases'. I understand that I can increment a counter using JS, but i'd like to keep all game logic within the bean if possible.
I have considered using forms and changing the anchor to a submit button, however, I'd like to keep that the player can no longer click the link after it the case is eliminated.
The printCase(int) function works by finding the corresponding case in the array, checking the value of a boolean (is the case is eliminated from the game [deal or no deal]) and then prints the amount of money held in the case if eliminated; the case number if it is not.
I have about a dozen cases.
<jsp:useBean id="myGame" scope="session" class="dealOrNoDeal.GameLogic"/>
<table border="1" id="dndTable">
<form action="/../doStuff.jsp" method="post">
<tr>
<td> <%= myGame.printCase(0) %> </td>
</tr>
</form>
</table>
I've also considered changing my bean to a servlet. Does that work? Can you have a bean in a servlet?
Thanks all.
Update: I've made printCase now print the tag that it's within now, as well. Prints as a submit button if the case is not opened, prints as a <p> if it is (I need it to use the class). Attempted putting the <td>s in there as well, but it somehow messes up the formatting.
I'm now looking to get the name of the one button that was clicked, any ideas?

I'm not sure about understand completely your qestion. But i'll try:
U have 2 ways:
You have to build a jquery where on each button click u call a servlet where u send information to your java class;
Using DWR: http://directwebremoting.org/dwr/index.html

Related

Load two return function with one click JSP and javascript

There is a jsp file calling 2 different js files. I had a button(assume ButtonA) in jsp which when clicked it load a function(Function1) which fill jsp form with values. There is another button in page (ButtonB) which when clicked it load another function where this function(Function2) calculate a figure based on result that Function1 populated in form. So the action was user click ButtonA first, field values loaded, then click ButtonB to get calculated figure. Now I dont want two button clicks here. I tried to put two functions in one button as example below
<td colspan=3><center><INPUT TYPE="Button" VALUE="Query Package Info" TARGET="bottom" onClick="generateReport('MK07FormPackageInfo'); computeMarkFormat(document.MK07Form.markSurf.value);"></td>
but it only correctly run first one but the second one with gives empty values.
Please help.
Why dont you have the Javascript Function1 just call Function2.
If Function 1 and 2 are used by other JSP's:
Function 1 could be overloaded or modified to take in a parameter that says call function2 or not. Other JSP's can still keep calling Function1 as is. This particular button can call Function1 with parameter to trigger
Function 2 call.
function1 (callFunction2) {
function1();
function2();
}
function1 (){
}
function2 () {
}
Is there another reason you need this to be two seperate calls?
Thanks,
Paul
I tried to execute your scenario, it is working actually.
Here is my code
<script language="javascript">
function loadValues(){
document.getElementById('a').value = '2';
document.getElementById('b').value = '2';
}
function calc(){
document.getElementById('c').value = document.getElementById('a').value + document.getElementById('b').value;
}
</script>
HTML
<input type="text" id="a"/>
<input type="text" id="b"/>
<input type="text" id="c"/>
<input type="button" onClick="loadValues(); calc();" />
Only place where it fails is, if your first method executed successfully then only the second function will be executed. If you have any exception or problem in first function, the second one will not work, you may try to give 'b1' instead of 'b' After then nothing will be executed. Correct me if something wrong. Thanks..
Why don't you have a close tag for <center> ?
You may need to debug or add console.log to debug your second function if the result is not what you expected(Since you said it returned empty val, which means it actually got called, right?). Also, try to open console on browser's developer tool and see if any Exception/Error.
Btw, just like other guys says:
onClick="generateReport('MK07FormPackageInfo'); computeMarkFormat(document.MK07Form.markSurf.value);"
Isn't really pretty and is not a recommend way to do this...
You may want to add multiple event Listener to your using jQuery:
<script src="//code.jquery.com/jquery-1.11.2.min.js" />
<!-- watever here -->
<INPUT id="queryPackageInfoBtn" TYPE="Button" VALUE="Query Package Info" TARGET="bottom" />
<!-- watever here -->
<!--
Binding the even
-->
<script>
jQuery('#queryPackageInfoBtn').click(function(){generateReport('MK07FormPackageInfo'); });
jQuery('#queryPackageInfoBtn').click(function(){computeMarkFormat(document.MK07Form.markSurf.value);});
</script>
<!--
actually you can just do:
jQuery('#queryPackageInfoBtn').click(function(){
generateReport('MK07FormPackageInfo');
computeMarkFormat(document.MK07Form.markSurf.value);
});
but I want to make it obvious how you can add multiple event handler to the buttons without using inline onClick which will be messy.
-->

How does the Spring forms .jsp tag library work?

So I have a .jsp page which has a form on it, like this (naturally this is a massive simplification):
<form:form commandName="myCommand" method="post">
<form:select path="values" class="select-tall" multiple="multiple" id="mySelect">
<option>first</option>
<option>second</option>
<option>third</option>
</form:select>
<button type="submit" class="button">Save</button>
</form:form>
When the submit button is pressed, the form is submitted(somehow) and the path= attributes are used to bind the data inside the form elements to the properties of an instance of a plain old java object. I understand how this POJO is specified, and I understand how the POST request is routed to the correct controller, but I don't understand where or how the form values are mapped to the given POJO.
What I don't understand is:
How does the spring tag library modify the form such that this binding takes place?
How would one go about doing this in a manual or ad-hoc fashion(using a Javascript onSubmit() method, say)?
Essentially my question is: How does the spring-form.tld tag library work?
Any resources, or even a high-level explanation in your own words, would be extremely helpful.
I've implemented a work-around solution in the mean time (dynamically adding items to a hidden form element), but I feel like this is hack-y and the wrong solution.

Struts 1: form can read bean value but on submit does not write in it

Hello dear folks of stack overflow.
I encountered a problem recently in my Struts application.
I have a jsp which displays some bean value correctly (i paste only relevant part of the code, i simplified to the extreme):
<table>
<logic:iterate name="bean" property="list1" id="listItem">
<tr>
<td>
<html:checkbox name="listItem" property="selected">
</html:checkbox>
</td>
</logic:iterate>
</table>
My bean has a list1 property with its getter and setter
private List<RandomObject> list1;
public List getList1() {
return list1;
}
public void setList1(List list1) {
this.list1=list1;
}
and my sub-bean has a selected property:
private boolean selected;
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
Now, when enter this jsp, the values i get are correct, ie: if my mapped object in DB was at selected=true, the checkbox is checked. What i dont get is how do i save the changes i make in this form. When i submit, all the changes are lost. This is pure struts related, because in debug when i enter the StrutsAction linked to submit, the ActionForm i get has already lost all interesting values. Also i feel like it has to do with the fact that the value i want to retain isn't directly stored on the main bean, but rather is a property of a sub-bean, because on the same page there are a lot of other properties directly on the main bean that i have no trouble saving.
What did i miss ?
It's probably declaring incorrect name attributes in the rendered HTML. If you look at the generated source code for your page it probably looks like this:
<input type="checkbox" name="selected" ...>
which would look for a selected field in your form bean class.
If you're using a collection that's a field in your form bean you want to be using the <nested:form>, <nested:iterate> and <nested:checkbox Struts tags, not the <html:form>,and` ones. So it would then look like this:
<nested:form action="foo">
...
<nested:iterate property="list1" id="listItem">
<tr>
<td>
<nested:checkbox property="selected">
</nested:checkbox>
</td>
</tr>
</nested:iterate>
...
</nested:form>
Note that I've removed the name attributes from the Struts tags, because they're not needed (in my experience they actually cause all kinds of problems - if you use <nested:*> tags don't use a name attribute). In the case of the <nested:iterate> the level of nesting is the form bean itself, so it knows that it needs to look for the list1 property in the form bean.
That tag creates its own nesting level, so the <nested:checkbox knows that it needs to look for the selected property of the current element in the iteration.
The rendered HTML will look something like this (for the first element):
<input type="checkbox" name="list1[0].selected" ...>
which means the selected field of the first element (index 0) in the collection referenced by the list1 field of your form bean.
And, of course, you'll need to make sure that you're using a session-scoped form bean, rather than a request-scoped one.
in my case i had to put the name attribute into the iterate otherwise it gives me error(cannot find property into any bean...)
I resolved deleting the attribute name into the checkbox: it seems it create a new object at page scope that is not connected with the form.
This is my code:
<nested:iterate id="apertura" type="it.puglia.innova.view.actionform.AperturaForm" indexId="index" name="strutturaRuraleForm" property="listAperturaForm">
<nested:checkbox styleId="checkbox_${index}" property="flagContinuato" onchange="changeOrarioContinuato(${index})"/>
that's it :-) didn't need to change html:form to nested too.
Bye

spring mvc form inputs

I m having a hard time working with array inputs for example how can I:
Write the following html input using spring form tag:
<input name="phone []"/>
<input name="phone[]"/>
I tried
<form:input path="phone []"/>
but no luck throws error saying that class attribute phone [] does not exists.
2 . After you tell me how to do step 1 how can i repopulate the form with user inputs values using #ModelAttribute In case of validation error. Obviously normal using of <spring:input path="phone"/> won't work cause phone has a list of values.
By the way I use controller with annotations.
Thanks
This depends if you are trying to do dynamic forms or just a static list based forms. For static ones - you need to iterate manually:
<c:forEach items="myModel.phones" varStatus="status">
<form:input path="phones[${status.index}]" />
</c:forEach>
Dynamic forms are a little bit complicated and you should try google as this was asked and answered few times.

dijit.form.Select re-appears unpopulated?

This is a continuation of an issue I was having yesterday so if it looks familiar, thats why :) It IS a different question tho!
So I have another dijit.form.Select initially created on the page like so;
<c:set var="clazzId" value="${verification.clazz.id}" />
<div id="clazzOptions">
<select id="clazz" name="clazz" style="width:22em" dojoType="dijit.form.Select" maxHeight="140">
<option value="-1" label=" " />
<c:forEach items="${requestScope.clazzes}" var="clazzItem">
<c:choose>
<c:when test="${clazzId eq clazzItem.id}">
<option value="${clazzItem.id}" selected = "true">${clazzItem.name}</option>
</c:when>
<c:otherwise>
<option value="${clazzItem.id}">${clazzItem.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
</div>
I then have some javascript that I'm trying to use to swap the contents of the div "clazzOptions" depending on the value chosen from a different drop down (not seen here). If its a certain value, replace the div with a text message, if its any other value, re-show the original dijit.form.Select;
<script type="text/javascript">
var classDropDown;
var classPhDMessage = "PhD's do not require a Class or Grade";
dojo.addOnLoad(function() {
classDropDown = dojo.byId('clazzOptions').innerHTML;
});
function checkForPHD() {
var awardOption = dijit.byId('qualification').attr('displayedValue');
if(awardOption == "PhD"){
dojo.byId('clazzOptions').innerHTML = classPhDMessage;
} else {
dojo.byId('clazzOptions').innerHTML = classDropDown;
}
}
</script>
As you can see I'm trying to capture the innerHTMLof the div as it is when the page loads and then depending on the value chosen in the other drop down (not seen) change between a predefine message and the captured div contents.
The issue is that after the original div contents have been replaced with the message and then the selection changes again away from "PhD" and the original div innerHTML is placed back into the div, the dijit.form.Select re-appears but is completely empty and in fact doesn't appear usable at all? If I remove the dijit.form.Select dojoType and just leave it as a normal select this whole operation works perfectly but I kinda need it to be a dijit.form.Select.
Why won't dijit.form.Select work in this case whereas a normal select does?
You shouldn't use innerHTML to add/remove dijits, especially if you're trying to re-use them.
A dijit is a combination of HTML and Javascript and can be thought of as 'more complex' than simply the contents of a specific node.
You have a number of options:
Disable your dijit.form.Select and add a small note under it (or set it's value) explaining why it's disabled (this is generally a better UI paradigm than removing controls). Depending on your UI this is what I'd try and do
Create a <span> as a sibling of your dijit.form.Select and use CSS to show/hide one of them at a time.
Obviously you'll still get the value of the dijit.form.Select when you submit your form, but because you do server side validation as well as client side validation (I hope :) this won't be a problem
Use the dojo.data API to create a datastore from your "${requestScope.clazzes}" iterator. Use this store when you (programatically) create the dijit.form.Select. Keep track of the current value of said Select somewhere. When you don't need it, call yourSelect.destroy() to properly destroy it, then when you need it again create a new one and set it's value to the saved value from before.
This seems unnecessarily expensive to me tho.

Categories