1

this might seem like a naive question but I'm fairly new to Java servlets and tomcat. I'm trying to call a servlet method by .post method in my javascript file. javascript is used in a .jsp file. everything works fine as long as the servlet is in the same directory with the jsp but when I change the path for file I can't get it to work no matter what I do. I tried these:

    $.post("./classes/myServlets/WEB-INF/order", $.param(data), function(response) {
    document.getElementById("Table").innerHTML = "Considered table number  " + response + "  for you";
});

or

    $.post("/classes/myServlets/WEB-INF/order", $.param(data), function(response) {
    document.getElementById("Table").innerHTML = "Considered table number  " + response + "  for you";
});

or

    $.post("order", $.param(data), function(response) {
    document.getElementById("Table").innerHTML = "Considered table number  " + response + "  for you";
});

or

    $.post("/classes/myServlets/WEB-INF/order.java", $.param(data), function(response) {
    document.getElementById("Table").innerHTML = "Considered table number  " + response + "  for you";
});

I know this must be very easy but I can't find the instructions anywhere. thank's in advance.

1 Answer 1

3

Your servlet while defined in a .java file and compiled into a class that is stored in your WEB-INF folder, will need to be mapped to a URL (usually in your web.xml). It would not be easy to answer this without more information about what servlet container and framework you are using, but assuming you were just using pure Tomcat (without any framework like Spring) you might look at your web.xml file for something like this:

<servlet>
    <servlet-name>com.project.Order</servlet-name>
    <servlet-class>com.project.Order</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>com.project.Order</servlet-name>
    <url-pattern>/order</url-pattern>
</servlet-mapping>

With this URL mapped you can then send HTTP POST request with some jQuery like this:

$.post("/order", $.param(data), function(response) {
  document.getElementById("Table").innerHTML = "Considered table number  " + response + "  for you";
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. I am using pure tomcat and I am trying this right. doesn't @WebServlet("order") do the same thing?
It should, though I would add a / and given that you are deploying this as a web app called myServlets that would make the absolute path (for your ajax request) /myServlets/order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.