Post request in javascript with Java rest api doesn't work - javascript

I have a dynamic web project and I want to send data on a mysql database on a remote server.
So, I have a REST api with this code in the file libraryPersistentBean.java :
public void addDemande(DemandeInscription demande) {
Connection con = null;
String url = "jdbc:mysql://my-ip:3306/my-database-name?useSSL=false";
String driver = "com.mysql.jdbc.Driver";
String userName = "my-username";
String password = "my-password";
// List<DemandeInscription> demandes = new ArrayList<DemandeInscription>();
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url , userName, password);
PreparedStatement st =
con.prepareStatement("insert into demandeInscription(name, city, address, food, type, email) values( ?, ?, ?, ?, ?, ?)");
st.setString(1,demande.getName());
st.setString(2,demande.getCity());
st.setString(3,demande.getAddress());
st.setString(4,demande.getFood());
st.setString(5,demande.getType());
st.setString(6,demande.getEmail());
// int result = st.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
I call this function here :
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void post(#FormParam("name") String name, #FormParam("city") String city, #FormParam("address") String address, #FormParam("food") String food,
#FormParam("type") String type, #FormParam("email") String email) throws IOException {
DemandeInscription demande = new DemandeInscription(name, city, address, food, type, email);
LibraryPersistentBean libraryPersistentBean = new LibraryPersistentBean();
libraryPersistentBean.addDemande(demande);
}
And my javascript file, I have :
function sendInscription(){
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
var address = document.getElementById("address").value;
var food = document.getElementById("food").value;
var type = document.getElementById("type").value;
var email = document.getElementById("email").value;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'rest/demandes');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send('name=' + name + '&city=' + city + '&address=' + address + '&food=' + food + '&type=' + type + '&email=' + email);
}
So, I don't have errors, but after a test, I have nothing in the database.
Do you have an idea why it doesn't work ?

I don't have enough points to comment but at first glance the st.executeUpdate() command is commented out. You also might need to do a conn.commit();. And lastly, you'll need a conn.close(); at the end of the addDemande method so you don't leak connections. Preferably the conn.close(); should be in a finally clause. Hope this helps point you in the right direction.
Update:
So here's your addDemande(...) method with the changes to commit and properly close the connections.
public void addDemande(DemandeInscription demande) {
Connection conn = null;
String url = "jdbc:mysql://my-ip:3306/my-database-name?useSSL=false";
String driver = "com.mysql.jdbc.Driver";
String userName = "my-username";
String password = "my-password";
// List<DemandeInscription> demandes = new ArrayList<DemandeInscription>();
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
PreparedStatement st = conn
.prepareStatement("insert into demandeInscription(name, city, address, food, type, email) values( ?, ?, ?, ?, ?, ?)");
st.setString(1, demande.getName());
st.setString(2, demande.getCity());
st.setString(3, demande.getAddress());
st.setString(4, demande.getFood());
st.setString(5, demande.getType());
st.setString(6, demande.getEmail());
// Turn off auto-commit
conn.setAutoCommit(false);
// Uncommented this statement that actually does the update
int result = st.executeUpdate();
// Commit the change
conn.commit();
// Release the resource
st.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}

Related

Sending/Receiving GET Request with Parameters

