how can pass array to java servlet - javascript

On my jsp, this is my code :
$('.save').on("click",function(){
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;
});
var data = JSON.stringify(array);
$.post("Controller.html", data, function(response) {
/// i dont know what to put here,so i think this where i get trouble with
});
});
but still data is null when i check on servlet.
this is my servlet :
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data=request.getParameter("data");
if (data== null) {
System.out.println("null");
}
RequestDispatcher view = request.getRequestDispatcher("/page.jsp");
view.forward(request, response);
}
fiddle here

First you need to send the data, you can use an ajax post method:
$.post("yourservlet", data=JSON.stringify(array), function(response) {
// handle response from your servlet.
alert(response)
});
In servlet, you retrieve the data with the command:
String data=request.getParameter("data");
Then you need to parse the json, you can use a library like JSON simple:
Object obj = JSONValue.parse(data);
JSONArray array = (JSONArray) obj;
Or you can manually parse it. Based on your code, your json string will look like this:
data = "[{'orange':['1.00','5']},{'apple':['2.00','5']}]";
You can use split() method or StringTokenizer to separate each object, but you should write your own parser method, for this you can find many tutorials on google.

Javascript is in client-side. And java servlet is for server-side.
You must use ajax to make a call from client-side to your servlet.

Related

How to access the given stringified data in Javascript

I am trying to access the data I passed from a Javascript array, to Java servlet and back to Javascript but I am getting "undefined".
Below is my Javascript code:
var buildingNo = [];
// Assuming the buildingNo's values are the following:
buildingNo = 12345, 54321;
$.ajax ({
url: env + "/webaapp/myTestWeb/myTestEarFile",
timeout:0,
cache: false,
data: {postalCode: postalCode, buildingNo: JSON.stringify(buildingNo)},
success:function(data){
alert(data);
//The output of this data is below:
//[{"status":"A";"buildingNo":"[\12345\",\"54321\"]"}]
var jsonParse = JSON.parse(data);
alert(jsonParse.status); // This gives out undefined.
}
});
Here is the Java Servlet code snippet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String postalCode = request.getParameter("postalCode");
String buildingNo = request.getParameter("buildingNo");
String status = "A";
JSONObject jsonObj = new JSONObject();
JSONArray jArray = new JSONArray();
jsonObj.put("status",status);
jsonObj.put("buildingNo",buildingNo);
jArray.add(jsonObj);
response.getWriter().write(jArray.toString());
}
How do I get the value of status, buildingNo separately for usage in Javascript?
Cutting through all the code errors in the question, the JSON returned by the servlet is very likely to be correct. If not, JSON.parse() would throw an error and you would not get an undefined value on outputting jsonParse.status.
Then the real issue is that your servlet is sending you an array, so you need to treat it as one:
const jsonParse = [{"status":"A","buildingNo":"[\"12345\",\"54321\"]"}];
console.log(jsonParse[0].status); // "A"

How to use spring mvc to receive array as a parameter?

