如何将数据从servlet传递到android应用程序

2024-04-22

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>

}

这是我的安卓应用程序

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

            }
        }
    };
}

您需要创建一个到 servlet 页面的 URLConnection 并执行此操作。其示例:如何从 url 下载文件/图像到您的设备 http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将数据从servlet传递到android应用程序 的相关文章

随机推荐

  • python文本框中文本和滚动条的自动滚动

    我有一个 tkinter 文本 和 滚动条 工作正常 在我的程序中 文本窗口中的行会自动不断添加 因此 当插入新的文本行且数据超出限制时 我希望文本和滚动条自动滚动到底部 以便始终显示最新的文本行 这个怎么做 另外 如何链接文本窗口和滚动条
  • 我们如何有效地处理 mnesia 记录的时间相关约束?

    我正在将记录写入mnesia 该记录应该保存在那里 仅在允许的时间 24 小时 内 24小时后 在用户修改其中的一部分之前 系统应该自动删除它们 例如 用户获得免费通话时间 用于语音通话 他们应该在给定时间内使用它们 如果他们不使用它 24
  • QtWebKit 无需安装 flash 播放器即可播放 HTML5 视频

    安装最新的 Flash 播放器并启用插件后 我的简单示例可以播放 YouTube 视频 操作系统 Windows 7 Qt 4 7 4 32 位和 64 位均可 但是 根据 http www youtube com html5 我的示例浏览
  • 三引号内可以有变量吗?如果是这样,怎么办?

    对于某些人来说 这可能是一个非常简单的问题 但它却难倒了我 你能在Python的三引号内使用变量吗 在下面的例子中 如何在文本中使用变量 wash clothes tuesdays clean dishes never mystring I
  • Electron Web 蓝牙 API requestDevice() 错误

    我正在尝试开发一个与蓝牙低功耗设备通信的应用程序 我使用 Web Bluetooth API 建立了一个工作 网站 一切正常 所以我使用 Electron 框架来构建一个应用程序 这个问题是已知的 如果你开始navigator blueto
  • 使用 jQuery 选择非标准标签

    有没有办法使用 jQuery 来选择
  • 基于动态用户属性创建受众

    我有一个应用程序 用户可以在其中拥有 付费 或 免费 状态 用户可以从 免费 切换到 付费 如果他进行应用内购买 或者如果他停止支付订阅费用 则可以从 付费 切换到 免费 我可以使用动态用户属性来跟踪 Firebase 中的信息吗 在文档中
  • 使用矢量化为 iPhone 编译 Eigen 库

    我正在努力为 iPhone 4 编译 Eigen 库 该库具有带有 armv7 指令集的 ARM 处理器 到目前为止 当我指定预处理器定义 EIGEN DONT VECTORIZE 时 一切正常 但由于一些性能问题 我想使用armv7优化的
  • 删除 IntelliJ 中的“运行任何内容”历史记录

    我正在使用 IntelliJ 2019 3 我想删除 Run Anything 历史记录中的 执行 Maven 目标 我怎样才能做到这一点 我找到的所有答案都是删除workspace xml 但这不适用于此版本 One other way
  • 如何分离运行容器并在退出时自动删除它们?

    Why are d and rmDocker 中的争论有冲突吗 docker run d rm image Conflicting options rm and d 我有许多运行单元 功能 集成测试的容器 Docker 容器启动 运行测试
  • 如何在项目中生成jar和war

    我们有两个不同的项目 并且两个项目中的控制器几乎相同 项目 A 内部有控制器 所以为其引发战争不是问题 但是项目 B 需要项目 A 控制器的控制器 jar 谁能告诉我如何从项目 A 的控制器生成可以在项目 B 中使用的 jar 文件 这种情
  • X-FRAME-OPTIONS: DENY 通过 nginx 来自 Django 站点在哪里?

    我的 Django 网站使用django summernote https github com summernote django summernote在 iframe 中 并抛出此错误 多个具有冲突值的 X Frame Options
  • C# 获取分配总数

    有没有办法获得分配总数 注意 分配数量 而不是分配的字节数 它可以是当前线程的 也可以是全局的 以更容易的为准 我想检查特定函数分配了多少个对象 虽然我了解 调试 gt 性能分析器 Alt F2 但我希望能够从程序内部以编程方式执行此操作
  • 允许 PDFium 支持 x86 和 x64

    我构建了一个 WinForms 应用程序 它使用 PDFium 来打印 PDF 文档 我从 NuGet 安装了 PDFium 它在我的项目中创建了两个子文件夹 x86 和 x64 正如预期的那样 每个子文件夹中都包含相关版本的 pdfium
  • 将均匀分布转换为正态分布

    如何将均匀分布 大多数随机数生成器产生的结果 例如在 0 0 和 1 0 之间 转换为正态分布 如果我想要我选择的平均值和标准差怎么办 方法有很多 Do not使用博克斯穆勒 特别是当你画很多高斯数时 Box Muller 产生的结果被限制
  • Django:模型类 user.models.Users 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中

    姜戈版本 2 0蟒蛇 3 6 5错误 模型类 user models Users 未声明显式 app label 并且不在 INSTALLED APPS 中的应用程序中 我刚刚将模型用户添加到我的视图中 base py DJANGO APP
  • 在SQL Server 2012 TSQL中,使用XML RAW、XML AUTO和XML PATH有什么区别

    正如标题所示 欢迎所有开放的思想 我在我的电脑上测试了一下 输出似乎是一样的 例如 USE BOB DATABASE SELECT ID Name First Name Last Name FROM DBO T User FOR XML A
  • 生成字符串所有组合的算法

    我在网上找到了一个链接 其中显示了生成字符串的所有组合的算法 http www mytechinterviews com combinations of a string http www mytechinterviews com comb
  • 为什么选择源进行 SQL 架构比较会导致 VS2012 崩溃?

    似乎没有任何原因 选择 SQL gt 架构比较 gt 新架构比较 然后尝试 选择源 会导致 Visual Studio 2012 崩溃 几个月来它一直按预期工作 除了尝试重新安装之外还有其他可能的修复方法吗 注意 尝试在 Visual St
  • 如何将数据从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 in