ServletRequest.getParameterValues returns only first value - java

I am assigning an integer converted into string value to a hidden input through a loop where s1 is the loop iterator.
<% int k=0;
String s1 = null;
while(mar.next()){
k++;
s1 = Integer.toString(k);%>
<table>
<tr><td><b>User Name </b> </td> <td><%= mar.getString("UserName") %></td></tr>
<tr><td><b>Type </b></td><td> <%= mar.getString("Type") %></td></tr>
<tr><td><b>Complain </b></td> <td><%= mar.getString("Complaint") %></td></tr>
<tr><td><b>Status </b> </td> <td><%= mar.getString("Status") %></td></tr>
<tr><td><b>Date </b> </td> <td><%= mar.getString("Date") %></td></tr>
</table>
<form action = "demo1.jsp" method = "post">
<% out.println(mar.getString("Id")); %>
<input type="radio" name = "<%= mar.getString("Id") %>"value="pending"checked>Pending
<input type="radio" name = "<%= mar.getString("Id") %>" value="done">Done
<input type="submit" name = "B" id = "submit" >
<input type = "hidden" name = "try" value = <%= s1 %> >
<% out.println(s1); %>
</form>
<br>
<br>
<%
}
Below is the code which should return a string of values from 1 to 3 (values of s1)
String[] vals;
vals = new String[3];
out.println(vals.length);
vals = request.getParameterValues("try");
out.println(vals.length);
for(int i=0; i<vals.length; i++){
out.println("Hy");
out.println(vals[i]);
}
It is only returning one value which is the first one and printing vals.length prints 1.

You are creating three forms. For each form there will be separate request made. Since each form contains only one hidden input you will always get only one value for each request for below code
request.getParameterValues("try");
Now if you have to submit all the forms with one click. here or here are the answers

Related

how to remove the duplicated element in the table JSP JAVA array

