WebService分布式开发

WebService:用来跨语言传递数据。
数据交互是通过XML来完成。

使用WebService开发一般为以下几种情况:
1) 政府或大型企业项目(要求保密性比较高的项目):为了防止后台数据泄露,由政府机构提供后台的接口,程序员开发前台项目内容,通过调用该接口中的方法来操作数据库。最早的WebService项目一般电信系统的项目。
2) 子公司与母公司项目:只使用一套后台代码,使用多套前台代码来调用后台代码的方法。
3) 两个公司合作开发:一个公司编写前台界面,用来显示数据,另一个公司编写后台DAO部分代码,用来查询数据库。

分布式开发:建立多个项目(区分前后台项目),各个项目同时开始开发,前后台项目通过一个或多个接口进行沟通。理论上开发效率会比普通的项目要高,但由于沟通问题,一般都会导致开发效率降低。

XFire:是WebService的一个实现框架,其他的类似AXIS等也是WebService的实现框架。
XFire是Java开发WebService最容易的一个框架,自带Spring框架核心支持包,支持与Spring + Hibernate联合开发。

开发一个简单的WebService程序,使用MyEclipse开发工具,由于MyEclipse自带最新版本的XFire框架支持,因此不需要单独下载XFire的支持包。


1、建立项目
注意:不是Web项目了,改为WebService项目了



这里要配置发布的Web服务的默认路径,默认为services虚拟目录下。
services.xml(XFire核心配置文件),所有发布的服务都是通过该文件完成的。


加入jar包支持,注意开发服务器端时,不需要单独加入客户端支持jar包。
XFire 1.1jar包也不需要加入

2、加入Hibernate支持





3、生成映射




package org.mldn.lin.pojo;



public class Menu implements java.io.Serializable {

// Fields

private Integer id;

private String title;

private Integer upid;

private String url;

// Constructors


public Menu() {
}


public Menu(String title, Integer upid) {
  this.title = title;
  this.upid = upid;
}


public Menu(String title, Integer upid, String url) {
  this.title = title;
  this.upid = upid;
  this.url = url;
}

// Property accessors

public Integer getId() {
  return this.id;
}

public void setId(Integer id) {
  this.id = id;
}

public String getTitle() {
  return this.title;
}

public void setTitle(String title) {
  this.title = title;
}

public Integer getUpid() {
  return this.upid;
}

public void setUpid(Integer upid) {
  this.upid = upid;
}

public String getUrl() {
  return this.url;
}

public void setUrl(String url) {
  this.url = url;
}

}

4、建立数据库连接类
package org.mldn.dbc;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class DataBaseConnection {
private static DataBaseConnection instance=new DataBaseConnection();

private SessionFactory sf;

private Session session;

private DataBaseConnection(){
  sf = new Configuration().configure().buildSessionFactory();
}

public static DataBaseConnection getInstance(){
  return instance;
}

public Session getConnection(){
  if(this.session==null || !this.session.isConnected()){
   this.session=sf.openSession();
  }
  return this.session;
}
public void colse(){
  if(this.session!=null){
   this.session.close();
  }
}
public void commit(){
  if(this.session!=null){
   this.session.beginTransaction().commit();
  }
}
public void rollback(){
  if(this.session!=null){
   this.session.beginTransaction().rollback();
  }
}
}



5、建立要发布的接口与实现类、代理类

package org.mldn.lin.dao;

import java.util.List;

import org.mldn.lin.pojo.Menu;

public interface MenuDAO {
public List<Menu> findAll(int cp,int ls,String keyword)throws Exception;
public int getAllCount(String keyword)throws Exception;
}

package org.mldn.lin.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.mldn.dbc.DataBaseConnection;
import org.mldn.lin.dao.MenuDAO;
import org.mldn.lin.pojo.Menu;

public class MenuDAOImpl implements MenuDAO {

private DataBaseConnection instance=DataBaseConnection.getInstance();

public List<Menu> findAll(int cp, int ls, String keyword) throws Exception {
  // TODO Auto-generated method stub
  String hql="FROM Menu WHERE title LIKE ?";
  Query q=this.instance.getConnection().createQuery(hql);
  q.setString(0, "%"+keyword+"%");
  q.setFirstResult((cp-1)*ls);
  q.setMaxResults(ls);
 
  return q.list();
}

public int getAllCount(String keyword) throws Exception {
  // TODO Auto-generated method stub
  String hql="SELECT count(*) FROM Menu WHERE title LIKE ?";
  Query q=this.instance.getConnection().createQuery(hql);
  q.setString(0, "%"+keyword+"%");
 
  List all =q.list();
  if(all!=null && all.size()>0){
   return (Integer)all.get(0);
  }
  return 0;
}

}

