jsp <html:file> property - java

I need to pass the value from jsp file property in a loop. Here is the code
</tr>
<%
for (int i = 0; i < value.size(); i++) {
<html:form action="save" method="post" styleId="update" enctype="multipart/form-data">
<input type=hidden id="secfeaturetype" name="secfeaturetype" value="" />
<html:file property="testfile" styleId="testfile"/>
<input type="button" value="Update" onclick='javascript:check_updatefields()' />
</html:form>
</td>
</tr>
I am trying to do some validation in javascript and it is reading only the first file properly and not the rest. Any ideas ?
function check_updatefields() {
var file = jQuery('#testfile').val();
alert(testfile);
}
Am I missing something here ? Thanks.

"id", it means it's unique in your page, so if there's more than one, the browser will only identify the first element, so here you'd better use "class", correcting it like this: styleClass="testfile". js: jQuery('.testfile').

As I mentioned in a comment above, the id attribute is supposed to be unique, so creating elements in a loop with the same id is giving you invalid html and $("#testfile") will select only the first element with that id (except in some browsers that might select only the last).
A better solution for repeated elements is to give them a common class and distinguish between them according to which container they belong to, or by a known relationship to some other element if not the container. Or select by tagname if that is unique enough with the containing element, or by the name attribute. You seem to be using jQuery, and it makes any of these options easy.
I think you can tidy your code up to something like this:
<table id="yourTableIdHere">
<% for (int i = 0; i < value.size(); i++) { %>
<tr><td>
<html:form action="save" method="post" styleId="update" enctype="multipart/form-data">
<input type=hidden name="secfeaturetype" value="" />
<html:file property="testfile" styleClass="testfile"/>
<input type="button" value="Update" />
</html:form>
</td></tr>
<% }%>
</table>
I'm not really familiar with the Struts html tag library, but I believe styleClass="testfile" will render an attribute class="testfile" (if not please substitute whatever the appropriate thing is to render class=...). Notice I removed your inline onclick=... attribute. You can assign these handlers in one step with jQuery:
$(document).ready(function() {
// assign a click handler to all the Update buttons that are
// within forms within your table element:
$('#yourTableIdHere form input[type="button"][value="Update"]').click(function() {
var $myForm = $(this).parent(); // or $(this).closest('form'),
$myFileInput = $myForm.find('input.testfile'),
$myHiddenInput = $myForm.find('input[type="hidden"]');
alert($myFileInput.val()); // alert value of file input
$myHiddenInput.val("something"); // set value of hidden
});
});
Within the click handler, this is the clicked button, so from $(this) you can navigate to the parent element to get a reference to the form that particular button belongs to, and from that form you can use .find() to select the file and hidden inputs in the current form.

Related

Get value of <td> in Java - request.getParameter

Im trying to get the values of some td elements where the data consist of data from MySQL table. It displays the data fine in my browser (e.g. if i change type from "hidden" to "submit"), but when I try to get the value i only get null.
Here are my jsp and it displays the correct results in the browser.
<td>
<form action="history.jsp" method="get">
<input type="hidden" name="res" value="<%=his.getRes()%>"/>
</form>
</td>
When i try to print the values however, I only get "null" at of evey :
<%
String res = request.getParameter("res");
System.out.print(res);
%>
I'm still very new, so it's proberly a straight forward answer. Thank you in advance for the help.
I suggest that you change the name of your variable :
String newname = request.getParameter("res");
System.out.println(newname)
One can submit (=send) only one <form>. So one must assume there is just one single td with one <form>. Forms also may not be nested in an outer form.
It need some way to submit the form.
So experiment first with:
<td>
<form action="history.jsp" method="get">
<input type="text" name="res" value="<%=his.getRes()%>"/>
<input type="submit" value="Send"/>
</form>
</td>
This will show whether his.getRes() yielded something. And allows a manual submit in the browser.

Displaying ${} of record from jsp to jsp

<c:forEach var = "student" items="${result}">
<tr>
<th>${student.name}</th>
<th>Notify</th>
</tr>
</c:forEach>
This is my output.jsp. Notice that I've put a link "Notify" to forward it on display.jsp. But I'm not sure how to display a record of student.name onto my display.jsp 's textbox. Thanks
You have to pass the student name over to the display.jsp (e.g. using a GET parameter).
Modify your link as follows:
<th>Notify</th>
Inside your display.jsp your textbox may look like this:
<input type="text" name="studentName" value="${param['studentName']}" />

Pass data from one jsp to another and display that jsp view

Hey i am a php developer and this is my first go with jsp. Now i retrieved a Json string from my class and converted it into GSON. I display a field in my result.jsp for eg:- ID and on clicking the id it should go to details.jsp and show more info about that ID
Currently my result.jsp is as follows:-
<html>
<body>
<div class="list-group">
<%
String json = (String)request.getAttribute("jsonstring");
Gson gson = new Gson();
ConCom diff = new ConCom();
diff = gson.fromJson(json, ConCom.class);
List<ComparisonResultDTOarr> ls = diff.getComparisonResultDTOarr();
for(int i = 0;i<ls.size();i++)
{
List<AuditItemLogsDTOArr> lsinner = ls.get(i).getAuditItemLogsDTOArr();
%><a href="#" class="list-group-item">
<%out.println(lsinner.get(0).getKeyAsString());%></a><%
}
%>
</div>
</body>
</html>
I read around SO and googled it and understood that that i could make a hidden form. Now I create a form with the following two fields and using the anchor tag i submit the form. But the values in the form need to be posted according to the ID clicked, how can i make that dynamic?
So if my form is as follows:-
<form action="details.jsp" method="post">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="phone">
</form>
And my details.jsp will be like:-
<%= request.getParameter("firstname") %>
<%= request.getParameter("phone") %>
I want the firstname and phone to be set according to the ID clicked and the form to be submitted. I can obtain the String/Integer value from my diff object in this page. Would i need to use JQuery? Any help?
Also i know i should be using JSTL. And i will get to that soon. Thank you.
You could call a javascript function during the onclick event of your anchor tag:
<a href="#" onclick="submitHiddenForm("<%=lsinner.getFirstName()%>", "<%=lsinner.getPhone()%>");">...
Your JS function would like like:
function submitHiddenForm(firstName, phone) {
document.getElementById("firstname").value = firstName;
document.getElementById("phone").value = phone;
// attach a name attribute to your form tag
// submit the form
document.myForm.submit();
}
I hope this helps.
EDIT: changed diff to lsinner, since that's the var used in the loop.
On click of the ID call a javascript function passing the values inside the function you can dynamically set the values of the form by getting each element like document.getElementById("firstname").value=value passed similarly set the other fields and in the end document.myform.submit();
Note since we are fetching HTML elements by Id you can use
<form action="details.jsp" method="post" name="myform">
First name: <input type="hidden" name="firstname" id="firstname"><br>
Last name: <input type="hidden" name="phone" id="phone">
</form>
type="hidden" will hide the elements.
check these for better understanding.
How to submit a form using javascript?
If you have the diff object in details.jsp as well, it should be enough to pass only the ID as a parameter, in a normal link.
details
You'd probably do the same in PHP.
JQuery is client side JavaScript and not required to solve your problem.

How to handle buttons with same value but different names in Spring

I have a table that is dynamically created that has rows of movies.
It has a title column,
a media type column,
a rating column,
and a column that contains a "view" button.
When one of these view buttons is clicked,
I would like to go to a page that contains all the details of that movie by sending the title to the controller so I can query for it in mySql.
The problem is that for all these buttons,
the value is always going to be "view".
So my solution is to make the name of the button different as shown in the code below (this is the raw html generated from the jsp):
<html>
<body>
<form action="someAction">
<table>
<tr>
<th>title</th>
<th>type</th>
<th>rating</th>
</tr>
<tr>
<td>title1</td>
<td>DVD</td>
<td>R</td>
<td><input type="submit" name="mediaType.title1" value="view"></td>
</tr>
<tr>
<td>title2</td>
<td>DVD</td>
<td>R</td>
<td><input type="submit" name="mediaType.title2" value="view"></td>
</tr>
<tr>
<td>title3</td>
<td>BLU-RAY</td>
<td>PG-13</td>
<td><input type="submit" name="mediaType.title3" value="view"></td>
</tr>
</table>
</form>
</body>
</html>
I could then use a parameterMap to figure out which view was pressed.
That is messy and Spring has to have some way of being able to do this.
I thought something like this would work in the controller:
#RequestMapping("someAction", params = "mediaType.{title}=view")
public ModelAndView loadPage(String title) {
// use title to query mysql
// build Model
// return ModelAndView
}
However this doesn't work.
Is there something that I can use in Spring that would be simpler and cleaner like above instead of getting the parameterMap from the request?
If I'm understanding this correctly, you have rows of information organized into a table. You're looping through some kind of collection, which has the side effect of making each input field have similar 'name' attributes. As a result, it's difficult to determine which input fields you really care about. You've then chosen to use the button as an identifier (presumably, because only the one button you actually click on get's added to the request -all the others don't get submitted) to determine which 'row', and subsequent input fields.
I think this might all come down to which 'button' you're using. If you're using a literal input tag (type="submit" or "button") the 'value' attribute is what the user sees as the text on the button -so, you're forced to play shenanigans with the 'name' attribute (presumably by adding an index to the name, splitting the string once you get it out of the request, and using that identifier to get the other parameters out of the request that also have the same identifier appended to their 'name' attribute).
JSP
<input type="submit" name="view${varStatus.index}" value="View" />
HTML Source
<input type="submit" name="view3" value="View">
You should probably use the button tag instead. It allows the text that the user sees to be different than the value that is submitted in the request.
JSP
<button type="submit" name="view" value="${varStatus.index}" >View</button>
HTML Source
<button type="submit" name="view" value="3">View</button>
This gives you the 'identifier' for the row.
How Spring fits into this:
I played with the #RequestMapping and the #RequestParam annotations, and was unable to get Spring to give me the values directly into the controller. But, I was able to do it by writing a custom HandlerMethodArgumentResolver along with a custom annotation.
note: I'm using annotations and java config instead of xml config, AND probably more importantly -this was a quick and dirty example to get it working. adjust it as needed for your situation.
HandlerMethodArgumentResolver
Annotation
Controller method
Instead of putting the table inside one form, you could put multiple forms inside the table, in the TRs:
<tr>
<form action="someAction">
<td>title1<input type='hidden' name='title' value='title1' /></td>
<td>DVD</td>
<td>R</td>
<td><input type="submit" value="view"></td>
</form>
</tr>
Then each title has its own form and you send in the title (always with parameter name of title) from a hidden input.
The solution lies in this statement:
"I have a table that is dynamically created that has rows of movies".
Presumably,
you are looping through a list of movies and generating the table in the jsp file and each row has some unique identifier.
Add a hidden to identify the selected row.
Set the value of the hidden value in an onclick handler from the submit buttons.
Here is some example stuff:
<form ...>
<c:forEach blah var="row">
<tr>
...
<td><input type="submit" value="View" onclick="setSelectedRow('${row.id}')"/></td>
</c:forEach>
<input type="hidden" id="blammy" name="blammy" value=""/>
</form>
<script type="text/javascript">
function setSelectedRow(rowId)
{
... set blammy.value equal to rowId.
}
</script>
// the id is used by JavaScript to find the object in the DOM.
// the name is what appears in the request.
#RequestMapping("someAction")
public ModelAndView loadPage(
#RequestParameter("blammy") final String blammy)
{
...
}

Struts logic:iterate input field

I currently have the following code and the data is displayed fine.
<logic:iterate name="myList" id="product" indexId="iteration" type="com.mycompany.MyBean">
<tr>
<td> <bean:write name="product" property="weight"/> </td>
<td> <bean:write name="product" property="sku"/> </td>
<td> <bean:write name="product" property="quantity"/> </td>
</tr>
</logic:iterate>
But now I need to make the "quantity" part modifiable. The user should be able to update that field, press submit and when its sent to the server, "myList" should automatically update with the new quantities.
I've tried searching for help on this but all I keep finding is examples on how to display data only, not modify it. Any help would be appreciated.
So this is tricky, because there are many things to get done in order for it to work. First, declare your tags inside the iterator with the html tags, with attribute INDEXED=TRUE and an ID DIFFERENT THAN THE NAME, i also took out the "indexId" attribute to use the simple "index" word for the index:
<logic:iterate name="myList" id="myListI" type="com.mycompany.MyBean">
<tr>
<td> <html:input name="myListI" property="weight" indexed="true"/> </td>
<td> <html:input name="myListI" property="sku" indexed="true"/> </td>
<td> <html:input name="myListI" property="quantity" indexed="true"/> </td>
</tr>
after that, in order for struts to be able to get and set the attributes of your beans, you need to declare EXTRA get and set methods inside your collection object, using the name you wrote in the id of the iterate tag. In this case, you would write 2 extra get and set methods for the "myListI" :
public void setMyListI(int index, myBean value){
this.myList.add(value);
}
public myBean getMyListI(int index){
return this.myList.get(index);
}
I think Th0rndikes answer is mostly correct. My implementation is slightly different, so it might be worth trying this as well.
Form
private List<Parameter> activeParameters;
public List<Parameter> getActiveParameters() {
return activeParameters;
}
public Parameter getParam(int index){
return this.activeParameters.get(index);
}
JSP
<logic:iterate name="MyForm" property="activeParameters" id="param">
<tr>
<td><bean:write name="param" property="prompt"/></td>
<td><html:text name="param" property="value" indexed="true"/></td>
</tr>
</logic:iterate>
In summary, I didn't use Type in the iterate tag, using the property tag instead. In the bean adding a getter with matched the name of the iterate ID in the JSP (param) with an index as a method parameter did the trick.
Take a look at this: http://wiki.apache.org/struts/StrutsCatalogLazyList
Indexed Properties
Struts html tags have an indexed attribute which will generate the
appropriate html to populate a collection of beans when the form is
submitted. The trick is to name the id attribute to the same as the
indexed property.
For example the following jsp...
<logic:iterate name="skillsForm" property="skills" id="skills">
<html:text name="skills" property="skillId" indexed="true"/>
</logic:iterate>
...will generate the following html
<input type="text" name="skills[0].skillId value="..."/>
<input type="text" name="skills[1].skillId value="..."/>
....
<input type="text" name="skills[n].skillId value="..."/>
When the form is submitted BeanUtils will first call the
getSkills(index) method to retrieve the indexed bean followed by
setSkillId(..) on the retrieved bean.
Theoretically, the indexed attribute of the struts html tags could be used for this:
Valid only inside of logic:iterate tag. If true then name of the html tag will be rendered as "id[34].propertyName". Number in brackets will be generated for every iteration and taken from ancestor logic:iterate tag.
But, there is no corresponding indexed attribute on the html:errors tag, which limits its usefulness. Also, the required combination of id, name and property attributes can be rather confusing.
I found it easier to use jsp scriptlets to generate the property name including the iteration index. The following code requires that your form has a string array property "quantity".
<% int idx=0; %>
<logic:iterate ...>
<html:text property='<%= "quantity[" + idx + "]" %>'/>
<html:errors property='<%= "quantity[" + idx + "]" %>'/>
<% i++; %>
</logic:iterate>

Categories