I have two arrays:
<%String TXTfileArray[] = (String[])request.getAttribute("txt");%>
<%String TXTContentArray[] = (String[])request.getAttribute("content");%>
the data in the array is repeated.
by using the following statement in JSP i can output the array in the table:
<table border="1">
<tr>
<th>txt name</th>
<th>txt content</th>
</tr>
<% for (int i=0; i< TXTfileArray.length;i++){ %>
<tr>
<td> <%=TXTfileArray[i] %> </td>
<td> <%=TXTContentArray[i] %> </td> <%} %>
</tr>
</table>
how to remove the repeated element in the table?
Please do not hard code, as the array is not fixed. the array is depended on the other process.
You could try adding each element in a Set, and if it already exists don't add it to the table:
<% Set<String> a = new HashSet<>();
for (int i=0; i< TXTfileArray.length;i++)
if (a.add(TXTfileArray[i]) { %>
<tr>
<td> <%=TXTfileArray[i] %> </td>
<td> <%=TXTContentArray[i] %> </td> <%} %>
Although I think JB Nizet's suggestion of using LinkedHashSet<SomeClass> is probably a better way to do it.

Working with Java beans and Servlet values dynamically

I have a table that sends a form post of 5 input text with values to servlet. In servlet I get the values and set them into bean class, and the sum that I set it too to bean class as sum.Then I get the values and the sum on the jsp table.The problem, is that now Im creating a button that when I click, I insert a row after the last row, and I want to keep the values too with the sum, How can I do it?
This is my jsp that send the form to Servlet: Test.jsp
<jsp:useBean id="helloBean" scope="request" class="user.HelloBean" />
<form method="post" action="Servlet">
<table id= "sum_table">
<tr>
<td>Test</td>
<td>Total</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td><input type="text" value="Test1" maxlength=25></td>
<td><input type="text" value="${helloBean.sum}" maxlength=3 readonly="readonly"></td>
<c:forEach items="${helloBean.values}" var="item">
<td><input type="text" id="val" name="values" value="${item}" maxlength=2/></td>
</c:forEach>
</tr>
</table>
<p><input type="submit"/></p>
<input type="button" id="btnAdd" value="+"/>
</form>
Now I got the values on servlet, calculate the sum and send them to java bean: Servlet.java
HelloBean hello = new HelloBean();
String[] values = request.getParameterValues("values");
if (values == null) {
values = new String[5];
for(int i = 0; i < 5; i++) {
values[i]= "0";
}
}
Integer sum = 0;
for (int i = 0; i < values.length; i++) {
hello.setSum(sum = sum + Integer.valueOf(values[i]));
hello.setValues(values);
}
request.setAttribute("helloBean", hello);
request.getRequestDispatcher("/Test.jsp").forward(request, response);
And this is my Bean Class: HelloBean.java
public class HelloBean {
String[] values;
Integer sum;
public Integer getSuma() {return sum;}
public void setSum(Integer integer) {this.sum = integer;}
public String[] getValues() {return values;}
public void setValues(String[] val) {this.values = val;}
}
This is how I add a new row:
$("#btnAdd").click(function () {
var row = $("#sum_table tbody > tr:last"),
newRow = row.clone(true);
newRow.find("input").each(function () {
var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
this.id = this.id.replace(/\d+$/, "") + num;
this.name = this.id;
});
newRow.insertAfter(row);
return false;
});
Thank You in Advance!
Simply put a check on the value of sum in JSP page and based on its value add new row.
pseudo code:
if sum is not null then
add a new row in JSP
When page is loaded first time the value of the sum will be null and when redirected by servlet the value is populated and the sum will not be null and a new row is automatically created in the JSP page.
It should be like this and keep in mind the integer overflow problem.
int sum=0;
for (int i = 0; i < values.length; i++) {
sum = sum + Integer.valueOf(values[i]);
}
hello.setValues(values);
hello.setSum(sum);
It should look like in JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<tr>
<td><input type="text" value="Test1" maxlength="25"/></td>
<c:forEach items="${helloBean.values}" var="item">
<td><input type="text" name="values" value="${item}" maxlength="2"/></td>
</c:forEach>
</tr>
<c:if test="${helloBean.sum != null}">
<tr>
<td><input type="text" value="${helloBean.sum}" maxlength="3" readonly="readonly"/></td>
</tr>
</c:if>
Some points:
ID must be unique in the whole page. Multiple input components are created with the same id val in the loop.
Use double quotes around the attribute values of the each tag. Is it typo?
property sum is not readable on type user.HelloBean because there is no getSum() method in class.
Don't need the Bean class
You can add keyup event for input
<form method="post" action="Servlet">
<table id= "sum_table">
<tr>
<td>Test</td>
<td>Total</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td class="test"><input type="text" name="test" value="Test1" maxlength=25></td>
<td class="sum"><input type="text" name="sum" value="" maxlength=3 readonly="readonly"></td>
<td><input type="text" name="mark1" value="" maxlength=2 ></td>
<td><input type="text" name="mark2" value="" maxlength=2 ></td>
<td><input type="text" name="mark3" value="" maxlength=2 ></td>
<td><input type="text" name="mark4" value="" maxlength=2 ></td>
<td><input type="text" name="mark5" value="" maxlength=2 ></td>
</tr>
</table>
<p><input type="button" id="btnSubmit" value="Submit"/></p>
<input type="button" id="btnAdd" value="+"/>
<script>
$("#btnAdd").click(function () {
var row = $("#sum_table tbody > tr:last"),
newRow = row.clone(true);
newRow.find("input").each(function () {
var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
this.id = this.id.replace(/\d+$/, "") + num;
this.name = this.id;
});
newRow.insertAfter(row);
return false;
});
$("#btnSubmit").click(function () {
$("#sum_table tbody tr").each(function() {
var row_total = 0;
$("td:not('.test'), td:not('.sum') input:text",this).each(function() {
var val =$.trim($(this).val());
//console.log('val='+val);
if(val!="" && !isNaN(val))
row_total += Number(val);
});
console.log('row_total='+row_total);
$(".sum :input:text",this).val(row_total);
});
});
</script>
-------------------SERVLET--------------
String[] test = request.getParameterValues("test");
String[] sum = request.getParameterValues("sum");
You can do it this way without using javascript for adding new row, if it helps you.
1) - Add name to the add button
<input type="button" id="btnAdd" ***name="addrow"*** value="+"/>
2) - At Servlet side check if add button is clicked
if (request.getParameter("addrow") != null){
request.setAttribute("addRow","yes");
}
3) - At Jsp side add below your for loop
<c:if test="${not empty request.addRow}">
<td><input type="text" id="val" name="values" value="" maxlength=2/></td>
</c:if>
This will add new emty text field whenever you click on the button.
NOTE: I did not test this code.
Just Replace with your input code I added "values[]" instead of "values"
You can use it as array and also set keys into it
<input type="text" id="val" name="values[]" value="${item}" maxlength=2/>