package org.mldn.lin.dao.proxy;

import java.util.List;

import org.mldn.dbc.DataBaseConnection;
import org.mldn.lin.dao.MenuDAO;
import org.mldn.lin.dao.impl.MenuDAOImpl;
import org.mldn.lin.pojo.Menu;

public class MenuDAOProxy implements MenuDAO{
private DataBaseConnection instance=DataBaseConnection.getInstance();
private MenuDAO menudao;

public MenuDAOProxy(){
  this.menudao=new MenuDAOImpl();
}

public List<Menu> findAll(int cp, int ls, String keyword) throws Exception {
  // TODO Auto-generated method stub
  List all=null;
  try {
   all=this.menudao.findAll(cp, ls, keyword);
  } catch (RuntimeException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   this.instance.colse();
  }
  return all;
}

public int getAllCount(String keyword) throws Exception {
  // TODO Auto-generated method stub
  int count=0;
  try {
   count=this.menudao.getAllCount(keyword);
  } catch (RuntimeException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   this.instance.colse();
  }
  return count;
}

}


6、进行服务的发布
在src下 new   Other
选择 MyEclipse  Web Services  WebService

选择要发布服务的项目,并使用JavaBean的形式发布服务



配置接口与实现类,设置发布的XML的样式及Servlet保存范围。

完成后会在services.xml中加入以下内容
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xfire.codehaus.org/config/1.0">

<service>
  <name>FirstXFire</name>
  <serviceClass>org.mldn.lin.dao.MenuDAO</serviceClass>
  <implementationClass>
   org.mldn.lin.dao.proxy.MenuDAOProxy
  </implementationClass>
  <style>rpc</style>
  <use>literal</use>
  <scope>session</scope>
</service></beans>


7、部署项目
注意这里必须使用MyEclipse自动部署,因为XFire的支持jar包加入方式不是直接拷贝到WEB-INF下的lib下的

8、测试

通过访问http://localhost:8080/XFireBackLinDemo/services/FirstXFire?wsdl可以查看到发布的Web服务

前台代码
1、建立项目




加入所有jar包

2、删除web.xml中的XFireServlet配置
  <servlet>
    <servlet-name>XFireServlet</servlet-name>
    <servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>XFireServlet</servlet-name>
    <url-pattern>/services
package org.mldn.lin.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.mldn.lin.pojo.Menu;


public class MenuForm extends ActionForm {



private String keyword="";


private int cp=1;


private int ls=5;


private String status;


private Menu menu=new Menu();




public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
  // TODO Auto-generated method stub
  return null;
}


public void reset(ActionMapping mapping, HttpServletRequest request) {
  // TODO Auto-generated method stub
}


public String getKeyword() {
  return keyword;
}


public void setKeyword(String keyword) {
  this.keyword = keyword;
}


public int getCp() {
  return cp;
}


public void setCp(int cp) {
  this.cp = cp;
}


public int getLs() {
  return ls;
}


public void setLs(int ls) {
  this.ls = ls;
}


public String getStatus() {
  return status;
}


public void setStatus(String status) {
  this.status = status;
}


public Menu getMenu() {
  return menu;
}


public void setMenu(Menu menu) {
  this.menu = menu;
}
}


6、DAOFactory
package org.mldn.lin.factory;

import org.codehaus.xfire.XFireFactory;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;

public class DAOFactory {
public static Object getInstance(Class clazz, String url) throws Exception {
  Object obj = null;
  Service srvcModel = new ObjectServiceFactory().create(clazz);
  // 建立XFire工厂
  XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
    .newInstance().getXFire());

  obj = factory.create(srvcModel, url);
  return obj;
}
}

7、编写Action

package org.mldn.lin.struts.action;


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

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.mldn.lin.dao.MenuDAO;
import org.mldn.lin.factory.DAOFactory;
import org.mldn.lin.pojo.Menu;
import org.mldn.lin.struts.form.MenuForm;


