Json+struts2

晨曦之光 发布于 2012/04/10 18:48
阅读 412
收藏 0

使用json数据交互信息

首先搭配SSH服务端,目前只用了Struts2,首先导入包,下面是需要的包



web.xml的代码

  1. <?xmlversion="1.0"encoding="UTF-8"?> 
  2. <web-app version="2.5"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
  7.   <welcome-file-list> 
  8.     <welcome-file>index.jsp</welcome-file> 
  9.   </welcome-file-list> 
  10.     <filter> 
  11.     <filter-name>struts2</filter-name> 
  12.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 
  13.   </filter> 
  14.   <filter-mapping> 
  15.     <filter-name>struts2</filter-name> 
  16.     <url-pattern>/*</url-pattern> 
  17.   </filter-mapping> 
  18. </web-app> 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <welcome-file-list>  
  8.     <welcome-file>index.jsp</welcome-file>  
  9.   </welcome-file-list>  
  10.     <filter>  
  11.     <filter-name>struts2</filter-name>  
  12.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  13.   </filter>  
  14.   <filter-mapping>  
  15.     <filter-name>struts2</filter-name>  
  16.     <url-pattern>/*</url-pattern>  
  17.   </filter-mapping>  
  18.  </web-app>  

struts.xml代码

  1. <?xmlversion="1.0"encoding="UTF-8"?> 
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 
  3. <struts> 
  4.   <packagename="as"extends="json-default"> 
  5.     <actionname="login"class="as.action.LoginAction"method="login"> 
  6.      <resulttype="json"></result> 
  7.     </action> 
  8.   </package> 
  9. </struts>     
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">  
  3. <struts>  
  4.   <package name="as" extends="json-default">  
  5.     <action name="login" class="as.action.LoginAction" method="login">  
  6.      <result type="json" ></result>  
  7.     </action>  
  8.   </package>  
  9. </struts>      

项目的结构

LoginAction.java代码

  1. package as.action; 
  2.  
  3. import java.util.HashMap; 
  4. import java.util.Map; 
  5.  
  6. import javax.servlet.http.HttpServletRequest; 
  7. import javax.servlet.http.HttpServletResponse; 
  8.  
  9. import org.apache.struts2.interceptor.ServletRequestAware; 
  10. import org.apache.struts2.interceptor.ServletResponseAware; 
  11.  
  12. import net.sf.json.JSONObject; 
  13.  
  14. import as.model.User; 
  15.  
  16. import com.opensymphony.xwork2.ActionSupport; 
  17. import com.opensymphony.xwork2.ModelDriven; 
  18.  
  19. public class LoginActionextends ActionSupport implements ServletResponseAware ,ServletRequestAware,ModelDriven<User>{ 
  20. private User user; 
  21. private HttpServletResponse response; 
  22. private HttpServletRequest request; 
  23. public User getUser() { 
  24.     return user; 
  25. public void setUser(User user) { 
  26.     this.user = user; 
  27. public void setServletResponse(HttpServletResponse arg0) { 
  28.     // TODO Auto-generated method stub 
  29.     this.response = arg0; 
  30.  
  31. public void setServletRequest(HttpServletRequest arg0) { 
  32.     // TODO Auto-generated method stub 
  33.     this.request=arg0; 
  34.  
  35. public void login() { 
  36.     try
  37.         // TODO Auto-generated method stub 
  38.         this.response.setContentType("text/html;charset=utf-8");   
  39.         this.response.setCharacterEncoding("UTF-8");   
  40.         JSONObject json=new JSONObject(); 
  41.         Map map=new HashMap<Object, String>(); 
  42.         map.put("name", user.getName()); 
  43.         map.put("pwd", user.getPwd()); 
  44.         json.put("LoginInfo", map); 
  45.         response.getWriter().write(json.toString()); 
  46.     } catch (Exception e) { 
  47.         // TODO: handle exception 
  48.         e.printStackTrace(); 
  49.     } 
  50.      
  51. public User getModel() { 
  52.     // TODO Auto-generated method stub 
  53.     if (user==null) { 
  54.         return user=new User(); 
  55.     } 
  56.     return user; 
  57. }    
  1. package as.action;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import org.apache.struts2.interceptor.ServletRequestAware;  
  10. import org.apache.struts2.interceptor.ServletResponseAware;  
  11.   
  12. import net.sf.json.JSONObject;  
  13.   
  14. import as.model.User;  
  15.   
  16. import com.opensymphony.xwork2.ActionSupport;  
  17. import com.opensymphony.xwork2.ModelDriven;  
  18.   
  19. public class LoginAction extends ActionSupport implements ServletResponseAware ,ServletRequestAware,ModelDriven<User>{  
  20. private User user;  
  21. private HttpServletResponse response;  
  22. private HttpServletRequest request;  
  23. public User getUser() {  
  24.     return user;  
  25. }  
  26. public void setUser(User user) {  
  27.     this.user = user;  
  28. }  
  29. public void setServletResponse(HttpServletResponse arg0) {  
  30.     // TODO Auto-generated method stub  
  31.     this.response = arg0;  
  32. }  
  33.   
  34. public void setServletRequest(HttpServletRequest arg0) {  
  35.     // TODO Auto-generated method stub  
  36.     this.request=arg0;  
  37. }  
  38.   
  39. public void login() {  
  40.     try {  
  41.         // TODO Auto-generated method stub  
  42.         this.response.setContentType("text/html;charset=utf-8");    
  43.         this.response.setCharacterEncoding("UTF-8");    
  44.         JSONObject json=new JSONObject();  
  45.         Map map=new HashMap<Object, String>();  
  46.         map.put("name", user.getName());  
  47.         map.put("pwd", user.getPwd());  
  48.         json.put("LoginInfo", map);  
  49.         response.getWriter().write(json.toString());  
  50.     } catch (Exception e) {  
  51.         // TODO: handle exception  
  52.         e.printStackTrace();  
  53.     }  
  54.       
  55.  }  
  56. public User getModel() {  
  57.     // TODO Auto-generated method stub  
  58.     if (user==null) {  
  59.         return user=new User();  
  60.     }  
  61.     return user;  
  62. }     
  63. }  

User.java

  1. package as.model; 
  2.  
  3. public class User { 
  4.     private String name; 
  5.     private String pwd; 
  6.     public String getName() { 
  7.         return name; 
  8.     } 
  9.     public void setName(String name) { 
  10.         this.name = name; 
  11.     } 
  12.     public String getPwd() { 
  13.         return pwd; 
  14.     } 
  15.     public void setPwd(String pwd) { 
  16.         this.pwd = pwd; 
  17.     } 
  18.      
  1. package as.model;  
  2.   
  3. public class User {  
  4.     private String name;  
  5.     private String pwd;  
  6.     public String getName() {  
  7.         return name;  
  8.     }  
  9.     public void setName(String name) {  
  10.         this.name = name;  
  11.     }  
  12.     public String getPwd() {  
  13.         return pwd;  
  14.     }  
  15.     public void setPwd(String pwd) {  
  16.         this.pwd = pwd;  
  17.     }  
  18.       
  19. }  

view层 index.jsp  代码

  1. <%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%> 
  2. <
  3. String path = request.getContextPath(); 
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
  5. %> 
  6.  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  8. <html> 
  9.   <head> 
  10.     <base href="<%=basePath%>"> 
  11.      
  12.     <title>My JSP 'index.jsp' starting page</title> 
  13.     <metahttp-equiv="pragma"content="no-cache"> 
  14.     <meta http-equiv="cache-control"content="no-cache"> 
  15.     <metahttp-equiv="expires"content="0">     
  16.     <meta http-equiv="keywords"content="keyword1,keyword2,keyword3"> 
  17.     <metahttp-equiv="description"content="This is my page"> 
  18.     <!--
  19.     <link rel="stylesheet" type="text/css" href="styles.css">
  20.     --> 
  21.   </head> 
  22.    
  23.   <body> 
  24.    <center> 
  25.     <formaction="login"method="post"> 
  26.    用户名: <inputtype="text"name="name"><br> 
  27.    密  码: <inputtype="password"name="pwd"><br>   
  28.    <input type="submit"value="登陆"name="submit">    <input type="reset"value="取消"name="reset"> 
  29.     </form> 
  30.     </center> 
  31.   </body> 
  32. </html> 
  33. 测试  用户名:2222 密码:1111  
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.    <center>  
  25.     <form action="login" method="post">  
  26.    用户名: <input type="text" name="name"><br>  
  27.    密  码: <input type="password" name="pwd"><br>    
  28.    <input type="submit" value="登陆" name="submit">     <input type="reset" value="取消" name="reset">  
  29.     </form>  
  30.     </center>  
  31.   </body>  
  32. </html>  
  33. 测试  用户名:2222 密码:1111   

现在在android上面测试,Android 项目构架

由于是post 请求,这里就给出Android post 请求的代码

UrlServiceImpl.java

111.122.31.54 是本机的IP地址


  1. package dlnu.message.serviceimpl; 
  2.  
  3. import java.io.IOException; 
  4. import java.util.ArrayList; 
  5. import java.util.List; 
  6.  
  7. import org.apache.http.HttpResponse; 
  8. import org.apache.http.NameValuePair; 
  9. import org.apache.http.client.ClientProtocolException; 
  10. import org.apache.http.client.HttpClient; 
  11. import org.apache.http.client.entity.UrlEncodedFormEntity; 
  12. import org.apache.http.client.methods.HttpPost; 
  13. import org.apache.http.impl.client.DefaultHttpClient; 
  14. import org.apache.http.message.BasicNameValuePair; 
  15. import org.apache.http.params.CoreConnectionPNames; 
  16. import org.apache.http.protocol.HTTP; 
  17. import org.apache.http.util.EntityUtils; 
  18.  
  19. import dlnu.message.service.UrlService; 
  20.  
  21. public class UrlServiceImplimplements UrlService{ 
  22.  
  23.     @Override 
  24.     public String Login(String name, String pwd) { 
  25.         // TODO Auto-generated method stub 
  26.         String uriAPI = "http://111.122.31.54:8080/AndroidService/login.action";  
  27.           /*建立HTTPost对象*/ 
  28.           HttpPost httpRequest = new HttpPost(uriAPI); 
  29.           HttpClient client=new DefaultHttpClient(); 
  30.           /*
  31.            * NameValuePair实现请求参数的封装
  32.           */ 
  33.           //System.out.println("--------"+name+"-----------"+pwd); 
  34.           List <NameValuePair> params = new ArrayList <NameValuePair>(2); 
  35.            
  36.           params.add(new BasicNameValuePair("name", name));//返回JSon数据  如果是xml 返回的就是XML数据 
  37.           params.add(new BasicNameValuePair("pwd", pwd)); 
  38.          
  39.           String strResult=null
  40.           try 
  41.           { 
  42.            
  43.             /* 添加请求参数到请求对象*/ 
  44.             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
  45.             /* 处理超时*/ 
  46.             client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000); 
  47.             /*发送请求并等待响应*/ 
  48.             HttpResponse httpResponse = client.execute(httpRequest); 
  49.             /*若状态码为200 ok*/ 
  50.             if(httpResponse.getStatusLine().getStatusCode() ==200)  
  51.             { 
  52.               /*读返回数据  去掉两头不要的参数*/ 
  53.                strResult= EntityUtils.toString(httpResponse.getEntity()); 
  54.             } 
  55.             else 
  56.             { 
  57.                 System.err.println("Error Response: "+httpResponse.getStatusLine().toString()); 
  58.                 strResult=null
  59.             } 
  60.           } 
  61.           catch (ClientProtocolException e) 
  62.           {  
  63.             e.printStackTrace(); 
  64.           } 
  65.           catch (IOException e) 
  66.           {  
  67.             
  68.             e.printStackTrace(); 
  69.           } 
  70.           catch (Exception e) 
  71.           {  
  72.            
  73.             e.printStackTrace();  
  74.           }   
  75.           return strResult; 
  76.     } 
  77.  
  78.  
  1. package dlnu.message.serviceimpl;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.ClientProtocolException;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  12. import org.apache.http.client.methods.HttpPost;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.message.BasicNameValuePair;  
  15. import org.apache.http.params.CoreConnectionPNames;  
  16. import org.apache.http.protocol.HTTP;  
  17. import org.apache.http.util.EntityUtils;  
  18.   
  19. import dlnu.message.service.UrlService;  
  20.   
  21. public class UrlServiceImpl implements UrlService{  
  22.   
  23.     @Override  
  24.     public String Login(String name, String pwd) {  
  25.         // TODO Auto-generated method stub  
  26.         String uriAPI = "http://111.122.31.54:8080/AndroidService/login.action";   
  27.           /*建立HTTPost对象*/  
  28.           HttpPost httpRequest = new HttpPost(uriAPI);  
  29.           HttpClient client=new DefaultHttpClient();  
  30.           /* 
  31.            * NameValuePair实现请求参数的封装 
  32.           */  
  33.           //System.out.println("--------"+name+"-----------"+pwd);  
  34.           List <NameValuePair> params = new ArrayList <NameValuePair>(2);  
  35.             
  36.           params.add(new BasicNameValuePair("name", name));//返回JSon数据  如果是xml 返回的就是XML数据  
  37.           params.add(new BasicNameValuePair("pwd", pwd));  
  38.           
  39.           String strResult=null;  
  40.           try  
  41.           {  
  42.             
  43.             /* 添加请求参数到请求对象*/  
  44.             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
  45.             /* 处理超时*/  
  46.             client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);  
  47.             /*发送请求并等待响应*/  
  48.             HttpResponse httpResponse = client.execute(httpRequest);  
  49.             /*若状态码为200 ok*/  
  50.             if(httpResponse.getStatusLine().getStatusCode() == 200)   
  51.             {  
  52.               /*读返回数据  去掉两头不要的参数*/  
  53.                strResult= EntityUtils.toString(httpResponse.getEntity());  
  54.             }  
  55.             else  
  56.             {  
  57.                 System.err.println("Error Response: "+httpResponse.getStatusLine().toString());  
  58.                 strResult=null;  
  59.             }  
  60.           }  
  61.           catch (ClientProtocolException e)  
  62.           {   
  63.             e.printStackTrace();  
  64.           }  
  65.           catch (IOException e)  
  66.           {   
  67.              
  68.             e.printStackTrace();  
  69.           }  
  70.           catch (Exception e)  
  71.           {   
  72.             
  73.             e.printStackTrace();   
  74.           }    
  75.           return strResult;  
  76.     }  
  77.   
  78.   
  79. }  

