Dynamically update JSP page via Servlet - java

I am new to web programming with Java. I have a Client/Server written (in Java) and I want updates from the Client to be sent from the Server to a web interface for a user to view. The timing of the updates will be random, but I want to be able to dynamically update a web page with new data without the browser having to refresh.
Hope this makes sense:
I've tried creating a Servlet that Observes (implements Observer) my Server (which extends Observable) for updates (Strings), however I don't know how to dynamically add these to a browser window. I have tried printing directly from the Servlet using PrintWriter out = response.getWriter(); in the doGet() method, but response.getWriter() is unavailable in the Servlet's update() method.
My initial thoughts were to use a JSP page (I need to eventually incorporate HTML/CSS) that receives the Observer updates from the Server but I'm not sure.
I've done some research into Comet/PUSH, but I'm not sure if this is what I need - perhaps a bit overkill? Any advice on how to achieve what I'm after would be greatly appreciated.

The most common way to do this is for the client to poll the server for changes. Use an AJAX request on the client side to poll an endpoint on your server.
You will then need to use JQuery / Javascript to update your web page with the new data retrieved from the AJAX request.
I would suggest using JQuery in theb rowser and using the AJAX function: http://api.jquery.com/jQuery.ajax/
It allows you to do a callback after the request and in that call back you can update the content of your web page with the data retrieved from the request.

You cannot update a web page from server, not without recurring to polling or push.
If you want a true push, then comet is not overkill, otherwise you can use a polling script on the web page.

Related

How to do a SPA using servlets and jsp?

I'm trying to do a single page application using servlets and jsp pages.
For the moment I have the first page, which is simple to do: a servlet that forwards to the corresponding jsp.
How should the implementation look when navigating to the second page?
I guess it should be an ajax call, the servlet would populate the necessary data, but how to display the second page jsp?
JSP is a server side ui technology. A Servlet listens to specific urls and redirects to JSPs pages. The JSP is compiled to a class (another servlet in fact), invoked (data will be added and inline scripts will run) and the output, whith is HTML, is send to the client (browser). To get to a different page its neccessary to query the server (servlet) for another url, resulting in another html page.
To create an SPA you need a client side technology like JavaScript. Your query the server for a single html page. The page, made of HTML and JavaScript, for example, (could even be the output of a single JSP, dont get confused) is send to the client (browser) and the JS is run. This is nomaly backed up by a framework like AngularJS, EmberJS or Backbone. Once the page is set up, the links within the page are anchors (http://example.com/#/mySecondPage), so clicking them will invoke the framework again (Ajax, querying the server for new data), but will stay on the same page. Some contents of the page might then be replaced by new content.
If it is a true SPA then you would just have a single JSP and handle all your functionality (after your initial page load) using Ajax.
Have you looked at using a client-side framework such as Angular to help you with this?
Depending on how rich your SPA is, you could either use the same servlet or multiple servlets to serve each page.
Unless you are doing this for a course or tutorial and have some constraints on how to achieve it, you will very probably save yourself a lot of time if you couple something like Angular with a server-side framework like Spring instead of coding servlets. As a suggestion have a look at Spring with Angular.
In SPA the browser only loads the document once (or a few, once per sub-application), and further communication to the server is done usually via AJAX or Websockets.
I recommend you to model your application as a thin server architecture, that is, a client application running in the browser (HTML, CSS, Javascript) consuming a web service API provided by the server.
The following are some points worth knowing;
Client-side:
Only presentation logic
Represent state by URL hash. This enables bookmarking, hyperlinking and browsing history. Your client app should listen to changes in the URL hash and act in consequence. This technique is called "routing" and it is implemented by all Javascript frameworks.
Client application is packaged server-side such it can be downloaded in a single request (in .html, .jsp, servlet, .jsp + multiple .jspf, ...)
Consumes services provided by the server via AJAX or Websockets
Server:
Offers client application to download
Provides a clean, stateless API to be consumed by the client application, better returning JSON (data) than HTML (presentation logic) (Why is it a bad practice to return generated HTML instead of JSON? Or is it?)
Use a REST or JSON-RPC frameworks to create the API. There is a lot of debate on what to choose (see here or here). In my opinion the only advantage of REST over RPC is that since REST has become a "de facto" standard its interoperability is higher, so my recommendation for SPA applications is using JSON-RPC, because your code is the only client of the API.
There are lots of alternatives for both client and server frameworks.
Javascript: AngularJS, EmberJS or Backbone,...
REST: Spring, Jersey, Restlet,..
JSON-RPC: https://en.wikipedia.org/wiki/JSON-RPC#Implementations
Regarding JSON-RPC, you might want to take a look to Brutusin-RPC, a JEE microframework I have created :)
If you are using an Ajax request, then you need to tell the browser that redirect to the second page. Example:
response.sendRedirect("second_page.jsp");
In your servlet, you need to differentiate a request to the first page, from a request that need to be redirected to the second page. You can use parameters, or session values, for example.
if (request.getParameter("page2") != null) {
response.sendRedirect("second_page.jsp");
} else {
.... // include here the normal logic of your Servlet for page 1
}
Then, you can invoke your servlet with or wihout the parameter page2, to go to page 1 (without parameter), or page 2 (with parameter).

