2015-10-10 57 views
0

我想从javascript调用serlvet。下面的代码:如何从javascript函数调用servlet doPost方法?

document.location.href="service1servlet"; 

它完美地代表打电话给servlet但有错误为:

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

我猜它希望在servlet的doGet方法。如何让它在该servlet中调用doPost方法? Servlet doPost方法如下:

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

回答

0

是否有任何理由为什么你的servlet应该只支持POST方法?如果没有,我建议你坚持使用GET方法。

无论如何,你总是可以在你的doGet方法中调用doPost。

定义一个doGet方法,如ff。例如:

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

或者如果您确实需要仅支持POST方法,那么您提到的Javascript函数将不起作用。 POST请求可以通过表单提交完成。

0

您可以通过使用Ajax或使用jQuery来完成此操作。这是调用servlet的jQuery代码,其url模式为/yourServlet

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

我会建议你去通过这个

相关问题