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.
Related
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).
I'm working on a project where we use Tomcat 8 as a application server and hence JSP and Servlets. Each JSP displays a kind of project list. The user of the application has the possibilty to simulate a project. What this means is not that important. When the user clicks the 'simulate'-button, the following process will be performed:
Via Ajax (javascript) a servlet will be executed which produces a zip file and stores the file on the hard disk of the server
a 'simulation'-flag will be set in the database for the respective project
a external java program (at the backend) listens for the 'simulation'-flag and if a flag for a project is set, the external program grabs the zip file stored by the web application
the external java program then runs the simulation for this project.
when the simulation is done, the external java program stores a new zip file on the hard disk of the server, sets a 'hey, I'm ready'-flag in the database and calls a servlet of the web application
this servlet saves the information of the data in the new zip file to the database
finish
So my question is: What is the best way to inform the JSP that the simulation is done?
The JSP still displays that the project is in simulation progress. My current idea is the following:
I could periodically send a Ajax request to the server to check the database for the 'hey I'm ready'-flag and if it is set, I could display the result on the JSP. But I've got the feeling that there are smarter solutions.
Maybe I could use the last servlet call (see point 5) to somehow inform the JSP that the simulation is done? The problem is that this servlet is not called by the client but by the external java program.
Do you have any suggestions? Or is there any technology I should read about?
Thank you.
using asynchronous ajax calls means that the function will return when the servlet finishes it's job and returns some HTTP code (200 for success).
so this example:
$.ajax({
url: Config.serverUrl+'/simulationServlet',
type: 'GET',
success: function(result) {
$('#infoBox').text("simulation is over");
}
});
will show that the simulation is done.
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.
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.
Is it possible to embed html with java
test.html
<input id="buttonId" type="button" class="button-click"
value="" onClick="checkSucess(2)" onload="counts(count)">
test.js
checkSucess = function(firstVal) {
// Jquery Ajax with url,params and response
doPost('test.java',
'first=' + firstVal,
function(response) {
});
test.java
Here get the 'first' value from ajax request, and further processing.
I believe you're looking for JavaServer Pages (.jsp), a starting point for implementing server-side logic using Java. (You can GET/POST to a jsp.)
Reference
JSP + Ajax Example
JavaServer Pages Technology
JSP Tutorial
Well, Java on the server side doesn't work quite like PHP. i.e. you can't simply drop your java files in your htdocs directory and trigger it by filename directly. Firstly you'll need an app server like tomcat or jetty (instead of just a webserver like apache httpd). Secondly, you'll need to create a Servlet (simplest case) and write your java code there and trigger it using the server request url. Google "servlets" and you should be able to pick it from there..
No, you can't do like that, you have to use AJAX request to interact with java from your html or javascript. For that you have to use servlet and pass the servlet URL to doPost function.
doPost('url to servlet',
'first=' + firstVal,
function(response) {
});
Since this is your first java project, you should do some reading to come up to speed with java. Here are some good tutorials:
Core Servlets, Intermediate Servlets
Apache Tomcat 6 - Apache is a nice tool for learning servlets; it is easy to install and run.
Core Servlets; Advanced Servlets - This may be more than you need.
Applets are Java, and the only (usual) way for Java in the browser.
You can communicate with Applets from Javascript/JQuery code. Applets have ending .class (.java is source code, you can't communicate with it).
In the case you want to communicate with serverside Java, you need servlets there. Then send requests to the url of the servlets.
No. Besides using Java Applets - which are actually just plugins - there is no way to embed Java into HTML.
That being said, It is possible to generate HTML using Java Server Pages.
It is also possible to use an HTML page in conjunction with JavaScript to interact with Java via subsequent HTTP Requests made using AJAX. These requests are initiated on the client browser, and received and fulfilled by a server capable of executing Java Server Pages (JPS).
Example:
An HTML page is loadad with some JavaScript that requests some url upon completion of DOM loading.
The request is received by some server which then responds to the request.
The client browser receives the response and provides it to JavaScript to be dealt with.
JavaScript reads the response, and uses it in some way (like "refreshing" some information on the page).