How to pass an array from jsp to servlet - java

I am trying to send some data from jsp to servlet using ajax call; In my java script I have the following method:
function sendMessage(){
var cellPhones=[];
var title=$('#subject').val();
var text=$('#smsText').val();
var groupsName=$('#dg').datagrid('getSelections');
for(var i=0;i<groupsName.length;i++){
cellPhones.push(groupsName[i].cellphone);
}
alert(cellPhones);
$.ajax({
type:"POST",
url:"<%=basePath%>/SendMsgServlet?flag=sendSms",
data:{
title:title,
text:text,
cellPhones:cellPhones
}
}).done(function(){
alert("ok");
})
}
and in my doPost method I have:
if("sendSms".equals(flag.trim())){
String title=request.getParameter("title");
String text=request.getParameter("text");
String[] cellPhones=request.getParameterValues("cellPhones");
this.sendSms(title,text,cellPhones,request,response);
}
The problem is that the cellPhones is null, nut the alert is not null, Could anybody help me please?

Why dont you create a class, which will have array as an attribute. set the field value and then set the obj to request. This will not only help you in the servlet but can also be used incase you want to send some data back to your jsp.

I solved the problem, All I had to do was to convert cellphones to string,no need to hidden element I just added this line of code:
var cellPhone=cellPhones.toString();

At ajax you are sending values as array like:
url= "cellPhone[]=121212&cellPhone[]=121212&cellPhone[]=121212"
But, at servlet you are trying to get value as single value. You need to get values as array []. Try,
String[] cellPhones=request.getParameterValues("cellPhones[]");
|- Use array sign

Related

How can I execute JS on server-side?

I'm on a Java EE project and I need to use the value of a JS var on my Java code but my java code is execute before my JS (logic)
But I need the value of a JS var to execute my java and I think it will work if I execute my js on server-side but I don't know how to do this ...
My code is something like this :
JS :
function(){
var url = "an url of 20.000 char that I can't pass in GET and who is automatically generated by google chart API"
}
Java :
<%
String urlChart = "value of my "url" var in js";
session.setAttribute("urlChart", urlChart);
%>
But I don't know how tu put the value of my JS var un my java code. Can you help me ?
Somebody said me that I have to use AJAX but I don't know how to use it.
That is not possible in my understanding. you must switch to some other alternate solutions. you can use CGI or PHP or AJAX.
http://www.w3schools.com/ajax/
You can check this similiar question: how to send a string to a servlet from javascript using xmlhttprequest
If this won't help, then you need to provide more details because i'm not sure if i understand your problem.

Passing String array from javascript to jsp

I googled a lot but I can't solve my problem. I'm new on jsp, in my application in the main jsp I retrive from a table an array of strings (portfolio items) through a scriptlet in javascript. I have to POST the array to another jsp and passing as parameter into a java method to calculate some portfolio stats (historical data are stored in src directories). The code I wrote is:
//obj is the array
var obj= $('#tablePtf td:nth-child(1)').map(function(response){
return $(this).text();
}).get();
//POST
$.ajax({
type: "POST",
url: "calculatePtf.jsp",
data: {portfolio:obj},
success: function(){
alert('ok');
},
error: function(){
alert('error');
}
});
on the server side (caluclatePtf.jsp):
String[]r=request.getParameterValues("portfolio");
calculate(r);// my method
This causes the NullPointerException on 'r' , so I'm wrong in posting the array. The 'obj' array is not empty (tested).
I tried also dynamically writing hidden inputs setting the 'name' attribute to 'portfolio' and submitting the form but the exception persists.
Where am I wrong? Sugestions for better solution are well accepted. Thanks
Solved, the problem wasn't POST but the starting function for retrieving obj array. Just changed in:
var obj=$('#tablePtf td:nth-child(1)').text();
and now works as aspected.

Passing javascript array tojava servlet

