how to pass Array values from js to JSP file using action - java

js file:
why does the size of dropdown1 is coming as 1?
function savethechanges(){
for(var i=0;i<count;i++)
{
dropdown1[i]=document.getElementById("sel"+i).value;
kot[i]=document.getElementById("kot"+i).value;
item[i]=document.getElementById("itemcode"+i).value;
if(dropdown1[i] == 0){
document.detailsview.action="BillCB.jsp?method=" + "11" + "&itemcode=" +item[i]+ "&kot=" +kot[i]+ "&itemStatus1=" +dropdown1[i]+ "&billno=" +billno;
}
else if(dropdown1[i] == 1){
document.detailsview.action="BillCB.jsp?method="+"9"+"&itemcode="+item[i]+"&kot="+kot[i]+"&itemStatus1="+dropdown1[i]+ "&billno="+billno;
}
else{
document.detailsview.action= "BillCB.jsp?method="+"10"+"&itemcode="+item[i]+"&kot="+kot[i]+"&itemStatus1="+dropdown1[i]+ "&billno="+billno;
}
}
}
JSP file:
while retrieving here the dropdown1 length is 1.but for kot and item length is 18
please provide your solution!
case 11:
gotMethod = true;
billdetails_be.billno = Integer.valueOf(request.getParameter("billno"));
String[] kotCB2=request.getParameterValues("kot");
String[] itemCB2=request.getParameterValues("itemcode");
String[] statCB2=request.getParameterValues("itemStatus1");
int[] kotarr2=new int[kotCB2.length];
int[] itemarr2=new int[itemCB2.length];
int[] statarr2=new int[statCB2.length];
System.out.println("IN AVAILABLE:length of array is:"+statCB2.length);
System.out.println("IN AVAILABLE:length of array is:"+kotCB2.length);
for(int i=1;i<itemarr2.length;i++)
{
kotarr2[i]=Integer.parseInt(kotCB2[i]);
}
for(int i=1;i<itemarr2.length;i++)
{
itemarr2[i]=Integer.parseInt(itemCB2[i]);
}
for(int i=1;i<itemarr2.length;i++)
{
statarr2[i]=Integer.parseInt(statCB2[i]);
}
for(int i=1;i<itemarr2.length;i++)
{
int kotint2=kotarr2[i];
int itemint2=itemarr2[i];
int statint2=statarr2[i];
System.out.println( i+"the value of kot in available"+ kotint2);
int availablebill = websrv.availablebill(billdetails_be.billno, kotint2, itemint2,statint2);
}
design page(jsp)
<%
for(int i=0;i<count;i++){
%>
<TR>
<TD> <input id="itemcode<%=i%>" type="hidden" name="itemcode" value=" <%=billdetails_be.get(i).itemcode%>"></TD>
<TD><%=billdetails_be.get(i).itemdescription%></TD>
<TD> <input id="quantity<%=i%>" type="text" name="quantity" style="width: 30px;" readOnly="readonly" value="<%=billdetails_be.get(i).quantity%>" >
<input type="submit" id="inc<%=i%>" onclick= "doIt1(1,<%=i%>);" value="+" style="width:20px; height:20px; border-radius:10px; padding:0 0; " />
<input type="submit" id="dec<%=i%>" onclick="doIt1(-1,<%=i%>);" value="-" style="width:20px; height:20px; border-radius:10px; padding:0 0; "/>
</TD>
<TD> <%=billdetails_be.get(i).price%></TD>
<TD> <%=billdetails_be.get(i).itemstatusdescription%></TD>
<td>
<select name="statusi" id="sel<%=i%>">
<option value="0">Available</option>
<option value="1">Unavailable</option>
<option value="2">Delete</option>
</select>
</td>
<td> <input id ="kot<%=i%>" type="text" style="border: 0px solid #000000;" name="kot" style="cursor: text" readonly="readonly" value="<%=billdetails_be.get(i).kotno%>"></td>
<TD> <input id="myquantity<%=i%>" type="hidden" name="quantity1" value=" <%=billdetails_be.get(i).quantity%>"></TD>
</TR>
<%
}
%>
<td><input style="width: 150px; " class="btn btn-green btn-large" type="submit" name="save" id="save" value="save" class="button" onclick="savetheChanges(<%=count%>);"> </td>
PROBLEM
1.this is in js file ,from which i am passing the value to BillCB.jsp
document.detailsview.action="BillCB.jsp?method=" + "11" + "&itemcode=" +itemcode1[i]+ "&kot=" +kot1[i]+ "&itemStatus1=" +selection[i]+ "&billno=" +billno;
2.this is in BillCB.jsp file (method :11)
String[] statCB2=request.getParameterValues("itemStatus1");
int[] statarr2=new int[statCB2.length];
System.out.println("IN AVAILABLE:length of STATUS array is:"+statCB2.length);
In AVAILABLE:length of STATUS array is:1-this is the problem.

