实际应用中经常遇到访问某个页面,系统以XML格式返回"成功"或者"失败"信息,客户端根据XML格式判断显示相应的页面。
服务器端的处理完请求之后,以XML格式返回处理信息,可以在response中写回去,Action中就return null
示例如下:
- importjava.io.IOException;
- importjava.util.Iterator;
- importjava.util.List;
- importjavax.servlet.http.HttpServletRequest;
- importjavax.servlet.http.HttpServletResponse;
- importorg.apache.log4j.Logger;
- importorg.apache.struts.action.ActionForm;
- importorg.apache.struts.action.ActionForward;
- importorg.apache.struts.action.ActionMapping;
- importorg.apache.struts.actions.DispatchAction;
- importorg.jdom.Document;
- importorg.jdom.Element;
- importorg.jdom.output.Format;
- importorg.jdom.output.XMLOutputter;
- publicclassGetAllActionextendsDispatchAction{
- privateHttpServletResponseresponse=null;
- publicActionForwardqueryAlluser(ActionMappingmapping,ActionFormform,
- HttpServletRequestrequest,HttpServletResponseresponse){
- this.response=response;
- //接收查询结果
- List<UserIPInfo>userPOList=null;
- //拼装HQL语句
- Stringhql="fromUserIPInfoaspoorderbyidasc";
- //生成XML格式的root
- ElementrootElt=newElement("userInformations");
- //获得commonDao的实例
- CommonDaoIf<UserIPInfo>commonDao=newCommonDaoImpl<UserIPInfo>();
- //调用CommonDaoImpl的query方法将所有符合条件的对象存入List中
- userPOList=commonDao.query(hql);
- for(Iterator<UserIPInfo>itor=userPOList.iterator();itor.hasNext();){
- UserIPInfotemp=itor.next();
- System.out.println(temp.getAddress());
- System.out.println(temp.getId());
- System.out.println(temp.getPort());
- }
- sendAccept(rootElt,userPOList);
- returnnull;
- }
- privatevoidsendAccept(ElementrootElt,List<UserIPInfo>list){
- //遍历List中的元素,将数据加入XML中
- for(Iterator<UserIPInfo>itor=list.iterator();itor.hasNext();){
- //获取符合条件的元素
- UserIPInfotemp=itor.next();
- //生成元素<user></user>
- Elementuser=newElement("user");
- //生成元素<userId></userId>
- ElementuserId=newElement("userId");
- //生成元素<userAddress></userAddress>
- ElementuserAddress=newElement("userAddress");
- //生成元素<userPort></userPort>
- ElementuserPort=newElement("userPort");
- //设置各个标签<userId><userAddress><userPort>的值
- userId.setText(Integer.toString(temp.getId()));
- userAddress.setText(temp.getAddress());
- userPort.setText(temp.getPort());
- //加入到上级标签<user>中去
- user.addContent(userId);
- user.addContent(userAddress);
- user.addContent(userPort);
- rootElt.addContent(user);
- send(rootElt);
- privatevoidsend(ElementrootElt){
- Documentdoc=newDocument(rootElt);
- XMLOutputterout=newXMLOutputter();
- //设置文件的编码格式
- out.setFormat(Format.getCompactFormat().setEncoding("UTF-8"));
- try{
- response.getOutputStream().write(out.outputString(doc).getBytes());
- }catch(IOExceptione){
- e.printStackTrace();
- }
比较讨巧的办法:就是直接转向某jsp页面
将数据设在request中,在jsp页面直接展示
在Action中就这样处理:
?