安卓连接servlet及mysql

客户端--界面
<?xml version="1.0" encoding="UTF-8"?>

    <LinearLayout
        android:background="@mipmap/grade"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical"
        xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout
        android:layout_height="20pt"
        android:layout_width="match_parent">
    </RelativeLayout>
    <RelativeLayout
        android:layout_height="108dp"
        android:layout_width="235dp"
        android:layout_marginLeft="35pt"
        android:layout_marginTop="30pt"
        android:layout_marginRight="35pt"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true">

    <TextView
        android:layout_height="20pt"
        android:layout_width="80pt"
        android:textColor="@color/colorGray"
        android:textSize="10pt"
        android:text="您的成绩是"
        android:id="@+id/textView4"/>

    <TextView
        android:layout_height="50pt"
        android:layout_width="match_parent"
        android:textColor="@color/colorRed"
        android:textSize="15pt"
        android:text="9:30:30"
        android:layout_marginLeft="49dp"
        android:id="@+id/grade"
        android:layout_marginTop="33dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginStart="49dp"/>

</RelativeLayout>
    <RelativeLayout
        android:layout_height="60pt"
        android:layout_width="match_parent"
        android:layout_marginLeft="35pt"
        android:layout_marginTop="20pt"
        android:layout_marginRight="35pt"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true">

    <Button
        android:background="@drawable/btn_click"
        android:layout_height="18pt"
        android:layout_width="50pt"
        android:textColor="@color/colorGray"
        android:text=" 重 玩"
        android:id="@+id/again"
        android:layout_marginTop="11dp"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/end"
        android:layout_alignLeft="@+id/end"/>

    <Button
        android:background="@drawable/shape"
        android:layout_height="18pt"
        android:layout_width="50pt"
        android:textColor="@color/colorGray"
        android:text="退 出 游 戏"
        android:id="@+id/end"
        android:layout_marginTop="27dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/again"/>

</RelativeLayout>

</LinearLayout>
界面对应的代码
package com.huat.qi.appfirst; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.huat.qi.appfirst.util.GradeUtils; public class grade extends AppCompatActivity { private TextView grade; private Button again; private Button end; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grade); //成绩显示 grade = (TextView)findViewById(R.id.grade); Bundle bundle = this.getIntent().getExtras();//获得绑定字段 String name = bundle.getString("timer"); grade.setText(name); //重玩 again = (Button)findViewById(R.id.again); again.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
new AsyncTask<Void,Void,Void>() { String result1=null; @Override protected Void doInBackground(Void... params) { //必须开启子线程访问网络 //提交数据到服务器 result1= GradeUtils.connect("你电脑的ip地址", grade.getText().toString().trim()); return null; } @Override protected void onPostExecute(Void result) { if(result1==null){ return ; } if(result1.equals("hello")){ startActivity(new Intent(grade.this,MainActivity.class)); finish(); }else{ Toast.makeText(grade.this,result1,300).show(); } super.onPostExecute(result); } }.execute(); } }); //退出游戏 end = (Button)findViewById(R.id.end); end.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { intent = new Intent(); intent.setClass(grade.this,MainActivity.class); startActivity(intent); } }); } }
访问servlet的工具类(客户端)
package com.huat.qi.appfirst.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Qi on 2018/6/9.
 */

public class GradeUtils {
    public GradeUtils(){
    }
    public static String connect(String ip, String grade) {
        String str = "http://" + ip
                + ":8084/game/GradeServlet?grade="+grade; //本机ip及访问的端口
        URL url=null;
        InputStream inputStream = null;
        HttpURLConnection connection = null;
        StringBuffer sb = null;// 线程安全
        try {
            url = new URL(str);//获得URL对象
            try {
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(3000);
                connection.setRequestMethod("GET");//GET方式提交参数
                connection.setDoOutput(true);//设置可以向服务器读写
                connection.setDoInput(true);
                //请求成功
                if (connection.getResponseCode() == 200) {
                    inputStream = connection.getInputStream();
                    Reader reader = new InputStreamReader(inputStream, "UTF-8");
                    //打包成字符流
                    BufferedReader bufferedReader = new BufferedReader(reader);
                    String str1 = null;
                    sb = new StringBuffer();
                    while ((str1 = bufferedReader.readLine()) != null) {
                        sb.append(str1);
                    }

                }

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

            e.printStackTrace();
            //关闭流很重要
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }

        }
        if (sb != null) {
            return new String(sb);
        }
        return "服务器异常!";

    }
}

服务器端
GradeServlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter();
String grade = request.getParameter("grade"); grade = new String(grade.getBytes("ISO-8859-1"),"UTF-8"); System.out.println(grade ); if(DaoFectory.getGradeDao().insertGrade(grade)){ out.write("hello"); System.out.print("返回的数据:"+"hello"+"登录成功");
}else{ System.out.println("插入失败" ); } }

数据库部分
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 *
 * @author Qi
 */
public class GradeDaoImp implements IGameDao{
    private static String url = "jdbc:mysql://localhost:3306/huat";
    private static String user = "用户名";
    private static String password = "密码";
    public boolean insertGrade(String grade){
        Statement stmt = null;
        PreparedStatement pstmt = null;   //灵活的对象
        Connection conn = null;
        try {
            //1.驱动注册程序
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接对象
            conn = (Connection) DriverManager.getConnection(url, user, password);
            String sql = "INSERT INTO gamegrade(grade) VALUES(?)";
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            pstmt.setString(1, grade);
            int count = pstmt.executeUpdate();
            System.out.println("影响了" + count + "行!");
            if(count==1){
                return true;
            }else{
                return false;
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //7.关闭连接(顺序:后打开的先关闭)
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

相关接口 (各自在独立的文件)

public interface IGameDao {
    public boolean insertGrade(String grade);
}


public class DaoFectory {
     public static  IGameDao getGradeDao(){
         return new GradeDaoImp();
    }
}
基本就是这样,注意web.xml的配置,以及服务器端与客户端的内容分开,运行时先开服务器,让它在Tomcat上跑起来,再开客户端即可。
客户端最重要的部分就是将值传到servlet那一部分,注意GradeUtils那部分的代码!
服务器端比较重要的就是配置文件,其他的就是数据库的操作了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值