0

I am learning working with Servlets and JavaScript, by trying to build an application where a Java servlet and a JavaScript code can exchange data. I have built a simple WebPage with an Header and a button. Upon Clicking the button, the client should send an AJAX request to the server, and the Server should send some data as a response, that should alter the text on the Header accordingly. I am using jQuery to send and receive the data, and alter the text on the Header. Here is the HTML code :

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>$(function() { alert('hello') });</script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="Try.js"></script>
</head>
<body>
    <h1 align = "center" id="header">Using Visual Studio</h1>
    <button id="button">Click</button>

</body>
</html>

This is the Try.js JavaScript code with jQuery :

$(function(){
   $("button").click(function(){
        $.ajax({url: "localhost:8080/Ajax/Serv", success: function(result){
                $("#header").html(result);
    }});

  });
});

And following is the servlet code:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdk.nashorn.internal.parser.JSONParser;

@WebServlet("/Serv")
public class Serv extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Serv() {
        super();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().write("Success Data!!!");
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

The webpage Header should display "Success Data!!!" on Clicking the button "Click". However that is not happening. I am using TomCat 7.0.39 on port 8080 for the server.

SomeCoder
  • 95
  • 1
  • 7
  • Does your server receive the AJAX request? Does your Javascript receive the response? Do you see an error message in the debugger console of your web browser? Can you see the request and response in the network tab of your debugger? If your Ajax URL starts with hostname and port it might be necessary to prefix it with "http://". – Stefan Apr 18 '20 at 14:32
  • Yes it is receiving the AJAX request. Also I prefixed it with "http://" but to no avail. Also I am receiving this error in Browser Console - "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/Ajax/Serv. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)." – SomeCoder Apr 18 '20 at 14:36
  • Hi @AnAmateur, Can you check the developer console > Network tab in your browser and see what is the response from the request? – Runcorn Apr 18 '20 at 14:40
  • @Runcorn I am receiving 142B of response, with these response headers :Content-Length 15 Content-Type text/html;charset=UTF-8 Date Sat, 18 Apr 2020 14:39:28 GMT Server Apache-Coyote/1.1 – SomeCoder Apr 18 '20 at 14:44
  • Hi @AnAmateur and what does the body contains(Check the response tab in the Network menu after clicking the request)? Can you console.log(result) in the JavaScript and check the response? – Runcorn Apr 18 '20 at 14:49

2 Answers2

1

It appears you are loading the html page from your file system (e.g. file:///C:/Ajax/serv.html) and not the localhost (e.g. http://localhost:8080/Ajax/serv.html). That's why you're getting the Cross Origin Request Blocked error when attempting the Ajax call, this is a Cross-site Scripting (XSS) security vulnerability that your browser is preventing.

You should move your html (js, etc) file under a new Tomcat webapps folder, such as webapps/Ajax) and load them using http://localhost:8080/Ajax/serv.html. This will prevent the XSS problem.

Also adding an error handler to the Ajax call will help determine the problem.

 $("button").click(function(){
    $.ajax({url: "localhost:8080/Ajax/Serv",
     success: function(result){
            $("#header").html(result);
     },
     error: function(xhr, status, ex) {
        alert("state=" + xhr.state() + ", status=" + status);
     }
});
Steve M
  • 181
  • 3
1

One common reason for the HTML/JSP page not being able to hit the servlet is when servlet has not been deployed. A simple way to test this scenario is to create a dynamic web project with an HTML/JSP page and a servlet in eclipse ▸ Right-click the ⁩HTML/JSP page ▸ Run As ▸ Run On Server

It will serve the HTML/JSP page from the server. However, you try to hit the servlet in the browser, it will show 404 error because the servlet has not been deployed.

Now, stop the server ▸ Right-click the servlet ▸ Run As ▸ Run On Server

You will see that the servlet is accessible this time. If a button (or other control), which has this servlet as the action, is clicked, the response from the server can be seen.

I have shown the screenshot with the structure of my web project. I tried your code and I was able to get the expected result without any issue.

enter image description here

halfer
  • 19,824
  • 17
  • 99
  • 186
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110