第一次写博客,就记录下困扰我很久的问题,如标题所述,由于是struts注解,所以关键的注解语句贴出来
@SuppressWarnings("all")
@Controller
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
@Results({@Result(name="error",type="json")})
public class LoginForAndroid extends BaseAction{
private UserPassInfo passInfo;
@Resource(name="passInfoBiz")
private UserPassInfoBiz passInfoBiz;
//因为返回的是UserPassInfo对象,所以在其get方法中加上@JSON(serialize=false)
@JSON(serialize=false)
public UserPassInfo getPassInfo() {
return passInfo;
}
public void setPassInfo(UserPassInfo passInfo) {
this.passInfo = passInfo;
}
由于使用的是struts和spring的整合包,所以要导入
struts2-convention-plugin-2.3.4.jar
struts2-json-plugin-2.3.4.jar
在对应的方法中要加上type="json",以及params中的参数,看下面代码:
@Action(value="userLoginForAndorid",results={
@Result(type="json", name="json",params={"root","passInfo","ignoreHierarchy","false"})
})
public java.lang.String loginForAndroid() throws Exception
{
System.out.println(this.passInfo+"passInfo");
String passWord=this.passInfo.getUserPass().trim();
passWord=Tools.MD5Encode(passWord);
this.passInfo.setUserPass(passWord);
List list=this.passInfoBiz.doUserLogin(passInfo);
if(!list.isEmpty()){
this.passInfo=(UserPassInfo) list.get(0);
/*JSONObject json=JSONObject.fromObject(passInfo);
String jsonToString =json.toString();*/
/*HttpServletResponse resp=ServletActionContext.getResponse();
PrintWriter pw=resp.getWriter();
pw.write(json.toString());
pw.flush();
pw.close();*/
}
return "json";
}
andorid 端 构建httpConnection,,并访问web服务器,将返回json数据接收。
new Thread(new Runnable() { @Override public void run() { //构建默认的http客户端 HttpClient client = new DefaultHttpClient(); //http请求方式 HttpPost request; //定义消息 String msg = ""; try { //构建请求RUl的对象 request = new HttpPost(URL); //构建传递参数user+pass; List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); pairs.add(new BasicNameValuePair("passInfo.userNo", user)); pairs.add(new BasicNameValuePair("passInfo.userPass", pass)); request.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); HttpResponse response = client.execute(request); // 判断请求是否成功 if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { String result= EntityUtils.toString(entity,"UTF-8"); Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show(); InputStream in = entity.getContent(); BufferedReader buff = new BufferedReader( new InputStreamReader(in)); String line = ""; while ((line = buff.readLine()) != null) { msg += line; } Message msg1 = mHandler.obtainMessage(); msg1.what = 1000; msg1.obj = msg; mHandler.sendMessage(msg1); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start();
得到的result为:
以上所述,个人觉得比较重要的点是导入jar包,加上@ParentPackage("json-default"),@JSON(serialize=false),以及@Result(type="json", name="json",params={"root","passInfo","ignoreHierarchy","false"}),由于本人是博客小白,仅仅作为练手,格式相当乱,请各位看官们轻喷!!!