public class MenuAction extends DispatchAction {

public ActionForward list(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  MenuForm menuForm = (MenuForm) form;// TODO Auto-generated method stub
  MenuDAO menudao=null;
  Menu[] all=null;
  int allRecorders=0;
  int allPages=0;
  List allPage=new ArrayList();
  try {
   menudao=(MenuDAO) DAOFactory.getInstance(MenuDAO.class, "http://localhost:8080/XFireBackLinDemo/services/FirstXFire");
   all=menudao.findAll(menuForm.getCp(), menuForm.getLs(), menuForm.getKeyword());
   allRecorders=menudao.getAllCount(menuForm.getKeyword());
   allPages = (allRecorders - 1) / menuForm.getLs() + 1;
   for (int i = 1; i <= allPages; i++) {
    allPage.add(i);
   }
  
   request.setAttribute("cp", menuForm.getCp());
   request.setAttribute("ls", menuForm.getLs());
   request.setAttribute("keyword", menuForm.getKeyword());
   request.setAttribute("all", all);
   request.setAttribute("allRecorders", allRecorders);
   request.setAttribute("allPages", allPages);
   request.setAttribute("allPage", allPage);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return mapping.findForward("list");
}
}

8、配置Action
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="menuForm" type="org.mldn.lin.struts.form.MenuForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      attribute="menuForm"
      input="/error.jsp"
      name="menuForm"
      parameter="status"
      path="/menu"
      scope="request"
      type="org.mldn.lin.struts.action.MenuAction">
      <forward name="list" path="/list.jsp" />
    </action>

  </action-mappings>

  <message-resources parameter="org.mldn.lin.struts.ApplicationResources" />
</struts-config>




9、编写前台页面
<%@ page language="java" pageEncoding="GBK"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>

  <body>
    <center>
    <a href="menu.do?status=list">列表显示</a>
    </center>
  </body>
</html>
<%@ page language="java" pageEncoding="GBK"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript">
  function changeCp(cp){
   document.splitForm.cp.value = cp ;
   // 提交表单
   document.splitForm.submit() ;
  }
  function changeLs(ls){
   document.splitForm.ls.value = ls ;
   document.splitForm.cp.value =1;
   document.splitForm.submit() ;
  }
  function changeKeyword(){
   document.splitForm.cp.value =1;
   document.splitForm.submit() ;
  }
</script>  
  </head>

  <body>
    <center>
    <table border="0">
     <tr>
      <td>编号</td>
      <td>标题</td>
      <td>UPID</td>
      <td>url</td>
     </tr>
     <logic:present name="all" scope="request">
     <logic:iterate id="tempt" name="all" scope="request">
     <tr>
      <td>${tempt.id }</td>
      <td>${tempt.title }</td>
      <td>${tempt.upid }</td>
      <td>${tempt.url }</td>
     </tr>
     </logic:iterate>
     </logic:present>
     <tr>
     <td colspan="4">
      <form action="${pageContext.request.contextPath }/menu.do" method="post" id="splitForm" name="splitForm">
         <input type="hidden" name="ls" value="${requestScope.ls }">
         <input type="hidden" name="cp" value="${requestScope.cp }">
         <input type="hidden" name="status" value="list">
        
     <img src="${pageContext.request.contextPath }/images/img/Library-button-1.gif" width="50" height="20" border="0" onClick="changeCp(1);"/>
     <img src="${pageContext.request.contextPath }/images/img/Library-button-2.gif" width="50" height="20" border="0" onClick="changeCp(${requestScope.cp==1?1:(requestScope.cp-1) });"/>
     <img src="${pageContext.request.contextPath }/images/img/Library-button-4.gif" width="50" height="20" border="0" onClick="changeCp(${requestScope.cp==requestScope.allPages?requestScope.allPages:(requestScope.cp+1) });"/>
     <img src="${pageContext.request.contextPath }/images/img/Library-button-5.gif" width="50" height="20" border="0" onClick="changeCp(${requestScope.allPages });"/>
     共${requestScope.allRecorders }条&nbsp;${requestScope.allPages }页&nbsp; 第${requestScope.cp }页&nbsp;跳转到第
       <select name="mycp" onchange="changeCp(this.value)">
       <logic:present name="allPage" scope="request">
       <logic:iterate id="page1" name="allPage" scope="request">
       <option value="${page1 }" ${page1==cp?"selected":""}>${page1 }</option>
       </logic:iterate>
       </logic:present>
    </select>页&nbsp;&nbsp;每页显示
    <select name="myls" onchange="changeLs(this.value)">
     <option value="2" ${requestScope.ls==2?"selected":"" }>2</option>
     <option value="5" ${requestScope.ls==5?"selected":"" }>5</option>
     <option value="10" ${requestScope.ls==10?"selected":"" }>10</option>
     <option value="20" ${requestScope.ls==20?"selected":"" }>20</option>
    </select>
   </form>
     </td>
     </tr>
    </table>
  
    </center>
  </body>
</html>

你可能感兴趣的:(DAO,apache,Hibernate,webservice,struts)