如何从javascript函数调用servlet doPost方法?

时间:2015-10-10 15:43:19

标签: javascript servlets

我试图从javascript调用一个serlvet。代码如下:

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");   
}

3 个答案:

答案 0 :(得分:0)

使用document.location.href无法发送POST请求。

similar Question

答案 1 :(得分:0)

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

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

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

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

或者如果你真的只需要支持POST方法,那么你提到的Javascript函数将无效。 POST请求可以通过表单提交完成。

答案 2 :(得分:0)

您可以使用Ajax或使用jQuery来实现。这是用于调用与/yourServlet的url模式映射的servlet的jQuery代码。

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

我建议你仔细阅读

相关问题