Javascript to Java Web Application -
i'm trying simple web project in eclipse, i'm new bare me. goal have .jsp/html file presentation layer, javascript handle logic, , java handle server side stuff. simple test, want able javascript code contact web server , have java code return date. here have right (note i'm displaying "trouble" parts)
.jsp (timer.jsp):
<div ><h2 id="date" class="main"></h2></div>
javascript (timer.js):
var xhr = new xmlhttprequest(); document.getelementbyid("date").innerhtml = xhr.responsetext; xhr.open("get", "cooptimer", true); xhr.send();
java:
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub dateformat dateformat = new simpledateformat("yyyy/mm/dd hh:mm:ss"); date date = new date(); request.setattribute("date", dateformat.format(date).tostring()); request.getrequestdispatcher("/timer.jsp").forward(request, response); }
the javascript sure wrong , trouble area. essentially, goal have header id "date" date javascript, , javascript value java servlet.
if can point me in right direction, whether it's resources, have you, terrific. thank you!
edit: here final code used. after hours of trying figure out wrong...nothing mentioned in eclipse right clicking html , run on server. humiliating mistake, 1 won't ever forget again.
here code used return simple date string:
.jsp (timer.jsp):
<div ><h2 id="date" class="main"></h2></div>
javascript (timer.js)
$("#date").load("http://127.0.0.1:14949/cooptimer/cooptimer");
java:
/** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub dateformat dateformat = new simpledateformat("yyyy/mm/dd hh:mm:ss"); date date = new date(); response.setcontenttype("text/plain"); response.setcharacterencoding("utf-8"); response.getwriter().write(date.tostring()); //system.out.println("ping"); }
there @ least 2 problems.
first: result of servlet rendered timer.jsp. , timer.jsp doesn't date stored in request servlet. if want servlet return formatted date, don't need forward jsp. write date response's writer.
second: javascript code tries change innerhtml of header content of response before sending request. can't work. advice, make js code easier write , understand , portable between browsers, use jquery , ajax functions:
$('#date').load('cooptimer');
Comments
Post a Comment