ssh学习:struts2与Android交互

struts2与Android数据交互

在实际的开发当中,Android不会只有只使用自带的sqlite微小型数据库等的单机应用;使用ssh开发的服务器也不会只有在pc平台使用。在实际应用当中,Android+struts2组合应用也是经常看到的。那么怎么来实现这两者之间的联系呢?

基本环境配置:

除了struts2所需的最基本的jar包之外还得需要以下两个包来支持:

1.\struts-2.3.24.1\lib下的struts2-json-plugin-2.3.24.1.jar  ;//基于struts2的json插件

2.\struts-2.3.24.1\lib下的json-lib-2.3-jdk15.jar   ;//json数据处理所需要的依赖

struts.xml配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<!-- 使用返回寄送字符形式 , -->
	 <!--需要将struts-default改为json-default -->
	<package name="test" extends="json-default" namespace="/">
		<action name="loginText" class="com.usc.action.AndroidTest"
			method="loginText">
			 <!--返回值类型设置为字符串(json),不设置返回页面 -->
			<result type="json"></result> 
		</action>
	</package>
</struts> 

 action类中

public class AndroidTest extends ActionSupport implements ServletRequestAware, ServletResponseAware {

	private ServletRequest request;
	private ServletResponse response;
	
	/**
	 *Android 与struts2进行数据交互(json数据)不需要返回值
	 */
	public void loginText(){
		response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
		//解析数据
		String name = request.getParameter("name");
		String psw = request.getParameter("psw");
		try {
			if(name.equals(psw)){
				//向客户端写出相应数据
				//就不写json格式的数据了,可根据需要进行json封装
				response.getWriter().write("登陆成功!");
			}else{
				response.getWriter().write("登陆失败!");
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		response = arg0;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
	}

}

 配置基本完成。看下访问的情况

在浏览器中访问http://127.0.0.1:8080//MutualAgricultrue/machine/loginText.action?name=gaosi&psw=gaosi



 

扫描二维码关注公众号,回复: 347313 查看本文章

在浏览器中已经实现了接收放回的数据,看一下Android中怎么实现的呢?

 private void liakStruts2() {
        String path = "http://169.254.153.224:8080//MutualAgricultrue/" +
                "machine/loginText.action?name=gaosi&psw=gaosi";
        try {
            URL url = new URL(path);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.setDoOutput(true);
            connection.setReadTimeout(3000);
            InputStream inputStream = connection.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            String value = new String(bytes, 0, read);
            Log.e("value", value);
            inputStream.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

 

猜你喜欢

转载自gaosililin.iteye.com/blog/2271637