4

I want to establish a communication between a Jquery function and a servlet in tomcat.

Servlet Code:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class Test extends HttpServlet {
public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }
    body = stringBuilder.toString();
    return body;
}
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        System.out.println(getBody(request));
        out.println("Success Call Ajax POST");

      }
    public void doGet( HttpServletRequest request, HttpServletResponse
        response ) throws ServletException, IOException{
    response.setContentType("text/html");
    response.setCharacterEncoding( "UTF-8" );
    PrintWriter out = response.getWriter();
    out.println("Get Method");

  }

}

The servlet identity is defined in web.xml

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
  <servlet>
    <servlet-name>Test</servlet-name>
    <servlet-class>com.servlets.Test</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/toto</url-pattern>
  </servlet-mapping>
</web-app>

And the following HTML contains the JQuery function:

Jquery code:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    function login(){  

      $.ajax({  
        type: "POST",  
        url: "http://localhost:8080/test/toto",  
        data: "POST Call",
        success: function(result){  
          alert("success call"+result);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
            alert("Status: " + textStatus); alert("Error: " + errorThrown); 
        }                 
      });  
    }        
    </script>
    <title>My AJAX</title>
</head>
<body>
    <button type="button" onclick="login()">Click Me!</button>
</body>

I tested the servlet with the browser, it's fine. When I tried the HTML/js app and I clicked in the button I got in the eclipse console the message displayed by the instruction System.out.println(getBody(request)); "POST Call" but I got in the browser the error alert. So ajax function call successfully the method post in the servlet but the servlet can't return successfully the response to the browser. It seems that there's a problem in the servlet. Can someone help me please?

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
Kallel Omar
  • 1,208
  • 2
  • 17
  • 51
  • If it is showing 'POST Call' , there might be issues in `data: "POST Call",` in ajax.. Also check network tab for response and header, if you are using chrome browser. – Arun May 18 '15 at 11:07
  • I tried with firefox and chrome and I got the same error alert. But in chrome I got also this error message when I click in the button: XMLHttpRequest cannot load http://localhost:8080/test/toto. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. – Kallel Omar May 18 '15 at 11:11
  • are you loading the servlet using an iframe?\ – MaVRoSCy May 18 '15 at 11:13
  • No I don't use the iframe load – Kallel Omar May 18 '15 at 11:16
  • I just simulated your code in a Web Application and works fine!!! The only thing that could be wrong is the application name.... Are you sure you can access `http://localhost:8080/test/` ? Is this the root of your application? – MaVRoSCy May 18 '15 at 11:26
  • You are making a cross origin request. You should probably look into this link for further detals http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ – Arun May 18 '15 at 11:26
  • @MaVRoSCy: yes the servlet app is working fine without any problem. – Kallel Omar May 18 '15 at 11:29
  • 1
    In the `doPost()` try adding the request header : `response.setContentType("text/html"); response.setHeader("Access-Control-Allow-Origin", "*");` does it make any difference? – MaVRoSCy May 18 '15 at 11:35
  • @MaVRoSCy: your suggestion saved me – Kallel Omar May 18 '15 at 11:39
  • ok i will add it as an answer – MaVRoSCy May 18 '15 at 11:47

2 Answers2

2

In the doPost() try adding the request header :

response.setContentType("text/html"); 
response.setHeader("Access-Control-Allow-Origin", "*"); 

I am certain that this has to do with the Allow Origin problem described here

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
0

It is browser specific.

Its works fine on Safari 8.0.3, it throws error No 'Access-Control-Allow-Origin' header is present on Chrome and Firefox.

Look at console in Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/toto. This can be fixed by moving the resource to the same domain or enabling CORS.

It could be fixed by disabling web security in browser or as already mentioned:

response.setHeader("Access-Control-Allow-Origin", your_domain);

Navidot
  • 327
  • 3
  • 10