doGET in Servlet does not write in the html page - javascript

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();

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);
}

unable to connect websocket(wss) from c#

In my application I am connecting chrome extension with windows application using websocket,
Javascript code :
var socket = new WebSocket('ws://172.xx.xxx.xx:11223/');
socket.onopen = function(event)
{
// Web Socket is connected, send data using send()
socket.send("hi..");
};
And C# code :
public static TcpListener Weblistener = null;
public static int selWebSocketPort = 0;
public static void StartListeningSahi()
{
Weblistener = new TcpListener(IPAddress.Parse(ipAddStr), portNumForSelenium);
try{
Weblistener.Start();
int TestingCycle = 100;
// Start listening for connections.
while (TestingCycle > 0){
TcpClient handler = Weblistener.AcceptTcpClient();
// An incoming connection needs to be processed.
lock (ClientSockets.SyncRoot){
if (handler != null){
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
SelWebSocketPort = (handler.Client.RemoteEndPoint as IPEndPoint).Port;
NetworkStream networkStream = handler.GetStream();
Byte[] clientReq = new Byte[handler.Available];
networkStream.Read(clientReq, 0, clientReq.Length);
string headerRequest = Encoding.UTF8.GetString(clientReq);
SendResponseToWebSocket(handler, networkStream, headerRequest);
}
else
continue;
}
}
Weblistener.Stop();
}
catch (Exception e){
Console.WriteLine(e.ToString());
}
}
public static void SendResponseToWebSocket(TcpClient handler, NetworkStream networkStream, string headerRequest)
{
// generate accept key fromm client header request
var key = headerRequest.Replace("ey:", "`")
.Split('`')[1]
.Replace("\r", "").Split('\n')[0]
.Trim();
var responseKey = AcceptKey(ref key);
//create the response for the webclient
var newLine = "\r\n";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + responseKey + newLine + newLine;
//send respose to the webclient
Byte[] sendBytes = Encoding.ASCII.GetBytes(response);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
selWebSocketPort = (handler.Client.RemoteEndPoint as IPEndPoint).Port;
}
This is working fine for http site. But after that I changed the this javascript line var socket = new WebSocket('ws://172.xx.xxx.xx:11223/'); to var socket = new WebSocket('wss://172.xx.xxx.xx:11223/'); to support https sites, but unable to do so. I am getting below error on chrome -
WebSocket connection to 'wss://172.16.106.22:11223/' failed: WebSocket opening handshake timed out
The handshaking is getting failed as in the request header I am getting some junk value.
Am I missing something ?

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

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();
}
}
}

How to pass parameters to controller using ajax and javascript?

I am trying to delete an item from shopping cart using Ajax with javascript, but I have trouble passing parameters to the controller. The parameters are null in controller.
My javascript code shows as below:
function removeRow(itemId, rowID){
if (xmlHttp == null)
{
alert("Your browser does not support AJAX!");
return;
}
var query = "action=remove&item=" + itemId;
/* alert(query); */
xmlHttp.onreadystatechange = function stateChanged()
{
if (xmlHttp.readyState == 4)
{
var row = document.getElementById(rowID);
row.parentNode.removeChild(row);
}
};
xmlHttp.open("GET", "addTo.htm", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(query);
return false;
/* var row = document.getElementById(rowID);
row.parentNode.removeChild(row); */
}
My controller code shows as below:
#Controller
#RequestMapping("/addTo.htm")
public class AddToController{
#RequestMapping(method=RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String action = request.getParameter("action");
System.out.println(action);
ModelAndView mv = new ModelAndView();
ArrayList<Item> cart;
if(action.equals("remove")){
System.out.println("cart size is" + cart.size());
Long itemId = Long.parseLong(request.getParameter("item"));
ItemDAO itemDao= new ItemDAO();
Item item = itemDao.get(itemId);
cart.remove(item);
System.out.println(cart.size());
}
return mv;
}
}
The action and item are null in the controller.
Can anyone help with this problem?
You're sending a GET request, so add the parameters as a query after your URL:
xmlHttp.open("GET", "addTo.htm?" + query, true);
and pass in null (rather than your query string) when calling the .send method:
xmlHttp.send(null);
Also, the "application/x-www-form-urlencoded" header is only used when you're sending serialised parameters but using POST, so remove the xmlHttp.setRequestHeader line.
More info: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

How to send/read java ByteBuffer (websocket) from javascript client onmessage function

Server code in java:
#OnMessage
public void onMessage(Session session, ByteBuffer message) {
if (session.isOpen()) {
String msg = new String(message.array());
System.out.println("Message from " + session.getId() + ": " + msg);
try {
session.getBasicRemote().sendBinary(ByteBuffer.wrap("I have got the message".getBytes()));
} catch (IOException ioe) {
System.out.println(ioe.toString());
}
} else {
System.out.println("Session is not open");
}
}
Client code in Javascript:
webSocket = new WebSocket("ws://192.168.10.1:2525/myChat/chat");
webSocket.binaryType = 'arraybuffer';
webSocket.onopen = function(event) {
updateOutput("Connected!");
connectBtn.disabled = true;
sendBtn.disabled = false;
};
webSocket.onmessage = function(event) {
updateOutput(event.data);
};
Note:
Server code works fine when I use it with Web GL client as it is send Binary data.
Javascript client works fine when I read String data in Server end
(from java code):
#OnMessage
public void onMessage(Session session, String message) {}
Thanks in advice for any comments.
I've found the solution to the issue.
I have used ByteBuffer.js library to send/read data of ByteBuffer type in JavaScript:
webSocket.binaryType = "arraybuffer";
In the function onmessage for reading data:
var d = event.data;
console.log(d.toString());
In the function send for sending data:
var bb = dcodeIO.ByteBuffer.wrap(text);
webSocket.send(bb.toArrayBiffer());

Categories