如何从servlet来android应用传递数据 [英] how to pass data from servlet to android application

查看:90
本文介绍了如何从servlet来android应用传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 我在机器人在提交即时通讯使用的servlet我必须表明该表已成功插入用户插入到数据库中的表。这是我的应用程序



进口java.io.IOException异常;
进口javax.servlet.ServletException;
进口javax.servlet.http.HttpServlet的;
进口javax.servlet.http.HttpServletRequest;
进口javax.servlet.http.HttpServletResponse;
进口java.sql.Connection中;
进口java.lang.DriverManager中;
进口java.sql.Statement中;
进口的java.util.ArrayList;



/ **
 *
 * @author见习
 * /
公共类的形式延伸的HttpServlet {

字符串名称;
字符串密码;
连接CON = NULL;
声明语句= NULL;
/ **
 *流程为HTTP&LT请求; code取代; GET< / code取代;和< code取代; POST< / code取代;的方法。
 *参数要求servlet请求
 * @参数响应servlet响应
 * @throws了ServletException如果出现一个servlet特定的错误
 * @throws IOException  - 如果发生I / O错误
 * /

        / * TODO输出你在这里页面
        通过out.println(< HTML>中);
        通过out.println(< HEAD>中);
        通过out.println(<冠军> Servlet的形式LT; /标题>中);
        通过out.println(< /头>);
        通过out.println(<身体GT;);
        通过out.println(< H1>在Servlet的形式+ request.getContextPath()+< / H1>中);
        通过out.println(< /身体GT;);
        通过out.println(< / HTML>中);
        * /




@覆盖
保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)
抛出了ServletException,IOException异常{

   尝试
  {

  }

  赶上(例外前)
  {

  }
}

/ **
 *处理HTTP< code取代; POST< / code取代;方法。
 *参数要求servlet请求
 * @参数响应servlet响应
 * @throws了ServletException如果出现一个servlet特定的错误
 * @throws IOException  - 如果发生I / O错误
 * /
@覆盖
保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)
抛出了ServletException,IOException异常{
  尝试
  {
     的Class.forName(com.mysql.jdbc.Driver);
     CON =的DriverManager.getConnection(JDBC:mysql的://本地主机:3306 /登录,根,);
     字符串NN =的request.getParameter(姓名);
     字符串传递=的request.getParameter(通行证);
     字符串email =的request.getParameter(电子邮件);
     语句= con.createStatement();
     字符串查询=插入到用户价值('+ NN +,+通+,+电子邮件+');;
     INT V = stmt.executeUpdate(查询);
     ArrayList的<字符串> ARR =新的ArrayList<字符串>();
     arr.add(插入);

的System.out.println(发回响应......);

  }
  赶上(例外前)
  {

  }

}

/ **
 *返回这个servlet的简短说明。
 返回:包含的servlet描述的String
 * /
@覆盖
公共字符串getServletInfo方法(){
    返回简短说明;
} //< /编辑倍>

}
 

这是我的Andr​​oid应用程序

 包org.me.loginandroid;

进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.util.ArrayList;
进口java.io. *;
进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONObject;

进口android.app.Activity;
进口android.content.Intent;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.TextView;
进口org.apache.http.client.methods.HttpGet;