Activity   ShowMessageMainActivity.java

  1. package dlnu.message.activity; 
  2.  
  3. import dlnu.message.model.User; 
  4. import dlnu.message.service.UserService; 
  5. import dlnu.message.serviceimpl.JsonServiceImpl; 
  6. import dlnu.message.serviceimpl.UserServiceImpl; 
  7. import android.app.Activity; 
  8. import android.os.Bundle; 
  9. import android.view.View; 
  10. import android.view.View.OnClickListener; 
  11. import android.widget.Button; 
  12. import android.widget.EditText; 
  13. import android.widget.Toast; 
  14.  
  15. public class ShowMessageMainActivityextends Activity { 
  16.     /** Called when the activity is first created. */ 
  17.     private EditText namEditText; 
  18.     private EditText pwdEditText; 
  19.     private Button submitButton; 
  20.     @Override 
  21.     public void onCreate(Bundle savedInstanceState) { 
  22.         super.onCreate(savedInstanceState); 
  23.         setContentView(R.layout.showmessageactivity); 
  24.         namEditText=(EditText) findViewById(R.id.nameditText1); 
  25.         pwdEditText=(EditText) findViewById(R.id.pwdseditText2); 
  26.         submitButton=(Button) findViewById(R.id.submitbutton1); 
  27.         submitButton.setOnClickListener(new ButtonListener()); 
  28.     } 
  29.     class ButtonListenerimplements OnClickListener{ 
  30.  
  31.         @Override 
  32.         public void onClick(View v) { 
  33.             // TODO Auto-generated method stub 
  34.             String name=namEditText.getText().toString().trim(); 
  35.             String pwd=pwdEditText.getText().toString().trim(); 
  36.             UserService userService=new UserServiceImpl(); 
  37.             JsonServiceImpl service=new JsonServiceImpl(); 
  38.             String string=userService.UserLogin(name, pwd); 
  39.             User user=new User(); 
  40.             user=service.UserLoginJsonAnalysis(string); 
  41.             Toast.makeText(ShowMessageMainActivity.this, user.getName()+"        "+user.getPwd(),8000).show(); 
  42.         } 
  43.          
  44.     } 
  1. package dlnu.message.activity;  
  2.   
  3. import dlnu.message.model.User;  
  4. import dlnu.message.service.UserService;  
  5. import dlnu.message.serviceimpl.JsonServiceImpl;  
  6. import dlnu.message.serviceimpl.UserServiceImpl;  
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.widget.Button;  
  12. import android.widget.EditText;  
  13. import android.widget.Toast;  
  14.   
  15. public class ShowMessageMainActivity extends Activity {  
  16.     /** Called when the activity is first created. */  
  17.     private EditText namEditText;  
  18.     private EditText pwdEditText;  
  19.     private Button submitButton;  
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.showmessageactivity);  
  24.         namEditText=(EditText) findViewById(R.id.nameditText1);  
  25.         pwdEditText=(EditText) findViewById(R.id.pwdseditText2);  
  26.         submitButton=(Button) findViewById(R.id.submitbutton1);  
  27.         submitButton.setOnClickListener(new ButtonListener());  
  28.     }  
  29.     class ButtonListener implements OnClickListener{  
  30.   
  31.         @Override  
  32.         public void onClick(View v) {  
  33.             // TODO Auto-generated method stub  
  34.             String name=namEditText.getText().toString().trim();  
  35.             String pwd=pwdEditText.getText().toString().trim();  
  36.             UserService userService=new UserServiceImpl();  
  37.             JsonServiceImpl service=new JsonServiceImpl();  
  38.             String string=userService.UserLogin(name, pwd);  
  39.             User user=new User();  
  40.             user=service.UserLoginJsonAnalysis(string);  
  41.             Toast.makeText(ShowMessageMainActivity.this, user.getName()+"        "+user.getPwd(), 8000).show();  
  42.         }  
  43.           
  44.     }  
  45. }  

效果




原文链接:http://blog.csdn.net/chengchanglun/article/details/7440963
加载中
返回顶部
顶部