how to set default radio button comparing database value in jsp

Did a lot of research but couldn't find a working solution.Here's my question.
I have a list of radio buttons named branchlist and i am fetching a value named branch from database. Now i wish to set the radio button as checked whose value is equal to the value of branch. Here is my code:
<%
ArrayList<String> branchlist = new ArrayList<String>();
branchlist.add(0,"Computer Engineering");
branchlist.add(1,"Information Technology");
branchlist.add(2,"Electronic & Telecom");
branchlist.add(3,"Instrumentation Engineering");
branchlist.add(4,"Mechanical Engineering ");
branchlist.add(5,"Civil Engineering");
for(int i=0;i<branchlist.size();i++){
//System.out.println(branchlist.get(i)+"="+branch);
if(branchlist.equals(branch)){%> <--- branch is the string value I am fetching from database.
<input type="radio" name="branch" value="<%=branchlist.get(i)%>" checked="checked" ><%=branchlist.get(i) %><br>
<% }else {%>
<input type="radio" name="branch" value="<%=branchlist.get(i)%>" ><%=branchlist.get(i) %><br>
<%}
}%>
how about this:
<%
ArrayList<String> branchlist = new ArrayList<String>();
branchlist.add(0,"Computer Engineering");
branchlist.add(1,"Information Technology");
branchlist.add(2,"Electronic & Telecom");
branchlist.add(3,"Instrumentation Engineering");
branchlist.add(4,"Mechanical Engineering ");
branchlist.add(5,"Civil Engineering");
for(int i=0;i<branchlist.size();i++){
//System.out.println(branchlist.get(i)+"="+branch);
if(branchlist.get(i).toString().equals(branch)){%>
<input type="radio" name="branch" value="<%=branchlist.get(i)%>" checked="checked" ><%=branchlist.get(i) %><br>
<% }else {%>
<input type="radio" name="branch" value="<%=branchlist.get(i)%>" ><%=branchlist.get(i) %><br>
<%}
}%>

Link to the correct item page by selecting the list of items in for loop

This is my jsp page that retrieve the list of items from database using for loop
<%
itemManager mgr = new itemManager();
Item[] items = mgr.getAllItems();
for(int i = 0; i < items.length; i++){
%>
<tr>
<td> <img border="0" src="<%=items[i].getItemImage() %>" width="100" height="100">
</td>
<td>
<%=items[i].getItemName()%>
<input type="text" name="itemID" value="<%=items[i].getItemID()%>">
<br/>
<%=items[i].getItemDesc()%>
<br/>
Start Bid : <%=items[i].getStartBid()%>
<br/>
Buy it now : <%=items[i].getEndBid()%>
<br/>
Bidding close on : <%=items[i].getDuration()%>
<br/>
<input type="submit" value="View">
<%
}
%></table>
This is the jsp page that link to the item you selected previously
<table border="1" align="center">
<%
itemManager mgr = new itemManager();
Item items = mgr.getItem((Integer)session.getAttribute("ITEM_DATA"));
%>
<tr>
<td> <b> <%=items.getItemName() %></b> </td>
</tr>
</table>
This is the servlet to store the session of the selected item id and forward to the correct item jsp page.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
int id = Integer.parseInt(request.getParameter("itemID"));
session.setAttribute("ITEM_DATA",id);
RequestDispatcher rd = request.getRequestDispatcher("viewItem.jsp");
rd.forward(request, response);
}
However, after I clicked the view button. It keeps linking to the itemID = 1.
The URL dispalys "/ItemServlet?itemID=1&itemID=2" .
In fact, if I click on itemID=2 the URL should display like this:
"/ItemServlet?itemID=2"
As a result, how can I achieve this? Thanks in advance!
The problem in your code is you are using a single form and dynamically creating Input box inside the form. So all the input box will be having same name. That's why when you submit the form all the input box values are sent as request parameters. I just reduced some part in your code for better under standing. Take this as your code
<form action="item" method="get">
<table>
<%
ItemManager mgr = new ItemManager();
Item[] items = mgr.getAllItems();
for(int i = 0; i < items.length; i++){
%>
<tr>
<td>
<%=items[i].getItemName()%>
<input type="text" name="itemID" value="<%=items[i].getItemId()%>">
<input type="submit" value="View"> </td></tr>
<%
}
%></table>
</form>
When you run this code and if you check the rendered HTML code it will be look
<form action="item" method="get">
<table>
<tr><td>
aaa
<input type="text" name="itemID" value="1">
<input type="submit" value="View"> </td></tr>
<tr>
<td>
bbb
<input type="text" name="itemID" value="2">
<input type="submit" value="View"> </td></tr>
<tr><td>
ccc
<input type="text" name="itemID" value="3">
<input type="submit" value="View"> </td></tr>
</table>
</form>
Here All the Input box having same name as "itemID". As a solution you can create the form inside the for loop, so that while submitting only one Input box value will be sent as request.
Create form inside your for loop like below code.
<table>
<%
ItemManager mgr = new ItemManager();
Item[] items = mgr.getAllItems();
for(int i = 0; i < items.length; i++){
%>
<form action="item" method="get">
<tr>
<td>
<%=items[i].getItemName()%>
<input type="text" name="itemID" value="<%=items[i].getItemId()%>">
<input type="submit" value="View"> </td></tr>
</form>
<%
}
%></table>
Hope This will help you.
change the name of text field dynamically.
And use getQueryString() in servlet to find the itemId name and value. by using EL.I hope this will help you

