java - 无法让 Angular $http 工作

标签 java angularjs servlets

我正在尝试让一个简单的 angularjs 登录屏幕正常工作。 Angular 应用程序通过 http get 方法将登录详细信息发送到 java servlet,并预期包含成功/失败的 json 响应。 java servlet 在 Tomcat 8.0 上运行。

不幸的是,Angular 应用程序似乎无法从 servlet 接收数据(它确实将数据发送到 servlet) - 每次都会调用“then”的 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。

此外,您不应在对象属性“success”设置为 false 的情况下发回成功响应(代码为 200),而应返回错误响应(如果所需凭据根本不存在,则返回 400;如果所需凭据不存在,则返回 401)无效)。这样做不仅显示了对 HTTP 协议(protocol)的尊重,而且允许按预期使用 http promise :

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

而不是

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

关于java - 无法让 Angular $http 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853067/

相关文章:

java - 我应该如何让程序停止并等待某些事情? java

java - 当引用 Java 对象模型中的关联时,为引用分配 null 值背后的相关性是什么?

java - “gomobile.user u”不能是 FROM 子句的第一个声明

javascript - Bootstrap 模态和 AngularJS

Java servlet java.lang.NoClassDefFoundError : org/json/JSONObject

java - 如何使用 tomcat 5.5 上传 excel 文件?

jquery - Servlet 在新窗口中打开 PDF

java - -Dwebdriver.chrome.driver 中的 -D 是什么意思

javascript - 如何将数组发布到我的 firebase 数据库中?

javascript - 动态添加指令时, Angular 代码无法在指令内工作?