I have googled a lot tried all the workarounds which were mostly for PHP but it didn't work. I'm trying to send POST parameters to j2ee servlet but parameters are not being received at servlet although if I'm sending parameters by attaching with URL (GET) so that I'm able to receive data.
Here's the code.
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
});
}
}
Here's the Servlet Code:
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");
}
Note: I'm new to Ionic 2.
Parameters (request.getParameter()) is only for application/x-www-form-urlencoded data or query string parameters. You are sending JSON.
To solve the problem, you can either send application/x-www-form-urlencoded, or extract the JSON from the request input stream and parse it yourself. You will need to use a library like Jackson for this. For example
InputStream in = request.getInputStream();
MyPojo pojo = new ObjectMapper().readValue(in, MyPojo.class);
ObjectMapper is a Jackson class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With