2012-10-21 30 views
-1

我試圖從Android客戶端向HttpServlet發送一些數據。我的servlet代碼如下HttpServlet在Android客戶端的doPost()中接收空值

import java.io.IOException; 
import java.io.PrintWriter; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 


public class DBServlet extends HttpServlet { 
private static final long serialVersionUID = 1L; 
Connection connection= null; 

/** 
* @see HttpServlet#HttpServlet() 
*/ 
public DBServlet() { 
     super(); 
} 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    doPost(request, response); 
} 

/** 
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 

    if(request.getParameterNames().hasMoreElements()){ 
       insertRecord(request, getDbConnection()); 
      } 
      else{ System.out.println("Servlet Started First Time"); } 



} 

/** 
* Return database connection 
* @return 
*/ 
private Connection getDbConnection(){ 
     String connectionURL = "jdbc:mysql://127.0.0.1:3306/testDB"; 

     try { 

      Class.forName("com.mysql.jdbc.Driver"); 
      connection = DriverManager.getConnection(connectionURL, "root", ""); 

     } catch (SQLException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return connection; 
} 

/** 
* Insert record in database 
* @param request 
* @param connection 
*/ 
private void insertRecord(HttpServletRequest request, Connection connection){ 

      System.out.println("===== Received Record ====="); 

      PreparedStatement stmt; 

      try { 
       stmt = connection.prepareStatement("insert into users(Name,email,password) values(?,?,?)"); 
       stmt.setString(1, request.getParameter("name")); 
       stmt.setString(2, request.getParameter("e-mail")); 
       stmt.setString(3, request.getParameter("password")); 

       int i= stmt.executeUpdate(); 

       if(i != 0){ 
        System.out.println("data inserted !!!"); 
       } 
       else{ 
        System.out.println("data failed to insert"); 
       } 

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

      finally{ 

       try { 
        connection.close(); 
       } catch (SQLException e) { 

        e.printStackTrace(); 
       } 
      } 
    } 
} 

和我的Android代碼

import java.io.DataOutputStream; 
import java.io.IOException; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.util.ArrayList; 

import org.apache.http.NameValuePair; 

import org.apache.http.message.BasicNameValuePair; 

import com.example.messenger.R; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.StrictMode; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

public class SignUp extends Activity { 

Button register; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.sign_up); 

    register = (Button)findViewById(R.id.register); 

    register.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Log.v("OnClick", "=== onClick ==="); 
      registerUser(); 

     } 
    }); 
} 

@SuppressLint({ "NewApi", "NewApi", "NewApi" }) 
private void registerUser(){ 


     String name= ((EditText)findViewById(R.id.name)).getText().toString(); 
     String email= ((EditText)findViewById(R.id.email)).getText().toString(); 
     String password= ((EditText)findViewById(R.id.password)).getText().toString(); 

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     nameValuePairs.add(new BasicNameValuePair("name", name)); 
     nameValuePairs.add(new BasicNameValuePair("email", email)); 
     nameValuePairs.add(new BasicNameValuePair("password", password)); 


     try { 

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 

      URL url=new URL("http://192.168.1.10:8080/DBservlet/DBServlet"); 
      HttpURLConnection con = (HttpURLConnection)url.openConnection(); 
      con.setDoOutput(true); 
      con.setRequestMethod("POST"); 
      DataOutputStream dos=new DataOutputStream(con.getOutputStream()); 
      dos.writeBytes(name); 
      dos.flush(); 
      dos.close(); 

} catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

} 

} 

的問題是,當我運行「的Servlet」我得到的輸出「的Servlet開始第一次」,這是確定的,但在我運行我的android客戶端,並在EditText字段中寫入一些數據並按下注冊按鈕,沒有任何反應。 'Servlet'收不到任何東西。請讓我知道我該如何解決這個問題。

問候,

+3

我不確定你具體*詢問*。你似乎已經做出了關於要求的觀察和陳述。我現在所能想到的只是,「好吧,只是相應地編寫代碼」。但那會使整個問題完全無用。請詳細說明具體問題。相應地編寫代碼時,你到底在哪裏? – BalusC

+1

我還不明白具體問題。只需放入一個'if'塊來檢查是否從客戶端收到數據,然後只在條件爲真時才執行查詢?如果實際上比這更復雜,那麼你真的需要詳細說明。我們不能神奇地照射到您的位置,以便自己查看您的代碼。編輯這個問題並加入一些清楚地表明問題的具體代碼對於更好地理解您的具體問題會非常有幫助。 – BalusC

+1

您在編輯過程中添加的問題反過來很奇怪。保持'doPost()'方法等待,直到請求屬性被設置?當前的線程基本上代表了HTTP請求本身時,這種情況如何呢?難道你不是真的指的是會話屬性嗎?也許你需要花更多的時間來學習基本的HTTP和servlet是如何工作的,然後再問概念錯誤的問題。這些帖子可能會有所幫助,然後:http://stackoverflow.com/a/3106909和http://stackoverflow.com/q/2793150一旦你正確掌握了基本概念,改善了這個問題。 – BalusC

回答

0

你的servlet查找功能還好(設計技術上沒有,但那是另一回事)。然而,你的Android側看起來絕對不好。

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
nameValuePairs.add(new BasicNameValuePair("name", name)); 
nameValuePairs.add(new BasicNameValuePair("email", email)); 
nameValuePairs.add(new BasicNameValuePair("password", password)); 

是你將如何發送使用Android的內置的Apache HttpClient API的HTTP請求之前準備請求參數。

但在這裏,

URL url=new URL("http://192.168.1.10:8080/DBservlet/DBServlet"); 
HttpURLConnection con = (HttpURLConnection)url.openConnection(); 
con.setDoOutput(true); 
con.setRequestMethod("POST"); 
DataOutputStream dos=new DataOutputStream(con.getOutputStream()); 
dos.writeBytes(name); 
dos.flush(); 
dos.close(); 

但是你發送使用Java SE內建URLConnection API,而不是HTTP請求。然後實際上以一種不好的方式;您沒有發送正確的application/x-www-form-urlendocded查詢字符串,而是平臺默認編碼中的單個字符串值。此外,DataOutputStream在這種情況下完全沒有意義,您根本沒有創建.dat文件。這感覺太像「roseindia.net-snippet」了。如果你確實正在閱讀那個可怕的網站,請從現在開始將它列入一生中的黑名單。

它看起來像你在混合不同在Android中發送HTTP POST請求的方法。

  1. Using HttpClient API
  2. Using URLConnection API

你應該選擇一個或另一個,並堅持下去。上面的鏈接指向Stack Overflow答案的具體例子。

+0

嗨Balusc,我沒有讀roseindia的任何東西。如果我有一些問題,我來到這裏:)無論如何,我已經改變了我的Android客戶端代碼之前,您的答案與HttpClient API而不是URLConnection。它的工作正常:)。感謝您的幫助和支持,但我還有一個問題,爲什麼它在設計技術上不好? –

+0

嗨BalusC,請你詳細說一下爲什麼servlet設計 - 技術上不行嗎? –