get and send data in String[] Array using servlet - java

int i = 0;
String[] pnumbers = new String[3];
String[] pqtys = new String[3];
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pnumber = request.getParameter("pnumber");
DAO dao = new DAO();
Product p = dao.checkProduct(pnumber);
String qunty = request.getParameter("pqty");
while (i < 3) {
pnumbers[i] = p.getNumber();
pqtys[i] = p.getQty();
i++;
}
request.setAttribute("pnum" pnumbers);
}
I need to add 3 items coming by webpage in to this array. but ones you can add one item
<td>
<input type="text" name="pnumber" value="" />
</td>
<td>
<input type="text" name="pqty" value="" />
</td>
i need to add only 3 items to array after adding those 3 i need to get that values again to same page please help?

Once you set attribute in you Servlet like you have done.
request.setAttribute("pnum" pnumbers);
Forward control from Servlet to required JSP and You can access it in your JSP using
request.getAttribute(paramName)
Hint:
if(request.getAttribute("pnum")!=null){
String []strArray = (String []) request.getAttribute("pnum");
for(int i=0;i<strArray.length;i++){
out.println(strArray[i]);
}
}
Print the values at your required point.

Related

How to show a message in the current JSP page after a submit to a servlet? [duplicate]

This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 4 years ago.
I have an Jsp page that has the ID text field which takes the input from the user and that input is read in a servlet. I am also validating that input in servlet. If user enters an wrong input I need to give a text message like wrong input below that ID field only in the Jsp.
Here is the servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
services2 reporteeservice = new services2();
services3 jiraservice = new services3();
service4 empid = new service4();
String id = request.getParameter("ManagerId");
int Number = 1;
PrintWriter out1=response.getWriter();
String n = ".*[0-9].*";
String a = ".*[a-z].*";
String c = ".*[A-Z].*";
if( id.matches(n) && id.matches(a) || id.matches(c))
{
out1.println("valid input");
try {
//s.getList(id);
....
}
else
{
out1.println("not a valid input");
}
But if I give else part as above, it will redirect me to next page and prints not a valid upon giving the wrong input. But, I want that to be displayed in the same page under the ID field in the Jsp.
My JSP page:
<form name = "reportees" method = "GET" action="reportsto">
<center>
<h1><font size="20"> Enter the ID to get the Reportees</font></h1>
<label><font size="+2">ID</font></label>
<input name="ManagerId" ype="text" style="font-size:16pt"/>
<input type="submit" value="submit"/>
<button type="reset" value="Reset">cancel</button>
</center>
</form>
See if this helps you.
<script>
function validateForm() {
var mid = document.getElementById("ManagerId").value;
// If manager id is empty
if(mid===""){
alert("Please enter valid manager id.");
return false;
}
}
</script>
<form name = "reportees" method = "GET" onsubmit="return validateForm()" action="reportsto">
<center>
<h1><font size="20"> Enter the ID to get the Reportees</font></h1>
<label><font size="+2">ID</font></label>
<input name="ManagerId" id="ManagerId" ype="text" style="font-size:16pt"/>
<input type="submit" value="submit"/>
<button type="reset" value="Reset">cancel</button>
</center>
</form>

passing date from jsp to servlet using getParameterValues

I am having error in servlet to pass the value from JSP..
JSP codes :
<table>
<tr>
<td>Day</td>
<td>Start</td>
<td>End</td>
<td>Date</td>
<td> </td>
</tr>
<tr>
<td><select name="availableDay">
<!--Listing days-->
</select></td>
<td><input type="time" name="availableStart"/></td>
<td><input type="time" name="availableEnd"/></td>
<td><input type="date" name="availableDate" /></td>
<td><input type="button" class="add" name="action" value="Add More"</td>
</tr>
</table>
I want to pass availableDate to servlet. Fyi, the row in JSP is dynamically generated. Thus, I pass using []. My servlet codes :
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String[] presentationID = request.getParameterValues("selectavailability");
String[] availableDay = request.getParameterValues("availableDay");
String[] availableStart = request.getParameterValues("availableStart");
String[] availableEnd = request.getParameterValues("availableEnd");
String[] availableDate = request.getParameterValues("availableDate");
SimpleDateFormat availDate = new SimpleDateFormat("dd-MM-yyyy");
Date chosenDate = availDate.parse(availableDate);// THIS IS WHERE I AM GETTING ERROR
try {
if(availableDay != null && availableStart != null && availableEnd != null)
{
for (int i = 0; i < availableDay.length; i++)
{
AvailabilityBean available = new AvailabilityBean();
available.setLecturerID(request.getParameter("lecturerID"));
available.setAvailableDay(availableDay[i]);
available.setAvailableStart(availableStart[i]);
available.setAvailableEnd(availableEnd[i]);
available.setAvailableDate(availableDate[i]); //EFFECTED THIS LINE TOO
available = AddAvailableDAO.addavailable(available);
}
}
}
response.sendRedirect("addAvailability.jsp");
}
catch (Throwable theException) {
System.out.println("hhhhhhh"+theException);
}
}
For extra, AvailabilityBean:
private String availableID;
private String lecturerID;
private String availableDay;
private String availableStart;
private String availableEnd;
private Date availableDate;
private String presentationID;
Error : incompatible types: String[] cannot be converted to String.
Can you show me where is my mistake? And how can i solve this? Thank you
Here is your availableDate Variable which is an array of String.
String[] availableDate = request.getParameterValues("availableDate");
Now , you are using SimpleDateFormat Class to format your String data into Date.
Here parse(String text) will take a String Argument not a type of String[] (Array).
SimpleDateFormat availDate = new SimpleDateFormat("dd-MM-yyyy");
Date chosenDate = availDate.parse(availableDate);// availableDate is a String Array not a String.
So, It will raise an compile-time error incompatible types: String[] cannot be converted to String.
better you should try this
Date chosenDate = availDate.parse(availableDate[0]); //preferred index you may pass as per your requirement.
Note:- availableDate[0] will return a String Object available at index 0.
Here is Your JSP Code sample..
<td><select name="availableDay"> //only one value will get selected so. use getParameterValue() for this field too.
<!--Listing days-->
</select></td>
//this will return only a String not a String[] . So use getParameterValue();
<td><input type="time" name="availableStart"/></td>
//this will also return only a String not a String[] . So use getParameterValue();
<td><input type="time" name="availableEnd"/></td>
//this too will return only a String not a String[] . So use getParameterValue();
<td><input type="date" name="availableDate" /></td> //this too will return a String with getParameterValue();
So, try this .. Code.
String availableDay = request.getParameter("availableDay");
String availableStart = request.getParameter("availableStart");
String availableEnd = request.getParameter("availableEnd");
String availableDate = request.getParameter("availableDate");
instead of this one.
String[] availableDay = request.getParameterValues("availableDay");
String[] availableStart = request.getParameterValues("availableStart");
String[] availableEnd = request.getParameterValues("availableEnd");
String[] availableDate = request.getParameterValues("availableDate");

