Struts2+Android 使用struts2制作做webservice


昨天去青软那边,认识到自己的不足,只做Android是不行的.前几天公司也让做服务器.于是今天开始拿起javaEE 以后还是好好做JavaEE+Android吧


看了一下黎老师的WebService,还是很典型的应用(黎老师的课程确实很棒啊!受益一生),可惜的是他用的struts做的 也是今天中午移植到struts2 也算是练手+重温了.


进正题>

做Struts2 首先是配置工程 这个很烦人,和Android比差的很远.

首先是

web.xml没什么好说的其实就是配置struts2

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <filter>
	<!-- 定义核心Filter的名称 -->
	<filter-name>struts2</filter-name>
	<!--定义核心Filter的实现类 -->
	<filter-class>
		org.apache.struts2.dispatcher.FilterDispatcher
	</filter-class>
</filter>

<filter-mapping>
	<!--核心Filter的名称 -->
	<filter-name>struts2</filter-name>
	<!--使用该核心Filter来接受所有的Web请求 -->
	<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>


struts.xml相当于Android中的AndroidManifest.xm

l就一个action,返回两个结果,json和xml 貌似Android中现在很流行json的WebService

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="struts2" extends="struts-default">
		<action name="List" class="com.su.action.VideoListAction">
			<result name="xml">/videos.jsp</result>
			<result name="json">/jsonvideos.jsp</result>
		</action>
	</package>
</struts>


然后就是结果返回页面,先看xml的:跳转到videos.jsp 注意这里有一个struts的迭代器 可以把获取的videos处理后输出


<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><?xml version="1.0" encoding="UTF-8"?>
<videos> 
<s:iterator value="#request.videos" id="video">
	<video id="<s:property value="#video.id"/>">
	<title><s:property value="#video.title"/></title>
	<timelength><s:property value="#video.time"/></timelength>
	</video>
	</s:iterator>	
</videos>

如果返回的是json那么是jsonviedos.jsp

<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${videos}

需要注意!xml文件中

<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><?xml version="1.0" encoding="UTF-8"?>


这里尖括号直接不要有空格不然在chrome里不能识别为xml文件 我想在解析的时候会报错(什么没有文件头什么的吧)


然后是java代码部分了


首先是VideoListAction.java也就是主action 相当于activity了


package com.su.action;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.su.domain.Video;
import com.su.service.VideoService;
import com.su.service.impl.VideoServiceBean;

public class VideoListAction extends ActionSupport {
	private VideoService service = new VideoServiceBean();
	private String format;
	public String getFormat() {
		return format;
	}
	public void setFormat(String format) {
		this.format = format;
	}
	
	@Override
	public String execute() throws Exception {
		List<Video> videos = service.getLastVideos();
		if (format.equals("json")) {
			StringBuilder json = new StringBuilder();
			json.append('[');
			for(Video video : videos){ // {id:76,title:"xxxx",timelength:80}
				json.append('{');
				json.append("id:").append(video.getId()).append(',');
				json.append("title:\"").append(video.getTitle()).append("\",");
				json.append("timelength:").append(video.getTime());
				json.append('}').append(',');
			}
			json.deleteCharAt(json.length()-1);
			json.append(']');
			ServletActionContext.getRequest().setAttribute("videos", json);
			System.out.println("1111111111111111111111111111");
			return "json";
		}
		else {
	    ServletActionContext.getRequest().setAttribute("videos", videos);
		return "xml";
		}
		
	}
}

很简单json就是从videos里拼接把String放到servleactioncontext ; xml就更简单了,直接返回的list

这个是video的bean Video.java


package com.su.domain;

public class Video {
	private Integer id;
	private String title;
	private Integer time;
	
	public Video(){}
	
	public Video(Integer id, String title, Integer time) {
		this.id = id;
		this.title = title;
		this.time = time;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public Integer getTime() {
		return time;
	}
	public void setTime(Integer time) {
		this.time = time;
	}
	
}


这个是VideoServicebean.java获取videos 这个在真实使用的时候 数据是放在数据库的这个类就是来从数据库取出数据的,这里这是简单举例没有数据库


package com.su.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.su.domain.Video;
import com.su.service.VideoService;


public class VideoServiceBean implements VideoService {

