Android+struts2+json方式模拟手机登录功能
2016-03-14 15:28
537 查看
涉及到的知识点:
1.Struts2框架的搭建(包括Struts2的jSON插件)
2.Android前台访问Web采用HttpClient方式。
3.Android采用JSON的解析。
服务端主要包含一个Action,通过struts的web配置配置struts.xml驱动业务逻辑的执行,然后对于符合条件的登录,返回给客户端通过jsonobject包装的数据。
服务端代码:
package com.easyway.json.android;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
/** * 模拟登录,并返回json数据 @author xiangzhihong
*/
public class LoginAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
/** * */
private static final long serialVersionUID = 1L;
HttpServletRequest request;
HttpServletResponse response;
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
/**
* 模拟用户登录的业务
*/
public void login() {
try {
this.response.setContentType("text/json;charset=utf-8");
this.response.setCharacterEncoding("UTF-8");
//JSONObject json=new JSONObject();
Map<String,String> <span style="color: #ff0000;">json</span>=new HashMap<String,String>();
if ("admin".equals(userName)&&"123456".equals(password)) {
json.put("message", "欢迎管理员登陆");
} else if ((!"admin".equals(userName))&&"123456".equals(password)) {
json.put("message", "欢迎"+userName+"登陆!");
} else {
json.put("message", "非法登陆信息!");
}
byte[] jsonBytes = json.toString().getBytes("utf-8");
response.setContentLength(jsonBytes.length);
response.getOutputStream().write(jsonBytes);
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
接下来是客户端代码,用AsyncHttpClient进行网络的请求,如果包含我返回的json字符串的标志,我认为访问成功
客户端代码:
好了,就到这,有需要的需要体验的请到我的git账号下载测试程序。
服务端代码:https://github.com/xiangzhihong/login
客户端代码:https://github.com/xiangzhihong/loginAndroid
1.Struts2框架的搭建(包括Struts2的jSON插件)
2.Android前台访问Web采用HttpClient方式。
3.Android采用JSON的解析。
服务端主要包含一个Action,通过struts的web配置配置struts.xml驱动业务逻辑的执行,然后对于符合条件的登录,返回给客户端通过jsonobject包装的数据。
服务端代码:
package com.easyway.json.android;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
/** * 模拟登录,并返回json数据 @author xiangzhihong
*/
public class LoginAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
/** * */
private static final long serialVersionUID = 1L;
HttpServletRequest request;
HttpServletResponse response;
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
/**
* 模拟用户登录的业务
*/
public void login() {
try {
this.response.setContentType("text/json;charset=utf-8");
this.response.setCharacterEncoding("UTF-8");
//JSONObject json=new JSONObject();
Map<String,String> <span style="color: #ff0000;">json</span>=new HashMap<String,String>();
if ("admin".equals(userName)&&"123456".equals(password)) {
json.put("message", "欢迎管理员登陆");
} else if ((!"admin".equals(userName))&&"123456".equals(password)) {
json.put("message", "欢迎"+userName+"登陆!");
} else {
json.put("message", "非法登陆信息!");
}
byte[] jsonBytes = json.toString().getBytes("utf-8");
response.setContentLength(jsonBytes.length);
response.getOutputStream().write(jsonBytes);
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
接下来是客户端代码,用AsyncHttpClient进行网络的请求,如果包含我返回的json字符串的标志,我认为访问成功
客户端代码:
package xzh.com.listviewhover.ui; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.StrictMode; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import xzh.com.listviewhover.R; import xzh.com.listviewhover.base.Constants; /** * Created by xiangzhihong on 2016/3/14 on 12:07. * 测试服务端的登录json */ public class LoginActivity extends AppCompatActivity { @InjectView(R.id.account) EditText account; @InjectView(R.id.pwd) EditText pwd; @InjectView(R.id.login) Button login; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { initProxy(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.inject(this); initView(); } private void initProxy() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); //设置虚拟机的策略 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDeath() .build()); } private void initView() { } @OnClick(R.id.login) void loginClick(View v){ String userName=account.getText().toString(); String password=pwd.getText().toString(); doLogin(userName,password); } private void doLogin(String userName, String password) { final String[] result = {null}; String reqUrl=null; reqUrl= Constants.LOGIN_URL+"userName="+userName+"&password="+password; try { doHttp(result, reqUrl); AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle("提示") .setMessage(result[0]) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(LoginActivity.this,MainActivity.class)); } }).setNegativeButton("取消",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void doHttp(final String[] result, String reqUrl) { // HttpClient httpclient = new DefaultHttpClient(); // HttpGet request=new HttpGet(reqUrl); // request.addHeader("Accept","text/json"); // HttpResponse response =httpclient.execute(request); // HttpEntity entity=response.getEntity(); // String json = EntityUtils.toString(entity,"UTF-8"); // if(json!=null&&json.contains("message")){ //// JSONObject jsonObject=new JSONObject(json); //// result=jsonObject.get("message").toString(); // result="登录成功"; // }else { // result="登录失败请重新登录"; // } AsyncHttpClient client = new AsyncHttpClient(); client.get(this,reqUrl,new AsyncHttpResponseHandler(){ @Override public void onSuccess(String content) { super.onSuccess(content); if (content!=null&&content.contains("message")){ result[0] ="登录成功"; }else { result[0] ="登录失败"; } } }); } }
好了,就到这,有需要的需要体验的请到我的git账号下载测试程序。
服务端代码:https://github.com/xiangzhihong/login
客户端代码:https://github.com/xiangzhihong/loginAndroid
相关文章推荐
- Android+struts2+json方式模拟手机登录功能
- Spring MVC配置Velocity
- Android+struts2+json方式模拟手机登录功能
- Eclipse中SVN路径中中文显示错乱问题小窍门
- Java核心技术学习笔记第五章
- eclipse 连接 hadoop集群
- Java基本数据类型
- JAVA测试题
- spring在普通类中获取session和request,springsession
- 用java写一个双向链表
- win10下eclipse中打开图片乱码解决
- JavaSE入门学习30:Java常用类之包装类
- Java实现的MD5加密
- Ubuntu上安装配置Java环境
- javaweb中使用百度地图进行定位
- java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind 【 解决方案】
- SpringMVC 400 Bad Request 问题
- MyEclipse项目左上角显示红色感叹号的解决方法
- 关闭MyEclipse的自动validation
- Java虚拟机(JVM)