How can I check for gender value by NameID?

I have this code that checks duplicate name id
NameRefBean myNameBean = new NameRefBean();
myNameBean.load(NameID);
if (!myNameBean.getErrFlag()) {
errExistFlag = true;
errCode = DUPLICATE_NAME_ID;
return(false);
I have switch case where it saves data from the jsp page form
case ACTION_SAVE:
if (hdTxnType.equalsIgnoreCase("Add")) {
if (validateInputData()) {
nameBean.setNameID(tbNameID);
nameBean.setName(tbName);
nameBean.setGender(tbGender);
hdTxnType = new String("Update");
}
} else {
nameBean.setNameID(hdNameID);
nameBean.setName(tbName);
nameBean.setGender(tbGender);
}
break;
My question is how can I check for gender value when particular nameid is selected? If user changes gender value from M to F, I need to give a warning on the jsp page saying "gender already exist do you want to modify it?"
Here is my jsp page
<% if (nameBean.getErrFlag()) {%>
<CENTER><b><font color=red><%= nameBean.getErrMsg() %></b></font></CENTER>
<% } %>
<TABLE WIDTH="800" BORDER="0">
<TR>
<TD><B>Name ID: </B></TD>
<% if (nameBean.getTxnType().equalsIgnoreCase("Add"))
{ %>
<TD><INPUT TYPE=TEXT NAME="tbNameID" VALUE="<%= nameBean.getnameID()%>" ></TD>
<% } else { %>
<TD><%= nameBean.getNameID()%> </TD>
<% } %>
<TD><B> Name: </B></TD>
<TD><INPUT TYPE=TEXT NAME="tbName" VALUE="<%= nameBean.getName()%>" ></TD>
<TD><B>Gender: </B></TD>
<TD><INPUT TYPE=TEXT NAME="tbGender" VALUE="<%= nameBean.getGender()%>" ></TD>
</TR>
<BR>
<TR>
<% if (userProfileBean.hasRole("FULL") ) { %>
<TD>
<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes">
<% if (nameBean.getTxnType().equalsIgnoreCase("Update"))
{ %>
<INPUT TYPE=SUBMIT NAME="action" VALUE="Delete">
<% } %>
<INPUT TYPE=SUBMIT NAME="action" VALUE="Cancel">
</TD>
<% } %>
You could add a piece of JavaScript that print the warning, if a user changed the gender. The only thing you have to do then, is to enable this java script if the nameid is already set (then the name already exists, and every change should print the warning.) If the nameid is null, then it is a new name and you must not enable the java script warning functionality.

Categories

Resources