Updating database record after displaying to user - java

I have a question on how to update a particular record in a database using JSTL and java servlets.
Ok to call one record, I use a servlet to run a query to populate a jsp page using this type of format.
ResultSet results = getRecords.executeQuery(); //run database query
Result result = ResultSupport.toResult(results);
request.setAttribute("result", result);
RequestDispatcher rd = request.getRequestDispatcher("/showReport.jsp"); //redirect to this page with query info
rd.forward(request, response);
In the jsp page, I use this format to populate the page.
the row number is the corresponding to the index of the value on how the query is run.
<c:forEach var="row" items="${result.rowsByIndex}">
<form action = "/runthis/servlet?id=${row[0]}" method = "get" >
Employee Name<input type="text" value="<c:out value="${row[2]}"/>" />
Department<select>
<option value="<c:out value="${row[4]}"/>"><c:out value="${row[4]}"/></option></select>
<input type="submit" value="Save">
</form>
</c:forEach>
So for instance, if someone changes the Employee Name, but leaves the Department field alone, or vice versa, how would I go about this?
I think I should be able to kick this form action to a "update servlet", but I would rather not "update" every element in the record if I do not need to.
Also I'm still learning web dev, so if you can think of a better way to prepopulate stuff, via javascript or whatever, I'm willing to try that as well, if it's a possible solution.
Thanks for any help!

i think you need to do something like this:
<c:forEach var="row" items="${result.rowsByIndex}">
<form action="/runthis/servlet" method="post">
<input type="hidden" name="id" value="<c:out value="${row[1]}"/>" />
<input type="hidden" name="EmployeeName_orig" value="<c:out value="${row[2]}"/>" />
Employee Name<input type="text" name="EmployeeName" value="<c:out value="${row[2]}"/>" />
<input type="hidden" name="Department_orig" value="<c:out value="${row[4]}"/>" />
Department
<select id="Department" name="Department">
<option value="<c:out value="${row[4]}"/>"><c:out value="${row[4]}"/></option>
</select>
<input type="submit" value="Save" />
</form>
</c:forEach>
and then, in your update servlet (here called /runthis/servlet) you do some form of update employee and set the name and department where the row is id. note that i send the id in a hidden field, but it could just as well be sent in the url as you mentioned in our discussion above!
about your remark on updating every element in a record:
this can be done in different ways. one way is to load the record from database first, and compare the fields to know what fields to update. but that would require an extra read from the database before the update.
another way (the one i have prepared for in my proposed solution) is to have hidden fields, one for each input in your form. this hidden field holds the original value for its input counterpart. this way you can compare the original value with the new value without having to do a read from the database. on the other hand, you're now transferring the double amount of data over the line for each post request.

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.

Spring, Java, HTML: How can I populate an HTML form with values?

I want to write a part of a website that lets the user alter the data of a pre existing book. For that, I am trying to use a form which works fine. I just can't figure out how to get the form to display data in the editing fields so the user doesn't have to enter everything again but can simply change some details. My HTML code looks like this:
<form method="post" role="form" class="ui form" id="bookForm" th:action="#{/editBook}" th:object="${bookForm}">
<div class="field">
<label for="name">Book</label>
<input id="name" name="name" th:field="*{name}" th:errorclass="fieldError" type="text" required="required"/><br/>
</div>
I include some more code about errors and other things but this is basically where I want the form not only to pass values to my java file but also to take values about the book and display them in the editing fields.
I think I need to pass the book that the user wants to edit into this form but I'm not sure how. I have tried:
<input type="hidden" id="currentBook" name="currentBook" th:value="${currentBook}"/>
right before the "div" statement and then passing the "currentBook" into HTML with
model.addAttribute("currentBook", currentBook);
in my #GetMapping method of that website. I then changed the "input" statement in my field as well to
<input id="name" name="name" th:field="*{name}" th:value="${currentBook.name}" th:errorclass="fieldError" type="text" required="required"/><br/>
currentBook.name will give me the name of that book just not within this context. Does anyone know what I'm doing wrong and how it will work?
Thank you in advance!

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)
{
...
}

How to get the value of drop down list?

I want to get the value to of drop down list, to send back to server to match something.
Update:
Sorry, i has to be clear on my question. I am using javascript to get values in client side and sending those back to server with DWR & processing them with JAVA code.
<select><option selected="selected" value="1">EEE</option><option value="2">ECE</option><option value="3">IT</option><option value="4">CSE</option><option value="5">MECH</option></select>
'
<input id="id" type="text" size="5"/>
<input id="name" type="text" size="15"/>
<input id="age" type="text" size="5"/>
<input id="age" type="text" size="5"/>
'
I want to get the values(1,2,3,4,5) ALONG with the other Name, Id, Age values.
I can get field text using dwr.util.getValues().
How can I get that select option value?
Since you specify no server-side language, I assume you want in HTML/JS. So, use this code in javascript, assuming the ID of your combobox is combo1:
<script type="text/javascript">
var combo1 = document.getElementById("combo1");
var val = combo1.options[combo1.selectedIndex].text;
//this will show the value in a Dialog Box
alert(val);
</script>
<select id="id"> ...
var opts = dwr.util.byId("id").options;
Try giving your select element a name attribute:
<select name='department'>...

How to get custom value from text field in JSP?

I'm working in a very simple and small web application, it is a jsp that handles a shopping cart.
What I do at this point is to iterate through all the products that are stored in the car and add them one by one to the jsp with each iteration.
This is the code that adds a row to the jsp in each iteration:
<tr>
<td>
<input type=text name=Quantity value=<%=quantity%>>
</td>
<td>
<input type=text name=id value=<%=id%>>
</td>
<td>
<input type=submit value="Delete" onclick=<%CustomSubmit(request, id); %>>
</td>
</tr>
As you can see I add to the end of each row a submit type control with a custom method for handling Click events, the use of this control is to remove from the car the respective product.
The problem that I have is that when I click in the delete button of a product, the id that is passed to the CustomSubmit(...) method is not the id of the product that I'm trying to remove but the id of the last product added to the jsp.
So, my question is how can I get the correct id from the item that I'm trying to remove?
The way i use to do it is as follows:
Replace
<input type=submit with a button
<input type="button" value="Delete" onclick="deleteIt('yourid');" />
add the deleteIt javascript function, in the function you fill a hidden input field with the id.
Then submit the page and the correct id gets passed to your page
Little sidenote its always prudent to escape all your Strings
dont use <input type=submit but use <input type="submit"
maybe like
<td>
<input type="text" name="id" value="<%=id%>">
</td>
<td>
<input type="button" value="Delete" onclick="deleteItem('<%=id%>')">
</td>
I assume your cart is a list of objects, each having the attributes id and quantity. So I would expect you code to look something like this (noting Peter's answer about using a 'button'):
<input type="button" value="Delete" onclick="CustomSubmit('<%=cartItem.id%>');"/>
I'm not entirely sure what you are trying to do with the 'request' parameter in your original code but if this is the HTTP request all you will get when you try to write it to the JSP is the result of the request.toString method.

Categories