checkbox index value in java

I am working in spring mvc, I used the following line to generate the checkboxes from DB table.
<td><input type="checkbox" name="loanId" value="${loan.id}" class="it"></td>
I need to get the index of this selected values in my java controller. I am able to get the values which are selected, but how to get the index values?
following code is I am using
String[] loanIds = request.getParameterValues("loanId");
for (String string : loanIds) {
System.out.println("loanIds****"+string);
}
You need javascript to get the index of checkbox and set it to hidden field :
var ids = document.getElementsByName('loanId');
var ind = document.getElementById('loanIndex');
var put = function() {
var arr = [];
var i = -1;
while (ids[++i])
if (ids[i].checked) arr.push(i);
ind.value = arr.join(',');
alert('selected index: ' + ind.value);
};
var i = -1;
while (ids[++i])
ids[i].onchange = put;
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="checkbox" name="loanId" />
<input type="hidden" name="loanIndex" id="loanIndex" value="" />
In controller:
String[] loanIndex= request.getParameter("loanIndex").split(",");
There is no direct method for this purpose.
You can have index as value which is passed on selecting checkbox. You can use this index-value later to get selected record data from in-memory collection i.e. when user selects checkbox and submits request, on server side you will fetch ParameterValues from request and list data from datasource, compare ids then derive selected list.
Using Jquery
var indexString;
var index;
$('#.it').each(function () {
$(this).find('.SomeCheckboxClass').each(function () {
if ($(this).attr('checked')) {
index = $(this).index();
indexString = index + ",";
}
});
});
post this indexString, it is a comma separated index string.

