gpt4 book ai didi

java - J2EE 和 Angular HTTP POST servlet

转载 作者:太空狗 更新时间:2023-10-29 18:31:03 24 4
gpt4 key购买 nike

我在谷歌上搜索了很多,尝试了所有主要针对 PHP 的解决方法,但没有奏效。我正在尝试将 POST 参数发送到 j2ee servlet,但 servlet 未接收到参数,尽管如果我通过附加 URL (GET) 发送参数以便我能够接收数据。

这是代码。

   import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/Rx';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
userName: string;
password: string;

constructor(public navCtrl: NavController, public navParams: NavParams,
public http: Http) {
}

login() {

var headers = new Headers({ 'Content-Type': 'application/json' });

let options = new RequestOptions({ headers: headers });
let devicecode = '1-001-001-009-1';

let postParams = {
loginid: this.userName,
password: this.password,
devicecode: devicecode
}

this.http.post("http://localhost:8092/OCWebService/LoginOSO", postParams
, options)
.subscribe(data => {
console.log(data);
alert(data);
}, error => {
console.log(error);// Error getting the data
});


}

}

这是 Servlet 代码:

  protected void processRequest(HttpServletRequest request, 
HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
response.setContentType("text/html;charset=UTF-8");

BufferedReader bf = request.getReader();
String userName = request.getParameter("loginid");
String password = request.getParameter("password");
String deviceCode = request.getParameter("devicecode");
}

注意:我是 Ionic 2 的新手。

最佳答案

Parameters (request.getParameter()) 仅用于application/x-www-form-urlencoded 数据或query string参数。您正在发送 JSON。

要解决这个问题,您可以send application/x-www-form-urlencoded ,或者从请求输入流中提取 JSON 并自行解析。为此,您需要使用像 Jackson 这样的库。例如

 InputStream in = request.getInputStream();
MyPojo pojo = new ObjectMapper().readValue(in, MyPojo.class);

ObjectMapper 是一个 Jackson 类。

关于java - J2EE 和 Angular HTTP POST servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44645413/

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