gpt4 book ai didi

java - 无法让 Angular $http 工作

转载 作者:行者123 更新时间:2023-12-01 10:16:38 31 4
gpt4 key购买 nike

我正在尝试让一个简单的 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com