我已经google了很多尝试所有的解决方法,主要是为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的新手。
答案 0 :(得分:2)
参数(import "reflect-metadata"
)仅适用于request.getParameter()
数据或query string参数。您正在发送JSON。
要解决此问题,您可以send application/x-www-form-urlencoded,或者从请求输入流中提取JSON并自行解析。你需要使用杰克逊这样的图书馆。例如
application/x-www-form-urlencoded
InputStream in = request.getInputStream();
MyPojo pojo = new ObjectMapper().readValue(in, MyPojo.class);
是杰克逊班。