将JSON传递给Servlet

时间:2014-07-07 13:38:10

标签: java ajax servlets http-post

当我尝试将JSON传递给这个Servlet的doPost()方法时,我得到一个" 405方法不允许" Chrome中的错误:

@Path("/users")
public class UserServlet extends BaseServlet {
   private static final long serialVersionUID = 1L;
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException {
      System.out.println("DO POST");
   }
}

此代码正在传递JSON对象:

$scope.login = function() {
    console.log("try login");
    $.ajax({
        type: "POST",
        url: "api/users",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify($scope.loggedInUser)
    });
};

单击按钮时会调用此代码:

<button type="submit" class="btn btn-success" ng-click="login()">Login</button>

这是Chrome打印出来的消息:

Remote Address:::1:9797
Request URL:http://localhost:9797/api/users
Request Method:POST
Status Code:405 Method Not Allowed
Request Headers
   Accept:application/json, text/javascript, */*; q=0.01
   Accept-Encoding:gzip,deflate,sdch
   Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
   Connection:keep-alive
   Content-Length:29
   Content-Type:application/json
   Cookie:__ngDebug=true
   Host:localhost:9797
   Origin:http://localhost:9797
   Referer:http://localhost:9797/
   User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
   X-Requested-With:XMLHttpRequest
Request Payload
   {name:test1, pwd:test}
      name: "test1"
      pwd: "test"
Response Headers
   Allow:OPTIONS
   Content-Length:0
   Server:Jetty(9.1.3.v20140225)
如果有人可以帮助我,我会很高兴。提前谢谢!

0 个答案:

没有答案