How to build request to java server? - java

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

Related

WebSocket Realtime REST-API client with Java

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.

HttpServletResponse shall send data without printing them to client screen

I am building a web application.
Part of this web application is an ajax request from the client-side to the server:
$.ajax({
url: url,
type: "get",
data: {
id: ID,
},
success: function(response) {
//parameter response contains the data sent back from the server
//some stuff is done to this data in the rest of this function
},
error: function() {
alert("An error occurred.");
}
});
On the server side I am using a servlet to handle the requests.
Once the data from the client is received, and some business logic has been applied to it, I want to send back a simple String.
The data string would then be handled by the following part of the ajax-function above:
success: function(response) {
//parameter response contains the data sent back from the server
//some stuff is done to this data in the rest of this function
},
My problem is this:
I know how to send data to the screen of the client:
PrintWriter out = response.getWriter();
out.println(data);
However, I don't know how to send data (not to the screen but instead) to the ajax-function, so that this ajax-function can then work with the data received from the server.
The java object "response" of class "HttpServletResponse" only provides methods such as "sendError()".
I want to send the data without printing them to the screen.
How can I do that?
*************************UPDATE********************************************
I tried to use PrintWriter to send a string back to the ajax function:
PrintWriter out = response.getWriter();
out.println("test");
... I then wanted to output the text "test" in an alert-message:
$.ajax({
url: url,
type: "get",
data: {
latitude: location.lat(),
longitude: location.lng(),
radius: 10
},
success: function(response) {
alert(response);
},
error: function() {
alert("Ein Fehler beim Abfragen der Daten ist aufgetreten.");
}
});
But instead of outputting an alert-message with content "test", the output consists of the whole html code of the JSP-Page from which the ajax-call had been sent!
Nothing gets sent to the "screen" specifically, it is all about where the request originates.
If you click on a link, the browser initiates the request, and the browser receives response and processes the output to display.
In this case, the request will originate from your ajax call, and therefore the ajax call will process the request and the content will be received in the .requestText property of the response.
You'll probably want to make sure the response content type of the HttpServletResponse object is set to "text/html", But since you're going so far as to use ajax, you might as well consider a step into using JSON as well.

Ajax post call to a rest service through servlet

I have a little problem:
I'm developing a jQuery Mobile app and i need to make an ajax post call to a rest service.
I create the pages dynamically using servlets.
I tried to make the ajax call to the rest url:
http://localhost:8181/myRestServicePath/func?key=value
from a page whit the following url:
http://localhost:8080/Mypage
but i get a cross-orign error from the browser.
So i'm tryng to perform this call, passing through a Java servlet using the doPost() method.
Now, my intent is to make an ajax post call from
http://localhost:8080/Mypage
to:
http://localhost:8080/myServletPath/func?key=value
and this servlet should redirect the POST request to my RestService:
http://localhost:8181/myRestServicePath/func?key=value
How can i perform this redirection?
There could be several ways to achieve that. I am just sharing 2 commons possibilities as below.
For POST requests:-
You will need to use Apache HTTPClient in your servlet to send the request to web services and get a response. After getting the response you can send that response to your page.
For GET Requests:-
You don't need extra servlet for cross domain request. You can use JSONP
jQuery example:
$.ajax({
url:"http://localhost:8080/myServletPath/func?key=value",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
},
});
For back end example visit Java J2EE Tutorial for Cross Domain JSONP

send data from servlet java to jsp

I'm doing a project in java in which I implemented a chat, everything works perfectly only when I receive messages I can not print the web page.
In my Servlet I have a callback method that is invoked when messages arrive, in fact if you see mold them in the console, but if you are sending them to the jsp using the RequestDispatcher can not get them to see.
I would like to know if there is a system that the jsp page listens for a callback method in the servlet?
Obviously, this system should not be constantly invoke the class I have something absurd like that.
So that I can print the messages I receive.
This is my code I put a comment where I should print eventually find in jsp page, or do a redirect by passing parameters post or get
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String strJid = (String) request.getParameter("jid");
String strMessage = (String) request.getParameter("textMessage");
Connection connection = (Connection)getServletContext().getAttribute("classConnection");
ChatManager chatManager = connection.getChatManager();
Chat newChat = chatManager.createChat(strJid, new MessageListener(){
#Override
public void processMessage(Chat chat, Message message){
//from here I have to print the message.getBody () in jsp page,
//how can I do? I'm happy also reload the page and pass as a parameter to get or post
}
});
try{
newChat.sendMessage(strMessage);
}
catch(XMPPException e){
System.out.println("Errore invio messaggio");
}
}
To implement a callback method in your servlet to receive chat messages is the wrong approach. A servlet will be called once for a browser request, creates the HTML page and send it back to the browser. After that there is no such kind of a connection between the servlet and the web page.
In traditional web programming all communication between browser and server is intiated by the client. There is no way for the server to send a message to the client. Workarounds are long polling requests.
But nowadays you can use Websockets. There are several frameworks supporting Websockets both for client and server side. One of them is Atmosphere. Their tutorial is a chat application.

JSON / JSP Processing - Success function, how to return data not stored in a file

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.

Categories

Resources