How to call a servlet from javascript

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 cannot call my servlet.

Is there a mistake? how to call a servlet?

+3
source share
3 answers

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>
0
source

From your original question:

document.location.href="/dataentry";

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

So, if the JSP page containing the script is running on

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

then your URL locationwill point to

http: // localhost: 8080 / dataentry

But you really need

http: // localhost: 8080 / contextname / dataentry

So correct the url accordingly

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

, unloadEvt() , onunload onbeforeunload. , . , - . , , . , , .

+14

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

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

All Articles