I haven't gone through your code but you might try this solution
Use JSON.stringify method to stringify the array data then send the stringified data to server using below line.
data=JSON.stringify("yourArrayName")
then send "data" as a parameter to JSP
On server side convert it back to array data.

Related

Print hashmap value in jsp page

I am trying to call a HashMap value in jsp page but got error there and error says
There was an unexpected error (type=Internal Server Error, status=500).
For input string: "res"
My code;
<c:forEach items="${onlineExamList}" var="item"
varStatus="loop">
<div>
<b>${item.question1}</b><br>
<div class="radio">
<label><input type="radio" value="a"
name="answers[${loop.index}]">${item.option1}</label>
</div>
<div class="radio">
<label><input type="radio" value="b"
name="answers[${loop.index}]">${item.option2}</label>
</div>
<div class="radio">
<label><input type="radio" value="c"
name="answers[${loop.index}]">${item.option3}</label>
</div>
<div class="radio">
<label><input type="radio" value="d"
name="answers[${loop.index}]">${item.option4}</label>
</div>
<input type="text" name="rightAnswer"
value="${item.rightAnswer}">
//problem in this line
<c:if test="${result != null}">
<br>
<br>
<b>Your answer: ${result.get("res"+loop.index).get(1)}</b>
<br>
</c:if>
</div>
<hr />
</c:forEach>
And this is how i have set hashmap from controller
Map<String, List<String>> mapResult = new HashMap<String, List<String>>();
int totalScore = 0;
for (int i = 0; i < answers.answers.size(); i++) {
List<String> result = new ArrayList<>();
String res = "Wrong";
if (answers.answers.get(i).equals(answers.rightAnswer.get(i))) {
res = "Correct";
totalScore+=10;
}
result.add(res);
result.add(answers.answers.get(i));
result.add(answers.rightAnswer.get(i));
mapResult.put("res" + i, result);
}
ra.addFlashAttribute("result", mapResult);
ra.addFlashAttribute("score", totalScore);
Same things printed on java page
for (int i = 0; i < 10; i++) {
System.out.println(mapResult.get("res" + i).get(0));
System.out.println(mapResult.get("res" + i).get(1));
System.out.println(mapResult.get("res" + i).get(2));
System.out.println("...................................");;
}
How can I print hashmap value in jsp page?
Please check try this.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach items="${currentLoggedInUsersMap}" var="entry">
Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>
I solve the problem by concating the string using concat like this
${result.get("res".concat(loop.index)).get(1)}
The mapResult object is a map containing string arrays
Hashmap<String, List<String>>
you may need to first get the Array from the map object and then iterate over it.
this may help?
<table>
<c:forEach var="results" items="${resultsMap['res' + loop.index]}" varStatus="loop">
<tr>
<c:forEach var="answer" items="${results}" varStatus="status">
<td>
<td>$answer</td>
</td>
</c:forEach>
</tr>
</c:forEach>
</table>