I have a situation in which I want to select all records from a database given a specific id. The request is first sent from JavaScript, which is received by a Servlet which accesses a DAO that in turn queries a database. The data will then, obviously, make its way back to the front-end. I'm just a little cloudy on passing these parameters along so that the database is queried correctly.
I am currently getting a 500 error which is due to my parameters not being passed along correctly.
Starting at the JavaScript with the initial request:
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/project1attempt/reimbursement?
employee_id=' + x._id, true);
xhr.send();
Receiving the parameters at the Servlet is my biggest point of confusion, therefore the code here is incomplete (rs is a Reimbursement Service):
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("application/json");
int id = ;
List<Reimbursement> reimbursements = rs.findAllReimbursements(id);
String json = new ObjectMapper().writeValueAsString(reimbursements);
resp.getWriter().write(json);
}
And the query:
public List<Reimbursement> findAllReimbursements(int id) {
List<Reimbursement> reimbursements = new ArrayList<>();
try
(Connection c = manager.getConnection()) {
String sql = "SELECT reimbursement_id, date, description, amount,
typing_id, employee_id" +
"FROM reimbursements" +
"WHERE reimbursement_id = ?";
PreparedStatement ps = c.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
Reimbursement r = null;
while (rs.next()) {
r = new Reimbursement();
r.setId(rs.getInt("reimbursement_id"));
r.setDate(rs.getDate("date"));
r.setDescription(rs.getString("description"));
r.setAmount(rs.getDouble("amount"));
r.setTypingId(rs.getInt("typing_id"));
r.setEmployeeId(rs.getInt("employee_id"));
reimbursements.add(r);
}
return reimbursements;
} catch (SQLException e) {
throw new BlabApplicationDataException("Could not connect to
Reimbursement Repository" + id);
}
}
You can use getParameter method of HttpServletRequest to get the URL parameter you need.
Probably, this is the line you are looking for.
String idStr = req.getParameter('employee_id');
if(idStr != null) {
int id = Integer.parseInt(idStr);
}

how to enable Javascript in the HttpURLConnection

i am write a code for access the sever php file and to do find and sort data from the server.... the code works the is no error, when i am using the wamp server but i am change local host in to sever there show a message
"This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support"
this is code i am used for access the sever side php file...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timelist);
Intent datafmto = getIntent();
rsltlist =(ListView)findViewById(R.id.rsltlist);
frm = datafmto.getExtras().getString("from");
to = datafmto.getExtras().getString("to");
Toast.makeText(this, frm + to, Toast.LENGTH_LONG).show();
new asd().execute("http://www.some severname.com/test.php", frm, to);
}
public class asd extends AsyncTask<String,Void,List<models>> {
StringBuffer buffer= null;
BufferedReader red = null;
HttpURLConnection con = null;
#Override
protected List<models> doInBackground(String... params) {
frm= params[1];
to = params[2];
JSONObject json =new JSONObject();
try {
json.put("from",frm);
json.put("to",to);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(String.valueOf(json));
try {
URL url = new URL(params[0]);
con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.connect();
DataOutputStream os = new DataOutputStream(con.getOutputStream());
os.writeBytes(String.valueOf(json));
System.out.println(String.valueOf(json));
os.flush();
os.close();
InputStream in = con.getInputStream();
red = new BufferedReader(new InputStreamReader(in));
String line = "";
buffer = new StringBuffer();
while ((line=red.readLine())!= null){
buffer.append(line);
}
String out = buffer.toString();
System.out.println(out);
JSONObject timing = new JSONObject(out);
JSONArray jarray = timing.getJSONArray("times");
List<models> timelist = new ArrayList<>();
for (int i = 0;i<jarray.length();i++){
JSONObject lastobj = jarray.getJSONObject(i);
models mod = new models();
mod.setRoute(lastobj.getString("route"));
mod.setStart(lastobj.getString("start"));
mod.setStop(lastobj.getString("stop"));
timelist.add(mod);
}
return timelist;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(con!=null){
con.disconnect(); }
try {
if (red!=null){
red.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

d3.json getting data is undefined

I am using URL in d3.json function, the data is showing undefined.
My code here
==============
var jsonURL = "http://192.168.7.102:8080/restful/traffic/json/get";
d3.json(jsonURL, function(error, data){
alert(data);
});
When it is executed data is showing undefined. I created restful web service application to get the data using above URL it returns JSONArray.
Application Code
#GET
#Path("/json/get")
#Produces(MediaType.APPLICATION_JSON)
public JSONArray startReading() throws JSONException {
String json = null;
String newJson = null;
try {
URL url = new URL("http://192.168.7.102:3000/data/traffic");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((json = br.readLine()) != null) {
newJson = json;
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONArray array = new JSONArray(newJson);
return array;
}
When I access the URL in the browser data is displaying. But in d3.json function it is showing undefined instead of data. Due to that, I am not able to display the graph in the browser. Please guide me where I was doing wrong.
var data;
d3.json("http://192.168.7.102:8080/restful/traffic/json/get", function(error, json) {
if (error) return console.warn(error);
data = json;
visualizeit();
});
Have a look at - https://github.com/mbostock/d3/wiki/Requests

Cordova plugin error in success callbackId referenceError: option is not defined

I am trying to modify an existing TCPSockets plugin to work with Cordova 5.0. I have changed it to run in a new thread so it doesn't run off the main thread. This appears to work up until I receive the callbackId from the plugin. It seems to be bogus as the app doesn't recognize it. I get the error in the title and then it says "Uncaught Reference Error: option is not defined". Can someone tell what is wrong with the plugin?
public class TCPSockets extends CordovaPlugin {
private CallbackContext callbackContext;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
// PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
this.callbackContext = callbackContext;
// Log.d("TCPSockets", "Plugin Called");
try {
if (action.equals("sendMessage")) {
if (args != null)
{
final int port = args.getInt(0);
final String host = args.getString(1);
final String message = args.getString(2);
final int connectionTimeout = args.getInt(3);
final boolean secureConnection = args.getBoolean(4);
sendMessage(port, host, message, connectionTimeout, secureConnection);
} else {
// return new PluginResult(PluginResult.Status.ERROR, "User did not specify host information");
callbackContext.error("User did not specify host information");
return true;
}
} else {
// return new PluginResult(PluginResult.Status.INVALID_ACTION);
callbackContext.error("Invalid Action");
return true;
}
}
catch (JSONException e) {
Log.d("TCPSockets", "JSONException: " + e.getMessage());
// return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
callbackContext.error("JSON Exception");
return true;
}
// return r;
// callbackContext.sendPluginResult(r);
return true;
}
public void sendMessage(final int port, final String host, final String message, final int connectionTimeout, final boolean secureConnection)
{
cordova.getThreadPool().execute(new Runnable() {
public void run() {
String reply = "";
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
try {
// If we don't want secure connections, then use Socket class
if(!secureConnection)
{
// Not SSL socket
Socket sock = new Socket(host, port);
Log.d("TCPSockets", "Socket created");
sock.setSoTimeout(connectionTimeout); // Time out all actions for 30 seconds
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Log.d("TCPSockets", "Created reader/writer");
out.println(message);
Log.d("TCPSockets", "Sent message");
reply = in.readLine();
Log.d("TCPSockets", "Received message: " + reply);
out.flush();
out.close();
in.close();
sock.close();
}
else // If we want secure connections, then use SSLSocket class
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Trust always
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Trust always
}
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e) {
Log.d("SSLTCPSockets", "No such algorithm");
// return new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return;
}
try {
sslContext.init(null, trustAllCerts, new SecureRandom());
} catch (KeyManagementException e) {
Log.d("SSLTCPSockets", "Key manager exception");
// return new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return;
}
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket)socketFactory.createSocket(host, port);
socket.setSoTimeout(connectionTimeout);
socket.setUseClientMode(true);
Log.d("SSLTCPSockets", "Connected to host");
SSLSession session = socket.getSession();
if (session.isValid())
{
Log.i(getClass().toString(), "Secure connection");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(message);
Log.d("SSLTCPSockets", "Sent message");
reply = in.readLine();
Log.d("SSLTCPSockets", "Received message: " + reply);
out.flush();
out.close();
in.close();
}
else
{
Log.d("SSLTCPSockets", "Cannot create a secure connection");
// return new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return;
}
socket.close();
}
Log.d("TCPSockets", "Saving pluginResult");
result = new PluginResult(PluginResult.Status.OK, reply);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
catch (UnknownHostException e) {
Log.d("TCPSockets", "Unknown Host");
// return new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, "Cannot connect to server. Please, try again");
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return;
}
catch (java.net.SocketTimeoutException e) {
Log.d("TCPSockets", "Connection timed out");
// return new PluginResult(PluginResult.Status.IO_EXCEPTION, "Connection timed out. Please, try again");
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, "Connection timed out. Please, try again");
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return;
}
catch (IOException e) {
Log.d("TCPSockets", "IOException");
// return new PluginResult(PluginResult.Status.IO_EXCEPTION, "Unexpected error. Please, try again");
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, "Unexpected error. Please, try again");
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return;
}
}
});
}
}
This turned out to be an error in the javascript code. The callback to the js code did in fact work successfully.

doGET in Servlet does not write in the html page

This is my javascript part
<script language=javascript type="text/javascript">
function myFunction() {
var request = new XMLHttpRequest();
request.open("GET", "http://localhost:8080/Test/Servlet");
request.send();
//document.write("Request GET enviado!");
}
</script>
This is my doGEt part
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Request GET recebido!");
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/Tests";
// Database credentials
String USER = "fabio";
String PASS = "hacking";
Connection conn = null;
Statement stmt = null;
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM people";
ResultSet rs = stmt.executeQuery(sql);
out.println("<html><body>");
// Extract data from result set
while (rs.next()) {
//Retrieve by column name
int person_id = rs.getInt("person_id");
String first_name = rs.getString("first_name");
String last_name = rs.getString("last_name");
//Display values
out.println("Person ID: " + person_id + " | ");
out.println("First name: " + first_name + " | ");
out.println("Last name: " + last_name + "<br>");
}
out.println("</body></html>");
// Clean-up environment
out.close();
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
They work until the point that data is retrieved from DB. The part that does not work is posting the out.println back to HTML page. Could someone please advise?
Thanks,
It is not obvious for me from the question if you did anything with the response like this:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var respdiv = document.getElementById("respdiv");
respdiv.innerHTML = "Response=" + xhr.responseText;
}
xhr.open("GET", "http://localhost:8080/Test/Servlet", true);
xhr.send(null);
Also it was interesting that running in built in eclipse browser it responded with "hello" instead of "SOMETHING" (did not check why) but worked when opened in chrome.
doGet code:
PrintWriter out = response.getWriter();
out.println("SOMETHING");
out.flush();
out.close();

Categories