Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call 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 can't call my servlet.

Is there any error ? how to call servlet ?

like image 788
chetan Avatar asked Dec 04 '22 21:12

chetan


1 Answers

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.

like image 192
BalusC Avatar answered Dec 27 '22 13:12

BalusC