公共类MainActivity延伸活动{

    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        按钮BTN1 =(按钮)findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    私人OnClickListener listener_login =新OnClickListener(){

        布尔查= FALSE;

        公共无效的onClick(视图v){
            EditText上emailText =(EditText上)findViewById(R.id.email);
            EditText上passText =(EditText上)findViewById(R.id.password);
            EditText上nameText =(EditText上)findViewById(R.id.uname);

            字符串名称= nameText.getText()的toString()。
            字符串email =(emailText.getText()的toString());
            字符串传递=(passText.getText()的toString());

            字符串结果=;
            ArrayList的<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>();
            nameValuePairs.add(新BasicNameValuePair(姓名,名字));
            nameValuePairs.add(新BasicNameValuePair(通,通));
            nameValuePairs.add(新BasicNameValuePair(邮件,邮件));

            尝试 {
                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpPost httppost =新HttpPost(http://10.0.2.2:8084/Login/form);
                httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                HTT presponse响应= httpclient.execute(httppost);
                HttpEntity实体= response.getEntity();
                InputStream的是= entity.getContent();

                的BufferedReader读卡器=新的BufferedReader(新InputStreamReader的(就是,ISO-8859-1),8);
                StringBuilder的SB =新的StringBuilder();
                串线= NULL;
                而((行= reader.readLine())!= NULL){
                    sb.append(行+\ N);
                }
                is.close();
                结果= sb.toString();
                TextView的LBL =(TextView中)findViewById(R.id.lbl);
                lbl.setText(结果);
            }赶上(例外五){
                TextView的电视=(TextView中)findViewById(R.id.err);
                tv.setText(错误分析数据+ e.toString());
                的System.out.println(错误分析数据+ e.toString());
            }
            //解析JSON数据
            尝试 {
                布尔查= FALSE;
               ArrayList的<字符串>阵列=新的ArrayList<字符串>();
               的for(int i = 0; I< arrays.size();我++)
               {
                   如果(arrays.get(ⅰ).equals(插入))
                   {
                        检查=真;
                   }
                   其他
                   {
                   }
               }
               如果(检查)
               {
                   意图myintent =新的意图(MainActivity.this,welcome.class);
                   startActivity(myintent);
               }
               其他
               {
                    TextView的电视=(TextView中)findViewById(R.id.err);
                    tv.setText(数据不正确插入);
               }


            }赶上(例外五){
                //setContentView(R.layout.notify);
                TextView的电视=(TextView中)findViewById(R.id.err);
                tv.setText(e.toString());
                的System.out.println(log_tag+错误分析数据);

            }
        }
    };
}
 

解决方案

您可以在这里查询。有样本code整体描述

<一个href="http://stackoverflow.com/questions/8292815/send-arraylist-from-servlet-to-android-application">Send数组列表由servlet来Android应用程序

I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;



/**
 *
 * @author trainee
 */
public class form extends HttpServlet {

String name;
String password;
Connection con = null;
Statement stmt = null;
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

        /* TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet form</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet form at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
        */




@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   try
  {

  }

  catch(Exception ex)
  {

  }
} 

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
     String nn=request.getParameter("name");
     String pass=request.getParameter("pass");
     String email=request.getParameter("email");
     stmt=con.createStatement();
     String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
     int v=stmt.executeUpdate(query);
     ArrayList<String> arr=new ArrayList<String>();
     arr.add("inserted");

System.out.println("sent response back...");

  }
  catch(Exception ex)
  {

  }

}

/** 
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

this is my android application

package org.me.loginandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button) findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    private OnClickListener listener_login = new OnClickListener() {

        boolean check = false;

        public void onClick(View v) {
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText passText = (EditText) findViewById(R.id.password);
            EditText nameText = (EditText) findViewById(R.id.uname);

            String name = nameText.getText().toString();
            String email = (emailText.getText().toString());
            String pass = (passText.getText().toString());

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

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                TextView lbl = (TextView) findViewById(R.id.lbl);
                lbl.setText(result);
            } catch (Exception e) {
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText("Error parsing data " + e.toString());
                System.out.println("Error parsing data " + e.toString());
            }
            //parse json data
            try {
                boolean check=false;
               ArrayList<String> arrays=new ArrayList<String>();
               for(int i=0;i<arrays.size();i++)
               {
                   if(arrays.get(i).equals("Inserted"))
                   {
                        check=true;
                   }
                   else
                   {
                   }
               }
               if(check)
               {
                   Intent myintent = new Intent(MainActivity.this, welcome.class);
                   startActivity(myintent);
               }
               else
               {
                    TextView tv = (TextView) findViewById(R.id.err);
                    tv.setText("Data was not inserted properly");
               }


            } catch (Exception e) {
                //setContentView(R.layout.notify);
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText(e.toString());
                System.out.println("log_tag" + "Error parsing data ");

            }
        }
    };
}

解决方案

You can check here. There is a whole description with sample code

Send arraylist from servlet to Android application

这篇关于如何从servlet来android应用传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