无法获得角$ http工作

问题描述:

我想获得一个简单的angularjs登录屏幕工作。 角度应用程序通过http get方法将登录详细信息发送到java servlet,并预期成功/失败的json响应。 Java servlet在Tomcat 8.0上运行。

不幸的是,角应用似乎不能够从servlet接收数据(它发送该数据到servlet) - “则”被称为每次的errorCallback方法。

此外,直接从浏览器访问servlet的url可以正常工作(浏览器显示响应字符串)。

你能帮我找到问题吗?

这是在HTML页面的div元素:

 <div ng-controller = "loginCtrl"> 
    <input type="text" ng-model = "userName" placeholder="Username"></input><br> 
    <input type = "text" ng-model = "userPass" placeholder="Password"></input><br> 
    <button type = "button" ng-click = "login()">Login</button><br> 

    {{message}} 
</div> 

这是js代码:

var expenseApp = angular.module("expenseApp",[]); 

expenseApp.controller('loginCtrl',['$scope','$http',function($scope,$http) { 
    $scope.userName = ""; 
    $scope.userPass = ""; 
    $scope.message = "type in your credentials"; 
    $scope.login = function() { 
     var address = "http://localhost:8080/ExpenseSystemServer/LoginServlet?userName=" + $scope.userName + "&userPass=" + $scope.userPass; 
     $http({method:'get', 
     url:address}) 
     .then(function(data, status, headers, config) { 
       $scope.message = "http success"; 
       }, 
       function(data, status, headers, config) { 
        $scope.message = "http error"; 
       }); 
    }; 
}]); 

而且这是在Java servlet的doGet方法(servlet的类名是LoginServlet ):

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     response.setContentType("application/json"); 
     response.setCharacterEncoding("UTF-8"); 

     String userName = request.getParameter("userName"); 
     String userPass = request.getParameter("userPass"); 
     System.out.print("Login attempt with " + userName + "; " + userPass + ": "); 
     if (userName == null || userPass == null || !userName.equals("admin") || !userPass.equals("pass")){ 
      response.getWriter().write("{'success':false,'message':'wrong details'}"); 
      System.out.println("failed."); 
     } 
     else { 
      response.getWriter().write("{'success':true, 'user':{'name':'admin'},'message':'Hi admin!'}"); 
      System.out.println("succeeded."); 
     } 

    } 

你能帮我吗?

谢谢。

您从servlet发送无效的JSON。 JSON键和字符串值必须使用双引号,而不是单引号。使用JSONLint来验证您的JSON。或者,更好的办法是创建一个Java对象,然后像Jackson一样编码器将该对象转换为有效的JSON。

而不是发送一个成功的响应(与代码200),与对象属性“成功”设置为false,您应该返回错误响应(400如果所需的凭据根本不存在,401 if他们无效)。这样做,不仅显示了HTTP协议的尊重,但使用HTTP承诺允许像预期一样:的

http(...).then(successCallback, errorCallback) 

代替

http(...).then(successButActuallyMaybeErrorCallback, anotherErrorCallback) 

你JSON是无效的使用单引号,应该是双

当大多数语言可以从本​​地数组和对象为您编码时,创建自己的程序是一种非常糟糕的做法。我不知道最好的方法使用Java,但它需要看起来像:

response.getWriter().write('{"success":false,"message":"wrong details"}'); 

注单开关和双引号