I have found other question regarding on this, but still im having a problem,When i check getParamerterValues, its always return null, and i think im having trouble redirecting it to my controller.Bare with me, in new to web app.
arr = [];
$(document).on("click","#idhere",function(){
$.post("servlet.html","ids="+arr+"",function(response){
});
});
or is there something like converting array of javascript to JSON of array in JSP so i can pass it to my servlet?
String arr [] = request.getParameterValues("ids");
if(arr != null){//this line doesnt return true even my array contains item}
change
String arr [] = request.getParameterValues("arr");
to
String arr [] = request.getParameterValues("ids");
Its always return null, and i think im having trouble redirecting it to my controller
I couldnt see any code to pass the values to the controller. In your jquery function , you have something like this $.post("servlet.html","ids="+arr+"",function(response){
It is not possible to post a value to the other html file from jsp. if you are trying to pass the values to the servlet.
try something like this ,
$(document).on("click","#idhere",function(){
$.post("servletName","ids="+arr+"",function(response){
});
});
Note: servletName refers to the url , mapped in your web.xml for the servlet you are trying to post the data.
Also make sure you jquery function is posting the data correctly to the controller through the browser console .
As the examples below show, the post method wants an json object as the data parameter.
This should do the job
$.post("servlet.html",{"ids": arr.join()},function(response){
});
Examples: Example: Request the test.php page, but ignore the return
results.
1 $.post( "test.php" ); Example: Request the test.php page and send
some additional data along (while still ignoring the return results).
1 $.post( "test.php", { name: "John", time: "2pm" } ); Example: Pass
arrays of data to the server (while still ignoring the return
results).
1 $.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } ); Example:
Send form data using ajax requests
1 $.post( "test.php", $( "#testform" ).serialize() );
see http://api.jquery.com/jquery.post/

Need Native Android/Java Method to Query Online Search Field

I'd like to query a .cfm page via Android but I'm not sure what method I should be using to do so - any suggestions?
Example:
http://www.sheriff.org/apps/arrest/results.cfm?lname=smith&fname=
P.S.
Would I use something along the lines of this?
http://androidexample.com/AsyncroTask_Example_To_Get_Server_Data_-_Android_Example/index.php?view=article_discription&aid=59&aaid=84
use an ajax call with the url with the appropriate first and last name parameters, and then extract the result table from the return value.
see a working jsfiddle sample here: http://jsfiddle.net/FhHXK/
code:
$('#get').click(function () {
$.ajax({
url:'http://www.sheriff.org/apps/arrest/results.cfm?lname=a&fname=b',
type: 'GET'
}).done(function (data){
var result = $(data).find('table.datagrid');
console.log(result.html());
$('body').append(result);
});
});

Java Servlet Programming

How to send/pass values from one servlet(consider it as one project) to another servlet(consider as another project). It's showing number format exception. Is it correct to pass values in sendredirect method or is there any other way
Example:
File: uzkpk2.java
String a1=request.getParameter("a[0]");
aa1=Integer.parseInt(a1);
String a2=request.getParameter("a[1]");
aa2=Integer.parseInt(a2);
String a3=request.getParameter("a[2]");
aa3=Integer.parseInt(a3);
String a4=request.getParameter("a[3]");
aa4=Integer.parseInt(a4);
response.sendRedirect("http://localhost:8080/CSP/czkpk1?y="+y+"&a1="+aa1+"&a2="+aa2+"&a3="+aa3+"&a4="+aa4);
}
catch(Exception e)
{
out.println(e);
}
}
}
File: czkpk1.java
aaa1=Integer.parseInt(request.getParameter("aa1"));
aaa2=Integer.parseInt(request.getParameter("aa2"));
aaa3=Integer.parseInt(request.getParameter("aa3"));
aaa4=Integer.parseInt(request.getParameter("aa4"));
You are using the wrong request parameter to get the value.
aaa1=Integer.parseInt(request.getParameter("aa1"));
aaa2=Integer.parseInt(request.getParameter("aa2"));
aaa3=Integer.parseInt(request.getParameter("aa3"));
aaa4=Integer.parseInt(request.getParameter("aa4"));
Instead of this use
aaa1=Integer.parseInt(request.getParameter("a1"));
aaa2=Integer.parseInt(request.getParameter("a2"));
aaa3=Integer.parseInt(request.getParameter("a3"));
aaa4=Integer.parseInt(request.getParameter("a4"));
since in czkpk1.java you are using the variable names instead of parameters passed in the url present in response.sendRedirect();
And one advice chech for only numeric values before parsing it into string.
The best way to do this is use concept of
Servlet Chaining.
-> Write your value in request context as an attribute using request.setAttribute()
-> After forward the request to second servlet using RequestDispatcher.forward()
-> In second servlet read the value using request.getAttribute()

Categories