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"
Related
I facing problems when I'm trying to fetch data from Servlet.
When I call the servlet by:
function urlFetchRequest(str, body = null, RequestType = 'GET'){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open(RequestType, str, true); // /Test is url to Servlet!
asyncRequest.send(body);
}
catch(exception)
{
alert("Request failed");
}
}
I get back the information I need from the Servlet, and can use it by:
jsonRes = JSON.parse(asyncRequest.responseText)
which is work. My problem is when I need to pass data to the servlet. so I try to do it with fetch() since I have read that I can use JSON objects to the servlet (Again, I cannot use any javascript libraries such as jquery) and I can't use the data that the servlet returns. It getting "undefined".
The javascript scope that I using:
function newFetch(url, options){
fetch(url, options).then(async (res) => {
if(res.ok){
jsonRes = res.
if(theSurvey === null) {
surveyLength = Object.keys(jsonRes).length;
theSurvey = jsonRes;
}
}
});
}
I call it from here:
returnedObject.SurveyLoader = async () => {
//urlFetchRequest("/SurveyServlet");
//await SurveyResults();
newFetch("/SurveyServlet", {
method: "GET",
headers: headers,
})
}
My servlet is:
#WebServlet(name = "SurveyServlet", urlPatterns = {"/SurveyServlet"} )
public class SurveyServlet extends HttpServlet {
public static final Logger LOGGER = Logger.getLogger("SurveyServlet");
private BufferedReader m_reader;
private String m_line;
public String convertWithStream(Map<String, String> map) {
String mapAsString = map.keySet().stream()
.map(key -> '\"' + key + '\"' + ":" + '\"' + map.get(key) + '\"')
.collect(Collectors.joining(", ", "{", "}"));
return mapAsString;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> SurveyObj = new LinkedHashMap<>();
m_reader = new BufferedReader(new FileReader(getServletContext().getRealPath("/poll.txt")));
m_line = m_reader.readLine();
SurveyObj.put(Integer.toString(0), m_line);
int id = 1;
while((m_line = m_reader.readLine())!=null) {
SurveyObj.put(Integer.toString(id), m_line);
++id;
}
String str = convertWithStream(SurveyObj);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//request.setAttribute("ArraySize", id);
// getServletContext().getRequestDispatcher("ResultServlet").forward(request,response);
PrintWriter out = response.getWriter();
out.write(str);
out.flush();
out.close();
}
}
My question here is about the fetch method. I know it gets Objects from a REST API. how do I use it to pass and get data from the servlet? how do I use the data I send to the servlet?
If it's not possible, how do I use XMLHttpRequest to pass data to the servlet? (no $ use)
Thanks.
It does not completely answer my question, but most of it:
I succeed to find a way to send a JSON object to my ajax client.
I used this in my client side (the url is my servlet name, and the options contain only the headers (content type etc):
function newFetch(url, options){
fetch(url, options).then(res => res.json()
).then((resp) => {
jsonRes = resp;
if (theSurvey === null) {
surveyLength = Object.keys(jsonRes).length;
theSurvey = jsonRes;
SurveyResults();
}
});
}
And in the servlet, I used javax library to use JSON object methods, that way:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> SurveyObj = new LinkedHashMap<>();
m_reader = new BufferedReader(new FileReader(getServletContext().getRealPath("/poll.txt")));
m_line = m_reader.readLine();
SurveyObj.put(Integer.toString(0), m_line);
int id = 1;
while((m_line = m_reader.readLine())!=null) {
SurveyObj.put(Integer.toString(id), m_line);
++id;
}
JsonObjectBuilder builder = Json.createObjectBuilder();
SurveyObj.forEach(builder::add);
JsonObject obj = builder.build();
// String str = convertWithStream(SurveyObj);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
try (OutputStream out = response.getOutputStream()) {
JsonWriter jsonW = Json.createWriter(out);
jsonW.write(obj);
jsonW.close();
}
}
I hope it will help someone in the future. anyway, I'm still facing the problem of sending JSON object to the servlet and access it via my request. If anyone can help - it will be perfect. if I'll find the answer, I will edit the post.
Thanks.
Edit: After lots of searching and tries, I find the best way, in my opinion, to pass data to the servlet:
1. Add to your servlet this annotation: #MultipartConfig
2. In your client-side, Use "FormData", and it will be possible to send it via fetch in the request body:
let formData = new FormData();
formData.append("size", surveyLength.toString());
newFetch('ServletResults', {
method: "POST",
//headers: headers,
body: formData
And because the annotation of #MultipartConfig, the servlet knows how to access parameter via "request.getParameter"
I hope this will help to someone in the future. Thanks, everyone.
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.
I am trying to perform a simple json encoding and decoding example with Java.
In this example I am sending signup page details to a Javascript. In Javascript I am encoding those values in json format and sending them to a servlet.
I don't know exactly where I'm going wrong but I'm unable to decode (parse) and print that data at the servlet end.
I'm new to json and Java and I just want to first print values from a json array in a servelet so that I can later put them in a database.
/*this is my javascript code*/
function signup()
{
var request = createCORSRequest( "GET", "http://localhost:8080/jsondem/pass" );
/*pass is the servlet*/
var name = document.getElementById('name').value;
var mobileNo = document.getElementById('mobileNo').value;
var emailId = document.getElementById('emailId').value;
var password = document.getElementById('password').value;
alert(name);
alert(mobileNo);
alert(emailId);
alert(password);
/*i m just printing values for cross checking*/
var data ={"name":name,"password":password,"mobileNo":mobileNo,"emailId":emailId};
alert(JSON.stringify(data));
var sendData = function(data){
alert(JSON.stringify(data));
$.ajax({
url:'http://localhost:8080/jsondem/pass',
type: 'GET',
contentType: 'application/json',
data: JSON.stringify(data),
success: function(response)
{
alert(response);
},
error: function(response)
{
alert('error'+response);
}
});
};
sendData(data);
}
Following is my servlet where I want to take the json data uploaded on localhost into a servlet and I want to print it
/*this is my servlet's doGet Method*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
new JavaHttpUrlConnectionReader();
}
/*I could add all the content in servlet itself but I have done it in separate class JavaHttpUrlConnectionReader*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
class JavaHttpUrlConnectionReader {
public JavaHttpUrlConnectionReader()
{
try
{
String myUrl = "http://localhost:8080/jsondem/pass";
// if your url can contain weird characters you will want to
// encode it here, something like this:
myUrl = URLEncoder.encode(myUrl, "UTF-8");
doHttpUrlConnectionAction(myUrl);
}
catch (Exception e)
{
System.out.println(e);
}
}
/*i m doing this by calling a method doHttpUrlConnectionAction*/
private void doHttpUrlConnectionAction(String myUrl) throws Exception {
URL url = null;
BufferedReader reader = null;
StringBuilder stringBuilder;
JSONParser jsonParser = new JSONParser();
try
{
// create the HttpURLConnection
url = new URL(myUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here
connection.setRequestMethod("GET");
// uncomment this if you want to write output to this url
//connection.setDoOutput(true);
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();
// read the output from the server
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
String name = (String) jsonObject.get("name");
System.out.println("Name: " + name);
long mobileNo = (long) jsonObject.get("mobileNo");
System.out.println("Mobile Number: " + mobileNo);
String emailId = (String) jsonObject.get("emailId");
System.out.println("Email Id: " + emailId);
String password = (String) jsonObject.get("password");
System.out.println("password: " + password);
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
I am getting the following output. Can anyone help?
Your JavaScript is submitting code to the server. On the server side (in the servlet), you need to read the data in the doGet method. You wouldn't "connect" to the server again. Here is an example of the doGet method implementation:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
String mobileNumber = request.getParameter("mobileNo");
//And so on...
}
Additionally, as you're sending data to the server, you'd rather use the POST http method and, in the servlet, implement doPost instead of doGet.
Do not use HTTP GET request when you intend to change the server state - updates to data.
step1: so your $.get should be $.post
step2: verify if the request is properly sent - you can use many tools. I prefer chrome developer console - use network tab to view the request parameters and payload.
step3: read the values sent in the server side
Corrections:
steps1 & step2: I tried your java script code - request is being sent properly. just a slight modification of your code :
function signup() {
var name = document.getElementById('name').value;
var mobileNo = document.getElementById('mobileNo').value;
var emailId = document.getElementById('emailId').value;
var password = document.getElementById('password').value;
var data = {
"name" : name,
"password" : password,
"mobileNo" : mobileNo,
"emailId" : emailId
};
var sendData = function(data) {
alert("sending: " + JSON.stringify(data));
$.ajax({
url : 'http://localhost:8080/jsondem/pass',
type : 'POST',
contentType : 'application/json',
data : JSON.stringify(data),
success : function(response) {
alert(response);
},
error : function(response) {
alert('error' + JSON.stringify(response));
}
});
};
sendData(data);
}
step3: Here is the code i used to test using servlet
#WebServlet(urlPatterns={"/pass"},name="testServlet")
public class TestServlet extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("got the request");
BufferedReader br = req.getReader();
String s = br.readLine();
while(s!=null){
System.out.println("read line is " + s);
s = br.readLine();
}
br.close();
}
}
output in console : read line is {"name":"a","password":"d","mobileNo":"b","emailId":"c"}
If for some reason, you dont want to use servlets and intend to handle directly using URLConnection, post the stacktrace you get.
On the server side, you are trying to reconnect to the server. You should read about the servlet model in Java and know how to implement a proper servlet, and how to read parameters from the client request.
Your client (javascript) implementation is OK. It sends a proper request to http://localhost:8080/jsondem/pass with a JSON body (though it should use POST method).
But your server implementation is wrong:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
new JavaHttpUrlConnectionReader();
}
You should read the data here (above) from the request object.
String myUrl = "http://localhost:8080/jsondem/pass";
// if your url can contain weird characters you will want to
// encode it here, something like this:
myUrl = URLEncoder.encode(myUrl, "UTF-8");
doHttpUrlConnectionAction(myUrl);
}
catch (Exception e)
{
System.out.println(e);
}
Here (above) you are trying to connect from the server side to the server again. I don't think this is what you wanted to do.
System.out.println("Name: " + name);
long mobileNo = (long) jsonObject.get("mobileNo");
System.out.println("Mobile Number: " + mobileNo);
String emailId = (String) jsonObject.get("emailId");
System.out.println("Email Id: " + emailId);
String password = (String) jsonObject.get("password");
System.out.println("password: " + password);
I think you wanted to return strings to the client. System.out.println does not send back anything to the client. It prints out on the server side console.
You should instead write on the response object below:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
new JavaHttpUrlConnectionReader();
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>pass</servlet-name>
<servlet-class>pass</servlet-class>
</servlet>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>pass1</servlet-name>
<servlet-class>pass1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pass</servlet-name>
<url-pattern>/pass</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pass1</servlet-name>
<url-pattern>/pass1</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
check this out #Balaji Krishnan
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
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.