Is it a good practice to use JSTL inside a script (javascript) tag?

I'm developing a web app using JSTL and Javascript in Eclipse Juno. I've been reading questions like How to set the JSTL variable value in javascript? and my code works good even if I have error in eclipse:
But... Is it a good practice to use JSTL and Javascript like this?
Does it cause a low performance in the time of rendering the webpage?
Can this be done in other way?
Is it a good practice to use JSTL and Javascript like this?
It is not bad practice or good practice. The bad practice would be using JSTL to control the flow of JavaScript, which is plain wrong because JSTL runs on server side and JavaScript on client side.
Does it cause a low performance in the time of rendering the webpage?
JSTL will only help to generate the HTML for the current view. JavaScript is not involved in the HTML generation at server side but at client side unless you work with nodejs or similar technologies.
Can this be done in other way?
This depends on what you're doing. Common way to access to data when accessing to a web page:
Application Server (AS) receives a GET request on http://www.foo.com/bar
AS pre process the GET request (load data from database or another data source, pre calculations, etc)
AS creates the response for the GET request (apply the data to generate the HTML)
AS sends the response to the client.
The browser client renders the HTML.
Another way to do it:
Application Server (AS) receives a GET request on http://www.foo.com/bar
AS creates the response for the GET request (generate the HTML which contains JavaScript functions to load the data in the onload event).
AS sends the response to the client.
The browser client renders the HTML.
The onload event fires and load data in the onload event through RESTful services. This way, the data interaction is handled in client side only, but the data comes from server side.
These are two very simple alternatives to handle the same problem. Which one to choose and work with will depend entirely on your design, there's no definitive answer.

Loading resources before running java code in servlet

I have a servlet in tomcat. It takes a really long time for the java code in the backend to execute. Is there a way to load static resources (css,images,javascript) in parallel with the code in the backend? Right now, they are only loaded once the code finishes running.
You could use an Ajax-style solution where you paint your page without data, with a placeholder for retrieving the data, maybe even with a "loading" spinner graphic.
The way that an Ajax call works, when the page is loaded, some Javascript will fire that will launch an Ajax request to Tomcat via XmlHttpRequest that will start the calculation. The browser will notify the browser when the tomcat request is completed. Then there will be some javascript in the webpage that will take the response and replace the placeholder. If the server returns an HTML fragment, it's as simple as executing in javascript placeholder-div.innerHtml = your-response-text.
Here's a basic tutorial on Ajax and a Java-based example that has the web front-end communicating with a Java Servlet back-end.

Send data to front end when back end updates [duplicate]

This question already has answers here:
Real time updates from database using JSF/Java EE
(3 answers)
Closed 2 years ago.
The backend of my web application receives updates from several clients. When such an update happens it should be communicated to all other clients.
How can I initiate an update from the server to all web browser clients when my backend is updated?
I'm using JBoss, JSF and the Spring framework.
See similar Stack overflow quetion : WebSockets vs. Server-Sent events/EventSource
I'm assuming, as DarthVader did, that your frontend is a (generally) stateless HTML page of some sort. Something in a browser. If you want all clients to be pushed changes automatically, you have three options:
Comet: (deprecated)
Comet is essentially making AJAX requests that have no request timeout limit. You make the request, and it sits there and streams data through it as is neccessary. This can be done with hidden iFrames or standard XMLHTTPRequests (which jQuery can wrap for you). You can read more about this method here.
Long Polling:
Essentially, you use the javascript setInterval method to continuously poll your server for changes. Simply set an interval that does a standard AJAX GET request to the server, and upon every success, update your page accordingly.
Browser APIs
HTML5 WebSockets
Using any type of Event-Based backend (Twisted, EventMachine, node.js, etc) makes WebSockets the ideal solution. Simply have all clients register with the backend, and upon a submit from any given client, push the changes to all other clients. You can read more (and see a nice example) of WebSockets on this page. Browser support => canIuse
Server-sent event (SSE)
With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page.
Browser suppport => canIuse
When you say front end, you are talking about stateless http client.
You cant push anything from your web servers to http or stateless clients.
The "trick" to do this if using asynchronous calls from front end to your back end, periodically.
Think about gmail, how do you think it displays that you have an email when you recieve a new email. You browser contantly, sending Asynch calls to gmail servers, if and when there is a new message, it displays it.
So Clients are stateless. use Ajax.
is this clear?
There are a couple of ways to go around this.. The way it should be in the future is following standards like Websockets
For now you are stuck with Comet which is essentially sending a request to the server and keeping it open (not signaling a response end) and just streaming data through it (Parking the request they call it). Or periodic polling, where you just do an AJAX request to the server every predefined interval to ask if the server has something new to say. Needless to say the first work around requires streaming support on both the server and browser but is more efficient in most scenarios.

How to call a JavaScript function in the HTTP response?

I'm implementing a web server. I have a chat application on it. When I publish a new message, an HTTP request is generated, it calls the right method in the server (Java), and get a response from the server, includes in its content the new HTML code of the chat page.
I don't want to refresh the whole page, so I want to call a JavaScript function that will inject the new message to the right div.
How can I do that?
Thanks,
Tomer
I think it's better/simpler to use something like jQuery's ajax load.

Categories

Resources