INPUT with multiple values of multiple values each

Not sure the best way to do this...
I have an HTML FORM with multiple rows.. But one of the columns also has multiple values.
I know I can receive the event into a String array with getParamaterValues(). But for the variable days, how do I get that into an array of arrays so it's still related to the event column?
It's all coming out of a database so I can't just hard code it.
I'm sure I actually know the answer but my brain is not cooperating... Thanks in advance for the kick-start... I'm using Java servlets. But it's really just an HTML question.
e.g.
<tr>
<td>
<input type="checkbox" name="event" value="ev1">
<td>
<input type="checkbox" name="days" value="Sat">
<input type="checkbox" name="days" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev2">
<td>
<input type="checkbox" name="days" value="Fri">
<input type="checkbox" name="days" value="Sat">
<input type="checkbox" name="days" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev3">
<td>
<input type="checkbox" name="days" value="Sat">
<input type="checkbox" name="days" value="Sun">
<input type="checkbox" name="days" value="Mon">
Append the value from the events to the name attribute of the days like ev1_days, ev2_days, ev3_days:
<tr>
<td>
<input type="checkbox" name="event" value="ev1">
</td>
<td>
<input type="checkbox" name="ev1_days" value="Sat">
<input type="checkbox" name="ev1_days" value="Sun">
</td>
</tr>
...
...
Then you can do something like:
String[] events = request.getParamaterValues("event");
for(int i=0; i<events.length; i++)
{
String[] days = request.getParamaterValues(events[i] + "_days");
//do something with days....
}
You should actually close your td's and tr's by the way.
You will have to change name of Checkboxes that belongs to the same event to a unique name.
HTML
<tr>
<td>
<input type="checkbox" name="event" value="ev1">
<td>
<input type="checkbox" name="daysA" value="Sat">
<input type="checkbox" name="daysA" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev2">
<td>
<input type="checkbox" name="daysB" value="Fri">
<input type="checkbox" name="daysB" value="Sat">
<input type="checkbox" name="daysB" value="Sun">
<tr>
<td>
<input type="checkbox" name="event" value="ev3">
<td>
<input type="checkbox" name="daysC" value="Sat">
<input type="checkbox" name="daysC" value="Sun">
<input type="checkbox" name="daysC" value="Mon">
Script
var events = [];
var daysA = [];
var daysB = [];
var daysC = [];
var jsonData="";
function c(){
var eventCB = document.getElementsByName("event");
var daysACB = document.getElementsByName("daysA");
var daysBCB = document.getElementsByName("daysB");
var daysCCB = document.getElementsByName("daysC");
for(var i=0;i<eventCB.length;++i){
events.push(eventCB[i].value);
}
for(var i=0;i<daysACB.length;++i){
daysA.push(daysACB[i].value);
}
for(var i=0;i<daysBCB.length;++i){
daysB.push(daysBCB[i].value);
}
for(var i=0;i<daysCCB.length;++i){
daysC.push(daysCCB[i].value);
}
jsonData ='{events:['+events.toString()+'],days:[['+daysA.toString()+'],['+daysB.toString()+'],['+daysC.toString()+']]}'
}
Passing data to Servlet
var jsonComplete = JSON.stringify(jsonData);//You will get below string
//{events:[ev1,ev2,ev3],days:[[Sat,Sun],[Fri,Sat,Sun],[Sat,Sun,Mon]]}
$.ajax({
url:"URLServlet",
type:"POST",
dataType:'json',
data: {jsonComplete : jsonComplete },
success:function(data){
// do whatever required
},
});
Receiving Data in Servlet Using org.json
JSONObject objJSON = new JSONObject(request.getParameter("jsonComplete "));
JSONArray arrEvents = objJSON.getJSONArray("events");
JSONArray arrDays = objJSON.getJSONArray("days");
for(int i=0;i<arrEvents.length();++i){
out.println("event["+i+"]:"+arrEvents.getString(i));//Similar to event[0]:ev1
}
for(int i=0;i<arrDays.length();++i){
JSONArray arrDaystemp = arrDays.getJSONArray(i);
out.println("days["+i+"]:[");
for(int i=0;i<arrDaystemp.length();++i){
out.println(arrDaystemp.getString(i));//Similar to days[0]:[Mon,Tue]
}
out.println("]");
}