Convert an array object to a json string using JSON.stringify
var array = [1, 2];
let json = JSON.stringify(array);
console.log(json);
axios.get('http://localhost/goods', json).then(function (res) {
if (res.code == 200) {
console.log("ok");
}
}
Parameters during transmission with Chrome browser console:
My goods controller class, for example:
#RequestMapping(value = "goods",method = RequestMethod.GET)
public String deleteByIds(#RequestBody Integer[] ids) {
goodsService.deleteByIds(ids);
return "ok";
}
Spring mvc can't receive an array.Or am I having a problem with writing axios code? How to solve it?
From your request,
axios.get('http://localhost/goods', json)
It's a get request. So it won't have a body.
You can try changing the get method to post or use #RequestParameter instead of #RequestBody.

Return JSON object from JSP to JS

I am trying to return JSON Object/Array from JSP to JavaScript. I dont know how to import JSP file in JS. I have populated JSON Array with DB values.
main.js:
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "operation.jsp",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {
response(data);
}
});
}
});
});
Operation.jsp:
try{
Class.forName(driverName);
connection = DriverManager.getConnection(connectionUrl, userId, password);
System.out.println("Connection Success");
statement = connection.createStatement();
String sql = "SELECT * FROM sample";
resultSet = statement.executeQuery(sql);
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
while (resultSet.next()) {
System.out.println(resultSet.getString("Name"));
System.out.println(resultSet.getString("Age"));
object.put("Name", resultSet.getString("Name"));
object.put("Age", resultSet.getString("Age"));
array.put(object);
}
System.out.println("The Array is" + array);
response.setContentType("application/json");
response.getWriter().write(array.toString());
} catch (Exception e) {
e.printStackTrace();
}
I need to populate the return JSON data in HTML Dropdown box.
Your jsp is creating a json Array, but the problem is in sending that data to Ajax call.
I would like to suggest few things to do:
1. add a writer flush & close statements in JSP.
response.getWriter().write(array.toString());
response.getWriter().flush();
response.getWriter().close();`
2. Set contentType of JSP page as below:
<%#page contentType="application/json; charset=UTF-8"%>
3. If JSP is not being called(syso does not prints anything) then check the relative path of url : "operation.jsp".
In your web-app, it can be like this /operation.jsp
Make use of servlet instead of JSP, Since you are writing only java code in JSP.
In case of servlet the url will be url : 'operation'.
operation is the url of servlet.
Try to changing your JSON keys as follows:
object.put("label", resultSet.getString("Name"));
object.put("value", resultSet.getString("Age"));
Because, according to documentation:
The label property is displayed in the suggestion menu. The value will
be inserted into the input element when a user selects an item.

How I send the result of the AJAX back to the JSP?

I post some via AJAX in my servet from my jsp
$.ajax({
url: 'myServlet?action=FEP',
type: 'post',
data: {machine: i, name: txt}, // i, txt have some values.
success: function (data) {
alert('success');
}
});
and in my Serlvlet
String jspAction = request.getParameter("action");
//...
if(jspAction.equals("FEP")){
int idMachine = Integer.parseInt(request.getParameter("machine"));
String name = request.getParameter("name");
double value = actions.getValue(idMachine, name); //<-- this variable I want to send it back to the JSP.
}
The data are sent succesfully. However I haven't understand how I send back the vaule to the jsp..
returning a string would go as follows:
response.getWriter().write("a string");
return null;
If you want to return json, you can use many libraries like: http://www.json.org/
This would result in something like following code:
response.setContentType("application/json");
JSONObject jsonObject = new JSONObject();
double aDouble = 38d;
jsonObject.put("returnValue", aDouble);
response.getWriter().write(jsonObject.toString());
return null;
Use
response.getWriter().write(value);
return null;
And in your ajax success block access the value.
See the following link for more understanding http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html

How to return Json object to view in a Async method

I have ASP.NET MVC 2 web app. On page load I call a javascript method:
function getSomeData() {
$.post(GetTablesDataUrl, null,
function (data) {
alert(data);
});
}
here is then called a method in my HomeController.cs
public void GetTablesData()
{
WebClient webClinet = new WebClient();
webClinet.DownloadDataAsync( new Uri("http://somer_url"));
webClinet.DownloadDataCompleted += new DownloadDataCompletedEventHandler(webClinet_DownloadDataCompleted);
}
when download is completed, next method is executed
void webClinet_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
byte[] responseArray = e.Result;
string s = responseArray.ToString();
ReturnDataToPage(s); // return json object
}
inside is am method to return data back to my page like this
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult ReturnDataToPage(string s)
{
var data = s;
return Json(data);
}
but I always get an empty string. What am I doing wrong???
You have two possibilities:
Use a normal controller and because the AJAX call is already async you probably wouldn't need more:
public class TablesController : Controller
{
[HttpPost]
public ActionResult ReturnTables(string s)
{
using (var client = new WebClient())
{
string result = client.DownloadString("http://example.com");
// Assuming the remote address returns a JSON object
// if not parse the response and return Json
return Content(result, "application/json");
}
}
}
Use an async controller and IOCP (I/O Completion Ports):
public class TablesController : AsyncController
{
[HttpPost]
public void ReturnTablesAsync(string s)
{
AsyncManager.OutstandingOperations.Increment();
var client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
try
{
AsyncManager.Parameters["result"] = e.Result;
}
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
};
client.DownloadStringAsync(new Uri("http://www.example.com"));
}
public ActionResult ReturnTablesCompleted(string result)
{
// Assuming the remote address returns a JSON object
// if not parse the response and return Json
return Content(result, "application/json");
}
}
In both cases you would consume those actions the same way:
// Not sure exactly what was the purpose of the "s" query string
// parameter as I am not using it in the action
var data = { s: 'some data' };
$.post('<%= Url.Action("ReturnTables", "Tables") %>', data, function(result) {
// Do something with the result
});
The difference between those two approaches is that the async version would use I/O Completion Ports and wouldn't block any worker threads during the retrieval of the remote resource.
The main issue with your approach is that you are calling the external site ("http://somer_url") asynchronously.
This means that the action called by 'someDataDataUrl' (Which, I assume, is not shown in your question) will return immediately, and this is probably before the asynch call returns with your actual data.
The secondary issue (If my understanding of your - possibly mistyped - question is correct) is that when the asynch call handler is invoked, it calls 'ReturnDataToPage' (Should this be 'ReturnTables'?), and then does nothing with the JsonResult that it gets.
You would be better off calling the external site Synchronously (although this introduces block issues, so timeouts need to be introduced) and the returning the result of this call correctly.
Doing this, however, would entail a bit of extra research (Not something that I've done from .NET, I'm afraid)

Categories

Resources