1

I'm trying to do a simple web project in eclipse. My goal is to have a .jsp/html file be a presentation layer, javascript to handle logic, and Java to handle server side stuff. For my simple test, I just want to be able for my javascript code to contact the web server and have the java code return a date. Here is what I have right now (note I'm only displaying the "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 I am sure is wrong and is probably the trouble area. So essentially, my goal is to have the header id "date" get a date from the javascript, and the javascript will get the value from the java servlet.

If anyone can point me in the right direction, whether it's resources, what have you, that would be terrific. Thank you!

EDIT: Here is the final code I used. After hours of trying to figure out what was wrong...nothing mentioned in eclipse about right clicking the HTML and Run As on server. A humiliating mistake, but one I won't ever forget again.

Here is the code I used to return a 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");
    }
2
  • I've added a tag for servlets. You should check out the documentation we have at SO: stackoverflow.com/tags/servlets/info Commented Apr 5, 2013 at 14:51
  • If you want to send an AJAX request, then you don't want to forward to a jsp, you need to write directly to the response outputstream (possibly json). Commented Apr 5, 2013 at 14:52

2 Answers 2

1

There are at least two problems.

First: the result of the servlet is what is rendered by Timer.jsp. And Timer.jsp doesn't do anything with the date stored in the request by the servlet. If you just want the servlet to return a formatted date, you don't need to forward to a JSP. Just write the date to the response's writer.

Second: your JavaScript code tries to change the innerHTML of the header with the content of the response before even sending the request. This can't work. My advice, to make your JS code easier to write and understand and portable between browsers, is to use jQuery and its AJAX functions:

$('#date').load('CoopTimer');
Sign up to request clarification or add additional context in comments.

5 Comments

First: So instead of saying equest.getRequestDispatcher("/Timer.jsp").forward(request, response); I would figure out what is trying to make the request, and instead send the response to it? Second: I've been reading a lot about jQuery and much easier it makes things. Is there a way to use the HttpRequest() to get assign the value based on the response instead of what I'm doing? Or is this only possible with jQuery?
First: If the contratc of the URL is to return the current date, you just need to return the current date, without having to figure out what is trying to make the request. A request is a request, and the servlet should always do the same thing. Second: Of course it's possible without jQuery. jQuery doesn't have more power than any script you might write yourself. But it makes things so much easier and portable that not using it is shooting yourself in the foot.
When I'm doing the load, what address do I use? I'm having the same issue as when I was using the HTTPRequest.open, where it can't find the CoopTimer file. [WARNING ] SRVE0190E: File not found: /CoopTimer.java
You need to use the URL the servlet is mapped to. This should be covered by the most basic tutorial or book about servlets.
My Javascript will now successfully contact the server, however I don't believe the Java is not returning the string properly or my Javascript isn't receiving the value properly. When I test this out in eclipse and run the page, the Servlet address /CoopTimer will display the string. However if I go to my Timer.jsp, it does not display the string. Instead it displays Object Object.
0

Use jquery to make ajax call which is very simple in it self . Here is the javascript code snippet

function pullResultFromServlet() {
  var url = 'servletURL';
  $.ajax({
    url: url,
    dataType: 'json',
    data:{
      "dateValue: $('#date').val(),
    },
    type: 'POST',
    success: function(responseFromServlet) {
      // further processing
      }


    },
    error: function(jqXHR, textStatus, errorThrown) {
    }
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.