Struts forms still empty

I am beginner developer and i'm working on a web application in Java whith struts.
I have a problem with my struts form which stay empty after user enters informations. I've tried many way to resolve it but nothing worked. Maybe the code lines will help you to help me ;).
My Jsp page :
<tr>
<td colspan="5">
<div class="content" align="center">
<form action="statistiques.do" method="POST">
<input type="hidden" name="operation" value="module1">
<tr>
<td><font size="3">État : </td>
<td>
<select name="choixEtat">
<option value='1' selected>Tous</option>
<option value='2' >Actif</option>
<option value='3' >Inactif</option>
</select>
</td>
</tr>
<tr>
<td>Date de début :<span style="font-weight: bolder; color: red;"> *</span></td>
<td>
<input type="text" name="dateDebut" size="10" maxlength="10" id="date" value=""
required="required">
</td>
</tr>
<tr>
<td>Date de fin :<span style="font-weight: bolder; color: red;"> *</span></td>
<td>
<input type="text" name="dateFin" size="10" maxlength="10" id="date2" value=""
required="required">
</td>
</tr>
<tr>
<td><font size="3">Chargé(e)(s)</td>
<td>
<select name="chargeMatricule">
<option value="0" selected></option>
<% for (Utilisateur u : utilisateurs) {%>
<option value="<%=u.getUtilisateurMatricule()%>"><%=u.getUtilisateurNom() + ", " + u.getUtilisateurPrenom()%></option>
<%}%>
</select>
</td>
</tr>
<tr>
<td><font size="3">Activité : </td>
<td>
<select name="activiteNom">
<option value="0" selected></option>
<% for (String s : activites) {%>
<option value="<%=s%>"><%=s%></option>
<%}%>
</select>
</td>
</tr>
<td colspan='5' align="center">
<input type="submit">
</td>
</tr>
</form>
</div>
</td>
and my action :
public class ActionStatistiques extends DispatchAction {
public ActionForward module1(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
FormStatMod1 forms = (FormStatMod1) form;
ServiceStatistiques service = new ServiceStatistiques();
String dd = forms.getDateDebut();
String dateDebut = dd.substring(6, 10) + '-' + dd.substring(3, 5) + '-' + dd.substring(0, 2);
String df = forms.getDateFin();
String dateFin = df.substring(6, 10) + '-' + df.substring(3, 5) + '-' + df.substring(0, 2);
Collection[] collections = service.module1(forms.getChoixEtat(), dateDebut, dateFin);
Collection<Flux> listef = collections[1];
String activiteNom = forms.getActiviteNom();
String chargeMatricule = forms.getChargeMatricule();
Hope, someone will see what's wrong.
Have a nice day!!
Use <html:form>
Here is the example - http://struts.apache.org/release/1.3.x/faqs/actionForm.html
Normally the form is rendered using Struts tags but you can use JSP EL expressions to populate the input fields. For example
<input type="text" name="dateFin" size="10" maxlength="10" id="date2" value="${formStatMod1.dateFin}" required="required">
Ok i found my way!!! Like many times it was a stupid omission ... a setter missed in my form!!! Never will forget to check it.

Updating list after insert new items through a JSP form

In my Spring project, I am passing a List to my JSP page from my controller in this way:
mav.addObject("tipos", tipo.listaTipos());
mav.addObject("campos", atributo.listaKey());
In the JSP page, besides display this items, I can add new items too, as demonstrated in the code below (both HTMl and Jquery):
HTML
<table class="bordered campos" id="edit_campos">
<thead>
<tr>
<th>Campo</th>
<th>#</th>
</tr>
</thead>
<tfoot>
<tr>
<td> <input type="text" name="nome_campo"> </td>
<td> <button type="button" id="incluir_campo" class="btn btn-link">Incluir</button> </td>
</tr>
</tfoot>
<c:forEach var="item_key" items="${campos}">
<tr id="linha_${item_key.id}">
<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>
<td> <button type="button" id="excluir_campo" class="btn btn-link">Excluir</button> </td>
</tr>
</c:forEach>
</table>
JQuery
$("#incluir_campo").on("click", function () {
$.ajax({
type: "GET",
url: "<c:out value="${pageContext.request.contextPath}/key/cadastra_campo"/>",
data: {nome: $("input[name=nome_campo]").val() }
}).done(function(data){
if(data=="yes") {
var newRow = $("<tr>");
cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';
newRow.append(cols);
$("table.campos").append(newRow);
$("input[name=nome_campo]").val("");
}
else {
alert("erro ao incluir campo");
}
}).fail(function(){
alert("falha ao incluir campo");
});
});
But, in this current scenario, the new lines are display with no content, due the list passed to JSP remains the same. How I can update the list I passed to my JSP after I insert a new item?
Look at these lines:
cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>';
cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">Excluir</button> </td>';
Don't use expressions(${}) in Jquery when you working dynamically with DOM elemnts like insert new, update DOM etc, expressions are evaluated when jsp is processed/rendered HTML.
Solution will be:
After getting new item in Controller add it to list, and return the same item as response to AJAX, then append it to exists table. like:
consider your controller method returns data in json like:
var data = {"item_key" : {nome : "abc"}, "item_campo" : {id : "1"}};
then in done do like:
.done(function(data){
if(data.length != 0) {
var $newRow = $("<tr>");
var $newTextbox = $('<input type="text" id="'+data.item_key.nome+'" name="foo">');
var $newButton = $('<button type="button" id="excluir_campo_'+data.item_campo.id+'" class="btn btn-link">Excluir</button>');
$newRow.append($('<td>').append($newTextbox));
$newRow.append($('<td>').append($newButton));
$("table.campos").append($newRow);
$("input[name=nome_campo]").val("");
}
else {
alert("erro ao incluir campo");
}
})
jsfiddle

Retrieving multiple textbox values with same name from JSP in Servlet

I am trying to pass values of textbox with same name from JSP to servlet but not able to accomplish this task.
I tried using this in servlet but i only get one textbox value:
String[] words = request.getParameterValues("words");
String[] meanings = request.getParameterValues("meaning");
My javascript which helps in generating multiple table rows is:
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
cell3.appendChild(element3);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
The Html table generating multiple rows:-
</body>
<form name="managelist" action="../createlistpath" method="post">
<TABLE id="dataTable" width="600px" border="0">
<tr>
<td><b> List Name</b></td>
<td colspan="2"><input type="text" name="listname"></td>
</tr>
<tr >
<td><b>Select</b></td>
<td><b>Word</b></td>
<td><b>Meaning</b></td>
</tr>
<TR >
<TD><INPUT type="checkbox" name="checkbox"/></TD>
<TD> <INPUT type="text" name="words" /> </TD>
<TD> <INPUT type="text" name="meaning" /> </TD>
</TR>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br>
<input type="submit" value = "submit" name="submit">
</form>
</body>
You do not name the dynamically created input elements (to "words" or "meaning")
var element2 = document.createElement("input");
element2.name = "words";
element2.type = "text";
cell2.appendChild(element2);
If you have a form like that:
<form method="post">
<input type="text" name="words"><br>
<input type="text" name="words"><br>
<input type="submit">
</form>
Sends if you put one and two in the textboxs
words=one&words=two
For getting,
String[] words = request.getParameterValues("words");

Categories