作爲一名安卓開發者可以自己給自己寫接口,甚至會javaweb可以說是我一直以來渴望的,今天終於小有所成^–^
事先說明一下:
關注的小夥伴們注意一下,我上一篇寫的是web訪問數據庫的元數據封裝,今天用的就是上一次的那個javaweb小項目登錄和註冊,今天用到上次的內容,需要的小夥伴們可以下載我的項目^–^
點擊下載:小javaweb項目
登錄接口代碼:
package com.zbv.servlet.jiekou;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.zbv.dao.DBUserDao;
import com.zbv.dao.impl.DBUserDaoImpl;
import com.zbv.javabean.User;
public class AndroidLogin extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
DBUserDao dbDao=new DBUserDaoImpl();
//同樣的簡單格式要求可以在客戶端判斷
String username=request.getParameter("username");
String password=request.getParameter("password");
User user=dbDao.findUserByUsernameAndPassword(username, password);
if(user!=null){
//合法登陸成功
JsonObject json=new JsonObject();
json.add("ResultCode", new JsonPrimitive("200"));
response.getWriter().write(json.toString());
}else{
//不合法
JsonObject json=new JsonObject();
json.add("ResultCode", new JsonPrimitive("300"));//用戶名或者密碼錯誤
response.getWriter().write(json.toString());
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
註冊接口代碼:
package com.zbv.servlet.jiekou;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.zbv.dao.DBUserDao;
import com.zbv.dao.impl.DBUserDaoImpl;
import com.zbv.javabean.User;
public class AndroidRegister extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
DBUserDao dbDao=new DBUserDaoImpl();
//服務端不作判斷:會上傳給我-用戶名 密碼 郵箱以及生日 。那麼首先我必須判斷此用戶是否已註冊,如果沒有則添加到數據庫並且返回結果給客戶端
String uname=request.getParameter("username");//依據字段username獲取客戶端post的信息
User u=dbDao.findUserByUsername(uname);
if(u==null){
//說明該用戶沒有註冊過,那麼需要進行註冊
//創建對象並將數據封裝進去
User user=new User();
user.setUsername(request.getParameter("username"));
user.setPassword(request.getParameter("password"));
user.setEmail(request.getParameter("email"));
String birthday=request.getParameter("birthday");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
Date birth=sdf.parse(birthday);
user.setBirthday(birth);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//操作數據庫,把數據添加到數據庫,並且返回結果至客戶端
dbDao.addUser(user);
JsonObject json=new JsonObject();
json.add("ResultCode", new JsonPrimitive("200"));
response.getWriter().write(json.toString());
}else{
//該用戶已經存在了,不需要再註冊了
JsonObject json=new JsonObject();
json.add("ResultCode", new JsonPrimitive("100"));
//輸出響應
response.getWriter().write(json.toString());
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
注意啦,上面的兩段代碼也是放在javaweb項目中的,我把瀏覽器部分的servlet和安卓接口的servlet放在各自不同的包中。我的登錄接口爲:http:192.168.1.105:8080/LittleTest/Login;註冊接口爲:http:192.168.1.105:8080/LittleTest/Register;我把MyEclipse中默認的訪問地址/Servlet/AndroidLogin/AndroidRegister改爲Login和Register。可能這幾句解釋有些小夥伴不明白,但是不要緊,想要了解的可以深入瞭解一下web知識即可!
安卓佈局—我嘗試用TableLayout來佈局也是無意中看到決定試試水,效果還挺不錯的
登錄佈局:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:layout_gravity="center_horizontal"
android:stretchColumns="1"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/logo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="welcom to login"
android:textSize="25sp"
android:gravity="center_horizontal" />
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="username:"
/>
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
/>
</TableRow>
<TableRow >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="password:"
/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
/>
</TableRow>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:layout_marginTop="10dp"
>
<Button
android:id="@+id/btn_login"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Login"
android:background="@drawable/btn_bg_selector"
android:layout_marginRight="30dp"
/>
<Button
android:id="@+id/btn_register"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Register"
android:background="@drawable/btn_bg_selector"
/>
</LinearLayout>
</TableLayout>
註冊佈局:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:stretchColumns="1" >
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用戶名:"
android:textColor="@android:color/white"
android:textSize="20sp" />
<EditText
android:id="@+id/uname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="20sp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密 碼:"
android:textColor="@android:color/white"
android:textSize="20sp" />
<EditText
android:id="@+id/r_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:textColor="@android:color/white"
android:textSize="20sp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="郵 箱:"
android:textColor="@android:color/white"
android:textSize="20sp" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="20sp" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="生 日:"
android:textColor="@android:color/white"
android:textSize="20sp" />
<EditText
android:id="@+id/birthday"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="20sp" />
</TableRow>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="@+id/toRegister"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:background="@drawable/btn_bg_selector"
android:text="register" />
<Button
android:id="@+id/toBack"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg_selector"
android:text="back" />
</LinearLayout>
</TableLayout>
安卓代碼如下:—再次溫習一下HttpURLConnection以及HttpClient,因爲現在網絡連接類實在太豐富了,功能也十分強大例如Volley甚至xUtils,還用基礎類基本很少了,今天算是溫習一下,都快忘完了,順帶記錄一下,以後好複習,萬丈高樓也要平地起嘛!注意啦:代碼中的MainActivity也就是一個跳轉界面而已
Constant類:主要放一些常量例如url
package com.zbv.testforjavaweb;
public class Constant {
public static String MAIN="http://192.168.1.105:8080/LittleTest/";
public static String LOGIN="Login";
public static String REGISTER="Register";
}
Login登錄類—activity
package com.zbv.testforjavaweb;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener {
EditText u_name;
EditText pwd;
Button btn_login;
Button btn_register;
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_login);
u_name = (EditText) findViewById(R.id.username);
pwd = (EditText) findViewById(R.id.password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_register = (Button) findViewById(R.id.btn_register);
btn_login.setOnClickListener(this);
btn_register.setOnClickListener(this);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x100:
Toast.makeText(LoginActivity.this, "訪問出錯了",
Toast.LENGTH_SHORT).show();
break;
case 0x200:
String text=(String) msg.obj;
//json解析
try {
JSONObject json=new JSONObject(text);
String result=json.getString("ResultCode");
Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
};
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_login:
/**
* HttpURLConnection:Post
* */
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(Constant.MAIN + Constant.LOGIN);
HttpURLConnection huc = (HttpURLConnection) url
.openConnection();
huc.setDoInput(true);
huc.setDoOutput(true);
huc.setReadTimeout(5000);
huc.setConnectTimeout(5000);
huc.setRequestMethod("POST");
// huc.setRequestProperty("Content-Type", "appliction/x-www-form-urlencoded");
// huc.setRequestProperty("Content-Length", "")
OutputStream os = huc.getOutputStream();
String strs = "username=" + u_name.getText().toString()
+ "&password=" + pwd.getText().toString();
os.write(strs.getBytes("utf-8"));
if (huc.getResponseCode() == 200) {
InputStream is = huc.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = is.read(bytes)) != -1) {
baos.write(bytes, 0, len);
}
String result = new String(baos.toByteArray());
Message msg = mHandler.obtainMessage();
msg.what = 0x200;
msg.obj = result;
mHandler.sendMessage(msg);
} else {
// 出錯了
mHandler.sendEmptyMessage(0x100);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
break;
case R.id.btn_register:
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
break;
}
}
}
Register註冊類—activity
package com.zbv.testforjavaweb;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
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.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends Activity implements OnClickListener{
EditText[] edits;
Button btn_register;
Button btn_back;
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_register);
edits=new EditText[4];
edits[0]=(EditText) findViewById(R.id.uname);//username
edits[1]=(EditText) findViewById(R.id.r_pwd);//username
edits[2]=(EditText) findViewById(R.id.email);//username
edits[3]=(EditText) findViewById(R.id.birthday);//username
btn_back=(Button) findViewById(R.id.toBack);
btn_register=(Button) findViewById(R.id.toRegister);
btn_back.setOnClickListener(this);
btn_register.setOnClickListener(this);
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x100:
Toast.makeText(RegisterActivity.this, "訪問出錯了", Toast.LENGTH_SHORT).show();
break;
case 0x200:
String text=(String) msg.obj;
try {
JSONObject json=new JSONObject(text);
String result=json.getString("ResultCode");
Toast.makeText(RegisterActivity.this, result, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
};
}
@Override
public void onClick(View v) {
int id=v.getId();
switch (id) {
case R.id.toRegister:
new Thread(new Runnable() {
@Override
public void run() {
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(Constant.MAIN+Constant.REGISTER);
//post.setParams(new BasicNameValuePair("username", value))
List<NameValuePair> list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("username", edits[0].getText().toString()));
list.add(new BasicNameValuePair("password", edits[1].getText().toString()));
list.add(new BasicNameValuePair("email", edits[2].getText().toString()));
list.add(new BasicNameValuePair("birthday", edits[3].getText().toString()));
try {
post.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
HttpResponse response=client.execute(post);
Log.d("tag", "register......"+response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode()==200){
String result=EntityUtils.toString(response.getEntity());
//InputStream is=response.getEntity().getContent();
Message msg=mHandler.obtainMessage();
msg.what=0x200;
msg.obj=result;
mHandler.sendMessage(msg);
}else{
mHandler.sendEmptyMessage(0x100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
break;
case R.id.toBack:
Intent intent=new Intent(this, LoginActivity.class);
startActivity(intent);
break;
}
}
}
勵志一番:分享是爲了共同進步,小夥伴們願我們繼續加油^__^!
歡迎大神的指正和建議,謝謝啦!