Sending form parameters from JSP to Struts action class - java

I am implementing a search functionality in a website I am building, which involves searching by the md5 hash of the name of the file submitted and searching by the notes associated with each submitted file. So, I should detect as to which button is pressed "Search by MD5" or "Search by Notes". This is the code I have:
JSP code for the form:
<form id="search" name="search" action = "search.do"
method="POST" enctype="multipart/form-data">
<table align = "center">
<tr>
<th colspan="4" bgcolor="#004276"><font color="white">
Search for Sample
</th>
</tr>
<tr>
<td><input name="md5" type="text" value="${form.md5}"/></td>
<td><input name="md5search" type="submit" value="Search by MD5"/>
</tr>
<tr>
<td><input name="notes" type="text" value="${form.notes}"/></td>
<td><input name="notessearch" type="submit" value="Search by Notes"/>
</tr>
</table>
</form>
search.do is mapped to SearchResultsAction.java. Code in Java action class (SearchResultsAction) which handles the request is:
if(request.getParameter("md5search").toString().equals("Search by MD5")){
searchSubmissionsList = submissionsDAO.searchSubmissionsByMD5(form.getMD5());
}
if(request.getParameter("notessearch").toString().equals("Search by Notes")){
searchSubmissionsList = submissionsDAO.searchSubmissionByNotes(form.getNotes());
}
But the problem I am facing here is that, request.getParameter("md5search") and request.getParameter("notessearch") return null for some reason. I have been working on this for a while and have not been able to figure it out. The weird thing is that it once worked for me sometime back when I was working on another project. Am I missing something here?

It's null because you used multipart/form-data form encoding instead of (default) application/x-www-form-urlencoded. Basically, you have to (let Struts) extract the text fields from the multipart form data body the same way as you (or Struts) extracted the uploaded file. Or, as there is actually no <input type="file"> field in your form at all, just remove the enctype attribute altogether.
See also
Does form with enctype="multipart/form-data" cause problems accessing a hidden field

Related

How to catch a table in POST and use it as an array

