简体   繁体   中英

Jquery and servlet communication with ajax

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?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM