This is my HTML page where there will be multiple rows depending on how many data will be in JSON file. The first problem I have is that I have problem with listing down all the color options that can be found in the JSON file. For now it only display only 1 value which is according to the fruit. I do not know what code I should include in the doPost method in Java
<form id="config_form" action="iLoveFruits" method="Post" enctype="multipart/form-data">
<table>
<c:forEach items="${fruits}" var="fruit" varStatus="count">
<tbody>
<tr>
<td><input type="text" name="fruit" id="fruit" value="${fruit.type}"></td>
<td>
<select name="color"><option id="color">${color}</option></select>
</td>
<input type="file" id="image" name="image" var="image" accept=".img,.IMG"/>
<label for="image">Upload</label>
</tr>
</tbody>
<button type="submit" id="submitBtn">Submit</button>
</form>
This is the codes under my doPost method where the file will be uploaded upon pressing the submit button. The issue I am facing is if there is 2 rows for example, whichever "Upload" button I click, it will display the file name under the first row. For example, I want to upload a image for the 3 row of the HTML page, after uploading the image, the name of the file will be shown in the first rather than the third. I do not know how to solve thi s please assist me
for (FileItem uploadItem : uploadItems) {
if (uploadItem.isFormField()) {
String fieldName = uploadItem.getFieldName();
if(fieldName.equals("fruit"))
{
String fruit = uploadItem.getString();
newOutput.put("fruit",fruit);
}
else if(fieldName.equals("color"))
{
String color = uploadItem.getString();
newOutput.put("color",color);
if (cert.toLowerCase().endsWith(".img")) {
File temp = new File(file_dir + File.separator + color);
uploadItem.write(temp);
}
}
}
}
I am trying to get the filename in the textbox according to the row that I am changing
Related
I am able to display a table when a user clicks a search button. But now I want to split the table into chunks of 20 rows where the user can click next or previous to go forward and backward through all of the data. I am not allowed to use JavaScript for this assignment. Only JSP, Java, HTML.
The two debugging out.print() calls are not showing up. A different page is being loaded after one of the buttons is clicked, but the two debugging out.print calls are not displaying any HTML. I have checked out How to know which button is clicked on jsp this post but had no luck.
<form method="GET">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
try {
if ("Previous".equals(val1)) { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if ("Next".equals(val2)) { // Get next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
I also have a follow up question. If the user clicks next or previous button, will my current table on the page be overwritten by the new one? That is my intent but I don't know if it will work that way.
I WAS ABLE TO FIX IT BY DOING THIS:
<form method="POST">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
you should add name with value for button after that you can get by parameter click value.
`<input type="hidden" name="myprevious" value="previous"/>
<input type="hidden" name="mynext" value="next" />
<%
String val1 = request.getParameter("myprevious");
String val2 = request.getParameter("mynext");
try {
if (val1 == "previous") { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if (val2 == "next") { // Go next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
`
I hope it will help you.
Thanks.
Try to use the subList() method of a List<>().
As explained here.
HOW TO IMPLEMENT IT ##
you can put an hidden input in your form to give you the last index for your list like :
<input type="hiden" value="${last_index_of_your_list + 1}" name="index">
Then in your servlet part you put like this :
int index = Interger.ParseInt(request.getParameter("index"));
if(index <= 0){
datalist = datalist(0, 19>datalist.size()? datalist.size() : 19);
}else{
if(clicked_on_next){
datalist = datalist(index, index+19>datalist.size()? datalist.size() : index+19 );
}else{
datalist = datalist(index - 40, index-20>datalist.size()? datalist.size() : index-20 );
}
}
You are using hidden fields but you need to use submit button for next and previous.
<input type="submit" name="myprevious" value="previous"/>
<input type="submit" name="mynext" value="next" />
Make sure both are define in form. when we submit form after that you will get button value in parameter.same my previous answer. because we can not get parameter value without submit form.
Thanks.
I have scenario that, I want to upload multiple files, In which User may or may not upload files, And I want to maintain Index at which position user has uploaded file and want to save file with that index as Name
I referred https://stackoverflow.com/a/17050230/3425489 , In my case I don't want to create new class, so not referred Accepted solution
till now In my Action Class I have
File upload [];
String uploadContentType []
String uploadFileName []
getters and setters
In my jsp I tried
<input type="file" name="upload">
but I'm able to get uploaded files only, not able to maintain index
also tried
<input type="file" name="upload[0]">
<input type="file" name="upload[1]">
<input type="file" name="upload[2]">
with this case, I'm not able to setProperties in my Action class
----Updated----
You can refer my Model Struts 2 : Unable to access Model properties in JSP
For your every ProcessSolutionStep, I want to maintain, which file is uploaded for particular step,
i.e. User may upload file for step 1 and step 5, skipping middle steps, and in view.
I want to display file uploaded for particular step
No need to create a new class (that is one way, if you prefer to encapsulate every object singularly), just use Lists:
public class Upload extends ActionSupport{
private List<File> files;
private List<String> filesContentType;
private List<String> filesFileName;
/* GETTERS AND SETTERS */
public String execute() throws Exception{
System.out.print("\n\n---------------------------------------");
int i=0;
for (File file : files){
System.out.print("\nFile ["+i+"] ");
System.out.print("; name:" + filesFileName.get(i));
System.out.print("; contentType: " + filesContentType.get(i));
System.out.print("; length: " + file.length());
i++;
}
System.out.println("\n---------------------------------------\n");
return SUCCESS;
}
}
Use the multiple attribute and don't forget the right enctype:
<s:form action="upload" enctype="multipart/form-data" >
<s:file name="files" multiple="multiple" />
<s:submit value="Upload files" />
</s:form>
This is How I solved my Problem:
<tr>
<td> Step 1 :
<td>
<input type="hidden" name="isFileUpload" id="id-is-file-upload-0" value="0">
<textarea id="id-solution-0" name="processSolutionSteps" rows="2" cols="50" maxlength="200" class="class-text-area class-text-area-not-blank"></textarea>
<!-- <input type="text" id="id-solution-0" name="processSolution" maxlength="30" size="35"> -->
<p id="id-process-solution-counter-0"></p>
</td>
<td>
<input type="file" id="id-file-0" name="uploads">
</td>
</tr>
<tr>
<td> Step 2 :
<td>
<input type="hidden" name="isFileUpload" id="id-is-file-upload-1" value="0">
<textarea id="id-solution-1" name="processSolutionSteps" rows="2" cols="50" maxlength="200" class="class-text-area class-text-area-not-blank"></textarea>
<!-- <input type="text" id="id-solution-1" name="processSolution" size="35"> -->
<p id="id-process-solution-counter-1"></p>
</td>
<td>
<input type="file" id="id-file-1" name="uploads">
</td>
</tr>
<tr>
<td> Step 3 :
<td>
<input type="hidden" name="isFileUpload" id="id-is-file-upload-2" value="0">
<textarea id="id-solution-2" name="processSolutionSteps" rows="2" cols="50" maxlength="200" class="class-text-area class-text-area-not-blank"></textarea>
<!-- <input type="text" id="id-solution-2" name="processSolution" size="35"> -->
<p id="id-process-solution-counter-2"></p>
</td>
<td>
<input type="file" id="id-file-2" name="uploads">
</td>
</tr>
I just post few sample code of my <tr> tag
I have maintained one hidden field isFileUpload with inital value 0 , as many no. of my <input type="file">,
After uploading file, on its change event I changed value of isFileUpload to 1 as
$('#id-solution-table').on('change', 'input[type=file]', function () {
$('#id-is-file-upload-'+$(this).prop("id").split("-")[2]).val(1);
});
And In my Action Class I have this code
Depending upon values of isFileUpload i.e. I have checked it with 1,
Means I have uploded file at this index position and Mapped with uploaded file array which is uploads
private File [] uploads;
private String [] uploadsFileName;
private String [] uploadsContentType;
private short isFileUpload [];
try {
int fileIndex = 0;
for (int i = 0; i < this.isFileUpload.length; i++) {
if( this.isFileUpload[i] == 1 ) {
System.out.println(" index "+i+ " isFileUpload "+this.isFileUpload[i]);
System.out.println("Index "+i+ " "+this.uploadsFileName[ fileIndex ]);
String filePath = path;
new File(filePath).mkdirs();
FileUtils.copyFile(this.uploads[ fileIndex ], new File(filePath+"/"+i+"."+FilenameUtils.getExtension(this.uploadsFileName[ fileIndex ])));
++fileIndex;
}
}
} catch(Exception exception) {
addActionError("Some files not uploaded.");
exception.printStackTrace();
}
In my jsp(index.jsp) I display some items in table with checkbox at the beginning of each row. If user check a row and click the confirm button it goes to other jsp(second.jsp) where I need to display all the rows which are checked in index.jsp.
my table looks like this and assume i enclosed table in form tag.
<form:form method="post" action="/somereq" modelattribute="transferInvoice">
<table id="assets-tbl" border="1"
class="table table-bordered table-hover table-striped"
<tbody id="assets-tbl-body" >
<c:forEach items="${transferinvoice}" var="invoice" varStatus="status">
<tr>
<td><input id="cartcheckbox" class="case" type="checkbox" name="case" value="${invoice}"/></td>
<td>${invoice.some}</td>
<td>${invoice.num}</td>
<td>${invoice.name}</td>
<td>${invoice.loca}</td>
<td>${invoice.time}</td>
</tr>
</c:forEach>
</tbody>
Can any one help me?
I tried this but some how able to fetch the selected rows into controller but how to pass these values to another jsp as java bean type unless can't able to parse the results in second.jsp
#RequestMapping(value = "somereq", method = RequestMethod.POST)
protected ModelAndView transferInvoiceConfirm(final HttpServletRequest request, final HttpServletResponse response)throws Exception {
Model model = new ExtendedModelMap();
String[] checkeditems =request.getParameterValues("caseob");
List<String> list = Arrays.asList(checkeditems);
List<beantype> invoicelist = new ArrayList<beantype>(list);
model.addAttribute("invoiceList", list);
return new ModelAndView("asset/secondform", model.asMap());
}
and in the second jsp, I am displaying the checked items in table as
<c:forEach items="${invoiceList}" var="invoice" varStatus="status">
<tr>
<td>${invoice.name}</td>
<td>${invoice.code}</td>
<td>${invoice.model}</td>
<td>${invoice.loc}</td>
<td>${invoice.date}</td>
</tr>
</c:forEach>
Somehow i feel, i am doing wrong things. Can any one please help to fix this issue?
Change this line
String[] checkeditems =request.getParameterValues("caseob");
To this line
String[] checkeditems =request.getParameterValues("case");
Because as you defined, your input name is "case" .
<td><input id="cartcheckbox" class="case" type="checkbox" name="case" value="${invoice}"/></td>
I hope this helps you!
Write a javascript which will trigger on onclick event of the Confirm button. In the javascript made a request for the second.jsp.
I have created dynamic row on click of button in table using following code :
<script type="text/javascript">
var counter = 1;
function displayResult()
{
counter++;
document.getElementById("myTable").insertRow(-1).innerHTML = '<td><select name="list_dispatch_state" id="list_dispatch_state"><option value="01">01</option><option value="02">02</option><option value="03">03</option></select></td><td><input type="text" name="txt_email'+ counter +'" id="txt_email'+ counter +'" value='+ counter +'></td>';
}
</script>
<body>
<form action="Dogetdat" method="post">
<table id="myTable" border="1">
<tr>
<th>Select</th>
<th>Value</th>
</tr>
</table>
<br />
<button type="button" onclick="displayResult()">Insert new row</button>
<input type="submit">
</form>
</body>
my question is that, on click of button new row and control inside it created but when I click on submit then form submitted to servlet page.
Then how servlet will know that how many data are received ?
Because in servlet I ll get data using
String str1= request.gerParameter("txt_email");
how servlet will know that how many variable it have to create and what will be the name of that ? what will I have to pass in request.gerParameter(""); ?
You have to use the following request.getParameterValues and get the result as an array
String emails[] = request.getParameterValues("txt_email");
I have a javascript function that I need to call on click of the delete button -
JavaScript:
function test(var1) {
alert(var1);
}
JSP code (logs is an ArrayList of length 10):
<table>
<%
for(int i=0; i<len; i++)
{
%>
<tr>
<td><%out.println(logs[i].getItemName());%></td>
<td><%out.println(logs[i].getItemDesc()); %></td>
<td> <input class="submit" type="submit" value="Delete" onclick="test(<%logs[i].getItemName();%>);"/></td>
</tr>
<%
}
%>
</table>
This will print the output as -
Name1 Description1 Delete_Button
Name2 Description2 Delete_Button
.
.
Name10 Description10 Delete_Button
I am not getting how to send the correct itemname value to the JavaScript, when I click on a corresponding row's delete button. Currently I am getting the value as undefined in the JavaScript alert when I click any of the delete buttons.
onclick='test("<%=logs[i].getItemName();%>");'