	public List<Video> getLastVideos() throws Exception{
		List<Video> videos = new ArrayList<Video>();
		videos.add(new Video(78, "视频1", 90));
		videos.add(new Video(78, "视频2", 20));
		videos.add(new Video(78, "视频3", 30));
		return videos;
	}
}


VideoService.java定义的获取videos的接口


package com.su.service;

import java.util.List;

import com.su.domain.Video;

public interface VideoService {

	public List<Video> getLastVideos() throws Exception;

}


然后是Android端了这里就不详细介绍了,挺简单的解析json和xml这是黎老师的代码

主activity

package cn.itcast.videoclient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.itcast.domain.Video;
import cn.itcast.service.VideoService;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
    private ListView listView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        listView = (ListView)this.findViewById(R.id.listView);
        try {
			List<Video> videos = VideoService.getJSONLastVideos();
			List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
			for(Video video : videos){
				HashMap<String, Object> item = new HashMap<String, Object>();
				item.put("id", video.getId());
				item.put("title", video.getTitle());
				item.put("timelength", "时长:"+ video.getTime());
				data.add(item);
			}
			SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, //放入了Adapter中
					new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
			listView.setAdapter(adapter);
		} catch (Exception e) {
			Toast.makeText(MainActivity.this, "获取最新视频资讯失败", 1).show();
			Log.e("MainActivity", e.toString());
		} 
    }
}

VideoService.java从服务器获取数据

package cn.itcast.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import cn.itcast.domain.Video;
import cn.itcast.utils.StreamTool;

public class VideoService {
	/**
	 * 获取最新的视频资讯
	 * @return
	 * @throws Exception
	 */
	public static List<Video> getLastVideos() throws Exception{
		String path = "http://10.1.27.35:8080/VideoWeb2/List.action";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setReadTimeout(5*1000);
		conn.setRequestMethod("GET");
		InputStream inStream = conn.getInputStream();
		return parseXML(inStream);
	}
	
	public static List<Video> getJSONLastVideos() throws Exception{
		List<Video> videos = new ArrayList<Video>();
		String path = "http://10.1.27.35:8080/VideoWeb2/List.action?format=json";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setReadTimeout(5*1000);
		conn.setRequestMethod("GET");
		InputStream inStream = conn.getInputStream();
		byte[] data = StreamTool.readInputStream(inStream);
		String json = new String(data);
		JSONArray array = new JSONArray(json);
		for(int i=0 ; i < array.length() ; i++){
			JSONObject item = array.getJSONObject(i);
			int id = item.getInt("id");
			String title = item.getString("title");
			int timelength = item.getInt("timelength");
			videos.add(new Video(id, title, timelength));
		}
		return videos;
	}
	/**
	 * 解析服务器返回的协议,得到视频资讯
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	private static List<Video> parseXML(InputStream inStream) throws Exception{
		List<Video> videos = null;
		Video video = null;
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(inStream, "UTF-8");
		int eventType = parser.getEventType();//产生第一个事件
		while(eventType!=XmlPullParser.END_DOCUMENT){//只要不是文档结束事件
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				videos = new ArrayList<Video>();
				break;
	
			case XmlPullParser.START_TAG:
				String name = parser.getName();//获取解析器当前指向的元素的名称
				if("video".equals(name)){
					video = new Video();
					video.setId(new Integer(parser.getAttributeValue(0)));
				}
				if(video!=null){
					if("title".equals(name)){
						video.setTitle(parser.nextText());//获取解析器当前指向元素的下一个文本节点的值
					}
					if("timelength".equals(name)){
						video.setTime(new Integer(parser.nextText()));
					}
				}
				break;
				
			case XmlPullParser.END_TAG:
				if("video".equals(parser.getName())){
					videos.add(video);
					video = null;
				}
				break;
			}
			eventType = parser.next();
		}
		return videos;
	}
}

StreamTool.java 这个类是处理instream的

package cn.itcast.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {

	/**
	 * 从输入流中获取数据输入一个input 输出一个byte[],获取的数据就可以通过new String(data)转换为String
	 * @param inStream 输入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while( (len=inStream.read(buffer)) != -1 ){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
}

也有一个video.java

package cn.itcast.domain;

public class Video {//video的bean
	private Integer id;
	private String title;
	private Integer time;
	
	public Video(){}
	
	public Video(Integer id, String title, Integer time) {
		this.id = id;
		this.title = title;
		this.time = time;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public Integer getTime() {
		return time;
	}
	public void setTime(Integer time) {
		this.time = time;
	}
	
}
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值