作为一名安卓开发者可以自己给自己写接口,甚至会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;
}
}
}
励志一番:分享是为了共同进步,小伙伴们愿我们继续加油^__^!
欢迎大神的指正和建议,谢谢啦!