so basically to lay this out I have
AffidavitController - Controller
Affidavit.jsp - GET view page
summary.jsp - POST view page
so basically I have a form that a user fills out and then they hit the submit button and it posts it.
This method is then called in the controller
#RequestMapping(value = "/affidavit", method = RequestMethod.POST)
public String post(AffidavitDetailDto affidavitDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
now within this method I catch the information that was passed over in the response object.
an example of this is I have a name field on the GET view page and the name of this field is 'custName'
so I catch it like so
String contactName = request.getParameter("custName");
model.addAttribute("contactName", contactName);
and then I can display it on my POST view page
<p>Name: ${contactName}</p>
but now I am trying to figure out how I can do the same with a table and treat it like an array
the following is how it is added on the GET view page
<table id="certEmail" name="certEmail">
<tr>
<td>${user.email}</td>
</tr>
</table>
the following is what I have attempted
String[] certEmail = request.getParameterValues("certEmail");
model.addAttribute("certEmail", certEmail);
and this is what I have on the view page to display it
<div id="Emails">
<c:forEach items="${certEmail}" var="email">
<p>${email}</p>
</c:forEach>
</div>
this does not currently work. I know I am probably just doing it wrong so can someone please at least point me in right direction. I just haven't figured out a good google query yet to get an answer.
Table is not a form element (https://www.w3schools.com/html/html_form_elements.asp). Only form element values on form are submitted to server. So instead of
<table id="certEmail" name="certEmail">
<tr>
<td>${user.email}</td>
</tr>
</table>
You should have something like
<table id="certEmail">
<tr>
<td>
<input type="text" name="certEmail" value="${user.email}" />
</td>
</tr>
</table>
if you want your data to be editable, or
<table id="certEmail">
<tr>
<td>
${user.email}
<input type="hidden" name="certEmail" value="${user.email}" />
</td>
</tr>
</table>
if you want it to be hidden and just resent to the server.
While I should denote that second variant generally should be avoided. I would recommend you to pass the user id and use it in back-end to load user and read his email.
Please learn how to use HTML forms: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form

Servlet Request Parameter return null

My code is as follows:
<c:forEach items="${cashInList}" var="list" varStatus="stat">
<tr>
<td>${list.dateandtime}
</td>
<td><fmt:formatNumber type="number" pattern="###,###,###,##0.00" value="${list.cashAmount}" />
</td>
<td>
<input id="checkBoxID" type="checkbox" name="checkBoxValues" value="${list.checkBoxValue}" />
${list.checkBoxValue}
</td>
</tr>
</c:forEach>
in the controller bean
String[] checkedValues = req.getParameterValues("checkBoxValues");
However I got a null value.
When an HTML page is submitted, no parameters are sent on the HTTP request for inputs of type "checkbox" if they are not checked.
Try a simple sample with a static HTMl page containing a simple form with two checkboxes, one checked and the other one not checked. In the development tools of your browser you should see that only a parameter for one input is added on the request.
There is also a problem in your code, you have several inputs with the same ID. You should have a different ID for each checkbox.

Passing Parameters in JSP to Servlet

I have following code
JSP
<tbody>
<c:forEach var="defect" items="${defects}">
<tr>
<td>${defect.name}</td>
<td>${defect.description}</td>
<td>${defect.summary}</td>
<td>${defect.priority}</td>
<td>${defect.originator.name}</td>
<td>${defect.assignee.name}</td>
<td>
<form action="AllOpenDefects?defectId=${defect.id}" method="get">
<input type="submit" value="Update" />
</form>
</td>
</tr>
</c:forEach>
</tbody>
Servlet (in doGet method)
System.out.println((String) request.getParameter("defectId")); // It is printing null
and also in url the defectId is NOT been appended ... Is there any issue with my code?
EDIT: The url is http://localhost:8080/BugManagemetSystem/AllOpenDefects but it should be like http://localhost:8080/BugManagemetSystem/AllOpenDefects?defectId=2
It looks like your browser clears parameters after ?... in action="..." attribute. In that case try passing it via <input type="hidden" .../> like
<form action="AllOpenDefects" method="get">
<input type="hidden" name="defectId" value="${defect.id}"/>
<input type="submit" value="Update" />
</form>
This way form should add them to URL as ?defectId=value of ${defect.id}.
IMHO the short answer to your question is "your code is ok".
As a side note, if it doesn't yield the new required link, it's often an update problem. E.g. try changing the URL algtogether just for testing (form action="Junk"), see if the browser catches it.
If not, try clearing various caches - browser cache, deleting the exploded war and work directories (e.g. in Tomcat it's /webapps/myapp/ and /work)...

On refreshing jsp page got submited again

I have created simple jsp servlet project on that when i submitting jsp form it insert data to specified table but after that when i refersh same jsp form get submitted and same data inserted to table..
ItemUnit.jsp
<form method="POST" action='ItemUnitHandler' name="frmAddUser">
<input type="hidden" name="action" value="insert" />
<table style="width:95%;margin-top:70px;" align="center">
<tr>
<td style="width:10%"> </td>
<td style="width:30%" align="right">Item Unit :</td>
<td style="width:2%"> </td>
<td style="width:40%" align="left"><input type="text" name="itemUnitName" style="width:200px;" /></td>
<td style="width:18%"> </td>
</tr>
<tr><td colspan="5"> </td></tr>
<tr>
<td colspan="5" align="center">
<input type="submit" class="button-2" value="Insert"></input>
<input type="reset" class="button-2" value="Reset"></input>
</td>
</tr>
</table>
</form>
Servlet post method code..
String action = request.getParameter("action");
System.out.println("action :action action : "+action);
if(action == null)
{
redirect = "ItemUnit.jsp";
}
else if(action.equalsIgnoreCase("insert"))
{
ItemUnit objItemUnit = new ItemUnit();
// System.out.println("request.getParameter : "+request.getParameter("itemUnitName"));
objItemUnit.setItemUnit(request.getParameter("itemUnitName"));
dao.addItemUnit(objItemUnit);
redirect = "ItemUnit.jsp";
}
please help me out from this problem...
Ideally, you should land on a static result page, instead of displaying the input form again. The idea is to force the browser to switch to a new URL so that a refresh will not re-trigger another data update. This is the simplest fix.
But if you prefer to use the same screen, you should use a hidden token. You must record some state since you want to differentiate 2 requests from one another: first and second request (the refresh).
Within your logic, plant a token the first time you display the input form. On any incoming request from the same session, check if you have used the token already and use it to determine if this is a second-time request. The diagram below will illustrate it further.
Setup
Processing

How to edit fields of a table?

I have a table to show a long list of items, I am wondering how I can edit the fields and submit the form to update them?
<form name="edit" method="POST" action="edit">
<table border="4">
<tbody>
<c:forEach items="${basket.items}" var="item">
<tr>
<td>
<input name="item.id" value="${item.id}"/>
</td>
<td>
<input label="Price" value="${item.product.price}"/>
<br/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
this is a new one
<input id="edit" type="submit" name="edit" value="Edit"/>
</form>
You are using Struts2, with JSTL and EL instead of Struts Tags and OGNL... is there a particular reason that forces you to drop most of the framework mechanics ?
That said, your inputs aren't valid (no type specified) and the "this is a new one" sentence in the HTML seems to indicate the willing to insert a new row, instead of editing the existing entres. Your description and your code seem to ask two different things... to insert a new one, just make a call to another method of the action (or another action) called "add" instead of "edit", sending one single element and adding it to the collection. No need to use AJAX here...
If instead, the question is really:
how I can edit the fields and submit the form to update them ?
this is the way:
<s:form method="POST" action="edit">
<table border="4">
<tbody>
<s:iterator value="basket.items" var="item" status="ctr">
<tr>
<td>
<s:textfield name="item[%{#ctr.index}].id" />
</td>
<td>
<s:textfield name="item[%{#ctr.index}].product.price" />
</td>
</tr>
</s:iterator>
</tbody>
</table>
<s:submit value="Edit"/>
</form>
I would suggest you make an AJAX call using jquery to update the new one. And then in the success handler you can append the new line to the existing table. Before doing that you need to give your table proper ids so that its easier to use JQUERY.
var newLine = document.createElement("tr");
var cellName = document.createElement("td");
$(cellName).text("itemId");
$(newLine).append(cellName);
// similarly create other td's
$("#modelTable").append(newLine);// replace modelTable by the id of your table

Categories