So I've created REST API end-point by using spring framework,
most of the end-points that I've created is using Spring WebSocket, which means I need to create real-time API request from the client-side,
It's pretty easy to use Web Socket on the javascript client-side, but I have no idea how to create Java Client-side to handle that.
Is anyone can give me some example project or code, how to build real-time WebSocket API requests by using Java? just plain java, not using any framework. just basic examples I guess, like how to set up the end-point URL, header, send JSON as body request, handling request data, handling request error, etc
Edit :
I found an example but its Javascript client side :
const url = 'http://localhost:8000';
function connectToSocket(gameId) {
console.log('connecting to the game');
let socket = new SockJS(url + '/gameplay');
stompClient = Stomp.over(socket);
stompClient.connect({},function (frame) {
console.log('connected to the frame: ' + frame);
stompClient.subscribe(
'/topic/game-progress/' + gameId,
function (response) {
let data = JSON.parse(response.body);
console.log(data);
displayResponse(data);
},
);
});
}
is there any equivalent code that I can use in java? thankyou.
Related
I am not sure if this question gonna be considered as duplicated or not, but I wasn't able to find my answer even by googling or through out the QA suggested topics on the SOF. So here I go asking my question:
I have developed a website with Javascript, PHP , AJAX that's using JSON to talk to eachother. And now the client is asking me to change all PHP backend to Spring Boot. That means I gonna talk to the HTML and Javascript and MySql using Java EE Spring Boot and I am not sure how I gonna do it. My main problems are:
1- Is it possible to parse data from Java to the jQuery using JSON ? I mean I retrive data from the MySql and then send it back to the .php file.
The PHP example would be:
$myJSON = json_encode($myObj);
echo $myJSON;
2- Is it possible to get the parsed the respons from the JAVA through the jQuery :
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(getParsedVAL) {
// the variable getParsedVAL is comming from the JAVA file
successmessage = 'Data was succesfully captured';
$("label#successmessage").text(successmessage);
},
error: function(getParsedVAL) {
// the variable getParsedVAL is comming from the JAVA file
successmessage = 'Error';
$("label#successmessage").text(successmessage);
},
});
success: function(getParsedVAL) {
// the variable getParsedVAL is comming from the JAVA file
successmessage = 'Data was succesfully captured';
}
I’m actually transitioning to spring boot from php. Spring boot actually encodes the java object to json automatically. If you developed the back end with some lightweight framework with routing and model controller structure you can easily convert it to spring boost
I am writing a REST server and client for it on Java. I do this for educational purpose.
My server is a web application that handle request from clients via servlet. After that it opens a storage conenction, retrieve data and send it as a json.
My client is a web aplication which has some simple web pages. User click a button, servlet on client handle and send(sic!) request to the server.
May be this way a little bit odd because on the client side moderbn world write just html pages with rich JS code, e.g. Bootstrap, Backbone Angular etc.and server side is wrote via JAX-RS or Spring, but my aim is to write this pet project on pure java as simple as it can be.
I faced with an issue that I don't understand how to send request from client side to the server side. I have received request from user in servlet and I want to send a reponse to the server.
What are possible ways to do that and what is the best one?
Thanks.
You can use Jquery Ajax to call your webservices with parameter required on server side. Update your view/jsp/html based on the data get from servlet.
Ajax Call from javascript :
function onButtonClick(){
$.ajax({
type: "post", //method type
dataType: "json", //response data type
url: ajaxUrl, //your webservice URL
data: "jsonobj", // Data to be send to server
success: function(response) // call back function after get successfull responce
{
// Process JSON response here
}
});
}
Your servlet code :
public class ResellerServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
//Process request here
// Convert your response in JSON and send it back to client
}
}
I am new in web service development. Currently I am developing an application (in html5 using javascript and jquery) in which I wanted to send data to web service in Json format.
My question are: 1) How to send(post) data to web service using javascript ? 2) How to retrieve json data at server side ? 3) How to get data from the web service in json format ? 4) How to retrieve json data at client side ?
Cast you json to string than send to server. In the server side cast it json again.
JSON is just a way to encapsulate data.
You should have parses on both sides that parse the json into data you can work with. On your Java serve you can use e.g. https://code.google.com/p/json-simple/
Easiest would be to use jquery ajax() function.
$.ajax({
type: 'post',
dataType: 'json',
data: { "var1": value1, "var2": value2 },
url: 'www.example.com' })
.success( function() {
console.log( 'success' );
});
This depends on what backend do you use on server, I can reccomend node.js with express.
The same as p1, the only difference that you will have to parse data you have received in success() function.
I am not sure if I understand correctly what you mean.
I am trying to call my own web service (Java Play 2.0.3) from a web application using easyXDM
this is my code on the client side (web):
var formValues = {
email: $('#editUserEmail').val(),
first_name: $('#editUserFirstName').val(),
last_name: $('#editUserLastName').val()
};
this.xhr.request({
url: "http://restserver.dev:9000/users/" + this.model.get('id'),
method: "PUT",
data: formValues
}, function(response){
console.log(response.data);
var jsonResponse = JSON.parse(response.data);
if (jsonResponse.status == 'success'){
alert("saved successfully");
}
});
Here is code for the server (Java) :
final Map<String, String[]> values = request().body()
.asFormUrlEncoded();
// validating
if (values.containsKey("first_name"))
db_user.first_name = values.get("first_name")[0];
if (values.containsKey("last_name"))
db_user.last_name = values.get("last_name")[0];
if (values.containsKey("email"))
db_user.email = values.get("email")[0];
It works fine for POST method, but whenever I tried using PUT method, somehow the server can't get the PUT request body data (values is null). I change it to POST with the same code and it works fine.
Did I do something wrong on the client or server side?
Thanks!
As far as I remember not all browsers support PUT on Ajax requests. This may the reason you are having an issue here. For cross-browser compatibility, you should stick to GET/POST on Ajax calls.
I have a process that I need to follow, I hope this makes sense.
I have a JSP that builds up json data, and sends to a URL. This URL exists, and therefore will be successful.
However, a java based server socket class is listening on a port, and actually picks up the data being sent and processes it. It needs to generate a response for me to receive (ie success or failure codes of what it is going), that I am looking to pick up in the sucess function - but this java socket listener code does not intend on writing this to a JSP or something similar.
Any ideas how the java listener and my success function can meet so I can get the this response.
In my test, I was making the listener code place the response on a JSP and I pick that but, I want a way to not have to place onto a JSP. Is it a case the response (which will be a JSON data) HAS TO actually be served/held within a JSP/PHP/JSON file?
This is my send code below:
$.ajax({
type: "POST",
url: suppliedURL,
data: "jsonData=" + jsonString, // I have already done a json stringify on this.
success: function(data, textStatus, jqXHR) {
var jsonJqXHR = JSON.stringify(jqXHR);
alert('jsonJqXHR : ' + jsonJqXHR);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
},
dataType: "json"
});
Javascript running in a browser page has limited communication and interconnection capabilities. One of the things a javascript program running in virtually any browser can do is send out an HTTP request. So the obvious way to get data into a javascript program is via XMLHttpRequest, via the pattern some people call AJAX. This pattern is implemented in the jQuery ajax function.
The Javascript program needs to connect to an HTTP server - that is where the JSP comes in. It is a Java program that can respond to HTTP GET/POST etc. JSP or a similar HTTP-connected programming environment on the server, is necessary to serve data to the javascript program.
The only challenge therefore is moving the data from the Java socket program running on the server to the JSP also running on the server. One simple way to handle it is via a shared database or filesystem.