i’ve just started to learn Java, and I’ve a problem with creating a Java server.
On HTML, there should be a form, and JavaScript witch submits that form every second (By POST method). The form should have a hidden field, with the value of user ID. Server should look for a user id in the request. It should give new ID to the new users, and to the visited users, show their id.
After each form submit, the inscription changes to: null, 2, null, 2, null, 2…. here is the code:
public class ServerConnect extends AbstractHandler{
private AtomicInteger ids = new AtomicInteger(0);
private String userId;
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println(PageGenerator.generateForm(userId));
userId = request.getParameter("userId");
if (userId == null){
ids.getAndIncrement();
userId = ids.toString();
}
}
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
server.setHandler(new ServerConnect());
server.start();
server.join();
}
}
public class PageGenerator {
public static String generateForm(String val){
String htmlCode = null;
htmlCode = "...
<script>
function reload(){
document.forms['MainForm'].submit();
}
setTimeout("reload()", 1000);
</script>
.... + val + ...
<form id='MainForm' method = 'POST'>
<input type = "hidden" name = "userId" value = \""+ val + \"">
<form>
...
return htmlCode;
}
}
I can’t get why is user ID equals to 2, and why after user gets his id, it’s value changes to null, and then, to 2 again
It seems that you are rendering your page before the userId has been resolved. You have
PageGenerator.generateForm(userId)before you checkif(userId == null)Also, you should understand that
AtomicLong.getAndIncrement()is a compound operation, similar toi++(but is a single atomic operation).So you need to have code like the following:
Finally, I’m not certain about the lifecycle of the
AbstractHandlerbut it would be reasonable to assume that a new instance of your class is being instantiated by Jetty every other request. Asidsis scoped as a “instance” field, it is discarded (and thus effectively reset) with new requests.Edit answers on Jetty’s threading model here: Jetty Architecture
To fix this, you would need to declare
idsasstatic final(and thus effectively make it a “Singleton” ID generator) to have it survive multiple requests. An ok approach for a toy application, but not something you’d necessarily do in production code.