How to call servlet from javascript

2020-06-23 09:56发布

问题:

Servlet Configuration in web.xml

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>DataEntry</servlet-name>
    <servlet-class>com.ctn.origin.connection.DataEntry</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>DataEntry</servlet-name>
    <url-pattern>/dataentry</url-pattern>
  </servlet-mapping>

Javascript :

<script type="text/javascript">
    function unloadEvt() {

        document.location.href='/test/dataentry';

    }
</script>

But using this javascript can't call my servlet.

Is there any error ? how to call servlet ?

回答1:

From your original question:

document.location.href="/dataentry";

The leading slash / in the URL will take you to the domain root.

So if the JSP page containing the script is running on

http://localhost:8080/contextname/page.jsp

then your location URL will point to

http://localhost:8080/dataentry

But you actually need

http://localhost:8080/contextname/dataentry

So, fix the URL accordingly

document.location.href = 'dataentry';
// Or
document.location.href = '/contextname/dataentry';
// Or
document.location.href = '${pageContext.request.contextPath}/dataentry';

Apart from that, the function name unloadEvt() suggests that you're invoking the function during onunload or onbeforeunload. If this is true, then you should look for another solution. The request is not guaranteed to ever reach the server. This depends on among others the browser used. How to solve it properly depends on the sole functional requirement which is not clear from the question.



回答2:

You can try this if you are using jQuery. It's simple:

<script>
    $(window).unload(function() {
        document.location.href='/test/dataentry';
    });
</script>


回答3:

This can be done using ajax

<script type="text/javascript">
    function loadXMLDoc() {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "/testmail/dataentry", true);
        xmlhttp.send();
    }
</script>