Android 클라이언트에서 HttpServlet으로 일부 데이터를 보내려고합니다. OK 그러나 때이다HttpServlet Android 클라이언트에서 doPost()의 Null 수신
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();
}
}
}
}
을 다음과 내 안드로이드 코드 문제는 내가 '서블릿'을 실행할 때 출력을 얻을 수 있다는 것입니다
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();
}
}
}
그대로 내 서블릿 코드는 '서블릿 시작 처음' 내 안드로이드 클라이언트를 실행하고 EditText 필드에 일부 데이터를 작성하고 아무 것도 일어나지 않는 Register 버튼을 누릅니다. 'Servlet'은 아무것도받지 못합니다. 이 문제를 어떻게 해결할 수 있는지 알려주십시오.
감사합니다,
구체적으로 당신이 무엇인지 모르겠습니다 *. 당신은 요구 사항에 대한 관찰과 진술을 한 것처럼 보입니다. 내가 지금 생각할 수있는 것은 "글쎄, 그냥 코드를 적어 라"이다. 그러나 그것은 전체 질문을 완전히 쓸모 없게 만들 것입니다. 구체적인 문제를 자세히 설명해주십시오. 그에 따라 코드를 작성하는 동안 정확히 어디에 갇혀 있습니까? – BalusC
아직도 구체적인 문제를 이해하지 못합니다. 데이터가 클라이언트로부터 수신되었는지를 검사하고 조건이 참인 경우에만 쿼리를 실행하는'if' 블록을 넣으십시오. 실제로 더 복잡하다면, 더 자세히 설명해야합니다. 우리는 스스로 코드를보기 위해 마술처럼 당신의 위치로 넘겨 줄 수는 없습니다. 질문을 편집하고 문제를 명확히 보여주는 구체적인 코드를 포함하면 구체적인 문제를 더 잘 이해하는 데 매우 도움이됩니다. – BalusC
편집하는 동안 추가 한 질문은 매우 이상합니다. 요청 속성이 설정 될 때까지'doPost()'메소드를 대기 상태로 유지 하시겠습니까? 현재 스레드가 기본적으로 HTTP 요청 자체를 나타내는 경우 어떻게 가능합니까?실제로 세션 속성을 대신 사용 하시겠습니까? 아마도 당신은 개념적으로 잘못된 질문을하기 전에 기본 HTTP 및 서블릿 작동 방식을 배우는데 더 많은 시간을 투자해야 할 것입니다. 그 게시물은 다음 도움이 될 수 있습니다 : http://stackoverflow.com/a/3106909 및 http://stackoverflow.com/q/2793150 일단 당신이 제대로 기본 개념을 파악하고, 질문을 향상시킵니다. – BalusC