JSON.stringify(array) from jsp to servlet (loop using javax.json-api1.0. jar or javax.json-1.0.jar only)

HTML :
<table>
<tr>
<td>
<input type="hidden" value="flag1" />
</td>
<td>
<input type="text" value="orange" />
</td>
<td>
<input type="text" value="1.00" />
</td>
<td>
<input type="text" value="5" />
</td>
</tr>
<tr>
<td>
<input type="hidden" value="flag2" />
</td>
<td>
<input type="text" value="apple" />
</td>
<td>
<input type="text" value="2.00" />
</td>
<td>
<input type="text" value="5" />
</td>
</tr>
</table>
JS :
var array = $.map($('table tr'), function (val, i) {
var obj = {}, inputs = $(val).find('td input:not(:hidden)');
obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
return val.value;
});
return obj;
});
alert(JSON.stringify(array));
$(document).on("click","#save",function(){
$.post("servlet.html","data="+JSON.stringify(array)+"",function(response){
});
});
Java servlet contains this :
String data = request.getParameter("data");
data looks like this :
[{"flag1":["orange","1.00","5"]},{"flag2":["apple","2.00","5"]}]//this is get from table row data using stringify
i want to get on first loop using javax.json-api1.0.jar or javax.json-1.0.jar only :
on first loop :
flag1
Orange
1.00
5
on second loop :
flag2
Apple
2.00
5
Any help will be best.
You can do it with only json-api, but you must be sure of the structure of the input data.
If not, gson or jackson2 are easier to use.
If you want to use json-api, you could do something like :
First declare a JsonFactoryReader attribute in your servlet because you will create a reader per request.
JsonReaderFactory readerFactory = Json.createReaderFactory(null);
then in your service or doXXX method do :
String data = request.getParameter("data");
// create a reader for json data
JsonReader jr = readerFactory.createReader(new StringReader(data));
// tol level must be an array, and we count the iteration for eventual error messages
JsonArray ja = jr.readArray();
int iteration = 0;
for (JsonValue jv: ja) {
// sub elements must be dicts
if (jv.getValueType() != ValueType.OBJECT) {
throw new FormatException(iteration, jv);
}
for (Entry<String, JsonValue> e: ((JsonObject) jv).entrySet()) {
// the key
String key = e.getKey();
if (e.getValue().getValueType() != ValueType.ARRAY) {
throw new FormatException(iteration, e.getValue());
}
// the values, first is a string
JsonArray array = (JsonArray) e.getValue();
for (int i=0; i<array.size(); i++) {
System.out.println(array.get(0).getValueType());
}
String name = array.getString(0);
// next a float and an int
float fval;
int ival;
try {
fval = Float.valueOf(array.getString(1));
ival = Integer.valueOf(array.getString(2));
}
catch (NumberFormatException ex) {
throw new FormatException(iteration, array);
}
// Do your stuff with those values ...
// for instance Data data = new Data(key, name, fval, ival) ...
iteration++;
}
}
I propose you an exception class to handle format errors (at least you know why it breaked ...):
class FormatException extends ServletException {
FormatException(int i, JsonValue jv) {
super("Iteration " + String.valueOf(i) + " : " + jv.toString());
}
}

Servlet Post parameters : what case can a parameter have several values?

Here is the a function on my servlet to test various things (I'm new to servlets althought I understadn the logic)
public void testParameters(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("\n>>>" + paramName);
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0){
out.print("No Value");
}else{
out.print(paramValue);
}
} else {
System.out.println("Number of parameters "+paramValues.length);
for(int i=0; i<paramValues.length; i++) {
out.print("" + paramValues[i]);
}
}
}
}
(this code I took from a tutorial and tweeked so it might just be something stupid)
I get everything working just fine but I was wandering in what cases does a parameter have several values?
Example: http://myhost/path?a=b&a=c&a=d
The parameter a has values b, c and d.
Example:
<form name="checkform" method="post" action="xxxxx">
Which langauge do you want to learn:<br>
<input type="checkbox" name="langtype" value="JSP">JSP
<input type="checkbox" name="langtype" value="PHP">PHP
<input type="checkbox" name="langtype" value="PERL">PERL
<input type="submit" name="b1" value="submit">
</form>
The form can allow you to select multiple values. If you ticks all check boxes , then the parameter langtype will have the values JSP , PHP and PERL

Categories