1

i'm using XMLHttpRequest to send a variable from the js file to java file in the same project.

My problem and my question is: how i know my URL ? Here is my code from js file

xhttp = new XMLHttpRequest();
    var handlerFunction = getReadyStateHandler(xhttp, getValue);
    xhttp.onreadystatechange = handlerFunction;
    xhttp.open("POST",/* Location of my java file */,true);
    xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhttp.send(identMsg);


    function getValue (body) {
        var valueBody = body.getElementByTagName("body")[0];
    }

    function getReadyStateHandler(xhttp, responseXmlHandler) {
        return function(){
            if (xhttp.readyState == 4) {
                if(xhttp.status == 200) {
                    responseXmlHandler(xhttp.responseXML);
                } else {alert("Http error: " +xhttp.status);}
            }
        }
    }

and the java code

public void doPost (HttpServletRequest xhttp, HttpServletResponse res) throws IOException {
     String body = null;
     StringBuilder stringBuilder = new StringBuilder();
     BufferedReader bufferedReader = null;

     try {
        InputStream inputStream = xhttp.getInputStream();
        if (inputStream != null) {
            bufferedReader = xhttp.getReader();
            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 ex2){
            throw ex2;
        }
      }
    }

     body = stringBuilder.toString();
     res.setContentType("application/xml");      
     res.getWriter().write(body);
}

what is missing?

EDIT: I need to get URL in the js side.

John John
  • 33
  • 8
  • The path where the file exists on the webserver? – epascarello Feb 10 '17 at 16:13
  • Possible duplicate of [How to get only part of URL from HttpServletRequest?](http://stackoverflow.com/questions/14065257/how-to-get-only-part-of-url-from-httpservletrequest) – Andremoniy Feb 10 '17 at 16:13

1 Answers1

0

You can have the URL in js with document.location.href

TheMMSH
  • 501
  • 6
  • 26