2017-06-20 81 views
2

我已經搜索了很多嘗試所有主要針對PHP的解決方法,但它不起作用。我試圖將POST參數發送給j2ee servlet,但是在servlet中沒有收到參數,但是如果我通過附加URL(GET)發送參數,以便能夠接收數據。J2EE和Angular HTTP POST小服務程序

這是代碼。

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"); 
     } 

注:我是新來的離子2.

+0

您應該發佈servlet代碼的堆棧跟蹤 – Dummy

回答

1

參數(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是一個傑克遜類。

+0

謝謝。像魅力一樣工作!我使用了第一種解決方案。 –