gpt4 book ai didi

AngularJS $http 参数与数据——如何在服务器上获取 'data'?

转载 作者:行者123 更新时间:2023-12-02 22:19:01 24 4
gpt4 key购买 nike

背景:使用 AngularJS 表单将数据发送到 Java servlet。

假设我的 $scope 中有一些模型,来自表单,名为firstName:

Controller 中的$http请求:

$http({
method: 'POST',
url: '/CustomerTrackerApp/JSONManager',
params: { firstName: $scope.firstName }
}).then(function(response) {
alert(response.data);
});

Servlet 中的 doPost() 方法:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String firstName = request.getParameter("firstName");
out.println("From Servlet: " + firstName);
}

这成功地发出警报“来自 Servlet:{在表单中输入的名称}”

我的问题是 params: { firstName: $scope.firstName, } 导致字段显示在网址中,所以我想使用:

$http({
method: 'POST',
url: '/CustomerTrackerApp/JSONManager',
data: { firstName: $scope.firstName }
}).then(function(response) {
alert(response.data);
});

如何从 doPost() 内的 data: { firstName: $scope.firstName } 获取 firstName 的值并将其保存在数组中?

非常感谢您的帮助,我已经在谷歌上搜索了一段时间,但找不到答案。

最佳答案

找到了解决方案。在java servlet doPost()中使用了InputStreamReader和BufferedReader:

InputStreamReader isr = new InputStreamReader(request.getInputStream());
BufferedReader in = new BufferedReader(isr);
String line = in.readLine();

现在您可以使用 JSONObject 轻松地将数据作为字符串进行操作:

JSONObject json;

try {

json = new JSONObject(line);
String jsonString = json.toString();
String[] names = JSONObject.getNames(json);

for (int i=0 ; i < names.length ; i++) {
System.out.println(names[i] + " : " + json.getString(names[i]));
}

} catch (JSONException e) { e.printStackTrace(); }

关于AngularJS $http 参数与数据——如何在服务器上获取 'data'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23715957/

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