0

I am trying to call a serlvet from javascript. Code below:

document.location.href="service1servlet";

It perfectly delegates call to the servlet but with an error as:

HTTP Status 405 - HTTP method GET is not supported by this URL

I guess its looking for doGet method in servlet. How do I make it call doPost method in that servlet? Servlet doPost method below:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("THIS IS IN SERVICE!SERVLET AND CAN CHANGE DATABASE");   
}
Harsh Vardhan
  • 83
  • 1
  • 3
  • 7

3 Answers3

0

Using document.location.href it's not possible to send a POST request.

similar Question

Community
  • 1
  • 1
rupesh_padhye
  • 1,305
  • 2
  • 12
  • 23
0

Is there any reason why your servlet should support only POST method? If there's none, I suggest you stick with GET method.

Anyway, you can always call doPost in your doGet method.

Define a doGet method such as the ff. example:

public void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
    doPost(request, response);
}

Or if you really need to support only POST method, then the Javascript function you mentioned won't work. POST requests can be done through form submission.

Ish
  • 3,460
  • 1
  • 14
  • 20
0

You can do it by using Ajax or by using jQuery.This is the jQuery code to call servlet mapped with url pattern of /yourServlet.

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $.post('yourServlet', function(data) {
        alert(data);
    });
</script>

I would recommend you to go through this

Community
  • 1
  • 1
Prince
  • 2,577
  • 2
  • 12
  • 31