سؤال

The goal here is to have a servlet which has a button, when clicked creates a persistent Date() object outside of session memory i.e the variable value can be retrieved after closing the browser and accessing page.
Wondering what the best approach would be here?
I've considered a database or write to file.

Looking to have a label and button on screen, when button is clicked it creates a time stamp on server, label contains the 'time passed' since the button was clicked.
Essentially a duration, but the same value is visable to all users/sessions.
Once #timeStarted is loaded by a request, there will be some javascript to update the duration with setInterval(), this part is no problem.

"<label id=\"timeStarted\"> + getTimeStarted() + "</label>"

<form method="post" action="SomeServlet">  
    <input type="submit" value="Go"/>  
</form>

In SomeServlet declare the variable/persistent object:

Date timeStarted = new Date();
هل كانت مفيدة؟

المحلول 2

Decided to use some AJAX here,
Once the button was clicked it fired a xmlhttprequest to a servlet.
The servlet then created a file storing a Date() object value i.e long

When the page is loaded it retrieves the Date value from the file and displays on screen .. thus persistent storage.

نصائح أخرى

You can store it at the ApplicationContext level by using the getServletContext() method and storing it there. This would keep the time at the application level.

But remember, if you are running the application on multiple servers with load balancers, you may not be able to achieve this. Then you have to look for DB based solution. Otherwise, you can store it at the application context and retrieve for all the users.

In your doGet / doPost method,

ServletContext context = request.getServletContext();
context.setAttribute("clicktime", new Timestamp(System.currentTimeMillis()));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top