Json+struts2

使用json数据交互信息

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

Json+struts2_第1张图片


web.xml的代码

  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. <?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>

项目的结构

Json+struts2_第2张图片

LoginAction.java代码

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

User.java

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

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. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <base href="<%=basePath%>">
  10. <title>My JSP 'index.jsp' starting page</title>
  11. <meta http-equiv="pragma" content="no-cache">
  12. <meta http-equiv="cache-control" content="no-cache">
  13. <meta http-equiv="expires" content="0">
  14. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  15. <meta http-equiv="description" content="This is my page">
  16. <!--
  17. <link rel="stylesheet" type="text/css" href="styles.css">
  18. -->
  19. </head>
  20. <body>
  21. <center>
  22. <form action="login" method="post">
  23. 用户名: <input type="text" name="name"><br>
  24. 密 码: <input type="password" name="pwd"><br>
  25. <input type="submit" value="登陆" name="submit"> <input type="reset" value="取消" name="reset">
  26. </form>
  27. </center>
  28. </body>
  29. </html>
  30. 测试 用户名:2222 密码:1111
Json+struts2_第3张图片

Json+struts2_第4张图片

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

Json+struts2_第5张图片

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

UrlServiceImpl.java

111.122.31.54 是本机的IP地址


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

Activity ShowMessageMainActivity.java

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

效果

Json+struts2_第6张图片

Json+struts2_第7张图片


你可能感兴趣的:(struts2)