使用axis1+spring+hibernate搭建webservice框架

原创不易,转载请注明出处:使用axis1+spring+hibernate搭建webservice框架

代码下载地址:http://www.zuidaima.com/share/1724478299180032.htm


写在前面的话:

       网上的教程大多都是使用wsdl2java工具构建webservice。本文则直接采用编辑server-config.wsdd来发布webservice,相比而言,可以比较快速的部署一个项目,适应工作需要。

   本教程模拟提供用户接口用于和别的系统结合,主要功能包括接受用户的增删改查。

一数据库创建
    创建数据库webservice

,创建用户表user

用户表内容如下:

CREATE TABLE ` user ` (
 `uid` int ( ) unsigned NOT NULL auto_increment,
 `name` varchar ( ) NOT NULL default '' ,
 `password` varchar ( ) NOT NULL default '' ,
 `nickname` varchar ( ) NOT NULL default '' ,
 PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET= gbk;

(您也可以直接使用附件中的sql文件创建数据库)

 

二新建web项目,搭建spring+hibernate框架。

1)新建用户模型,User类,如下:

package com.zuidaima.model;

public class User {
	/*
	 * 用户属性,分别对应user表
	 */
	/*
	 * 用户id
	 */
	private Integer uid;
	/*
	 * 用户名
	 */
	private String name;
	/*
	 * 密码
	 */
	private String password;
	/*
	 * 用户昵称
	 */
	private String nickname;

	/*
	 * 必须提供一不带参数的构造方法,以供hibernate初始化User
	 */
	public User() {

	}

	/*
	 * 使用参数构建User
	 */
	public User(String name, String password, String nickname) {
		this.name = name;
		this.password = password;
		this.nickname = nickname;
	}

	public Integer getUid() {
		return uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
}

另外user的配置文件User.hbm.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<hibernate-mapping>
	<class name="com.zuidaima.model.User" table="user">
		<id name="uid" type="java.lang.Integer" column="UID">
			<generator class="native"></generator>
		</id>
		<property name="name" type="java.lang.String" column="NAME"
			length="45" insert="true" update="true" />
		<property name="password" type="java.lang.String" column="PASSWORD"
			length="45" insert="true" update="true" />
		<property name="nickname" type="java.lang.String" column="NICKNAME"
			length="45" insert="true" update="true" />
	</class>
</hibernate-mapping>

2)新建DAO,UserDAO类,如下:

package com.zuidaima.dao;

import java.util.List;

import org.springframework.orm.hibernate.support.HibernateDaoSupport;
import com.zuidaima.model.User;

public class UserDAO extends HibernateDaoSupport {
	public User getUser(int uid) {
		return (User) getHibernateTemplate().get(User.class, new Integer(uid));
	}

	/**
	 * 添加用户
	 * 
	 * @param user
	 */
	public void saveUser(User user) {
		getHibernateTemplate().save(user);
	}

	/**
	 * 删除用户
	 * 
	 * @param uid
	 */
	public void deleteUser(int uid) {
		StringBuffer strBuf = new StringBuffer();
		strBuf.append("from User as u where u.uid=");
		strBuf.append(uid);
		getHibernateTemplate().delete(strBuf.toString());
	}

	/**
	 * 更新用户
	 * 
	 * @param user
	 */
	public void updateUser(User user) {
		getHibernateTemplate().saveOrUpdate(user);
	}

	/**
	 * 根据用户名查找用户
	 * 
	 * @param name
	 * @return user or null
	 */
	/*
	 * return null if can't find
	 */
	public User getUserByName(String name) {
		StringBuffer strBuf = new StringBuffer();
		strBuf.append("select u from User as u where u.name='");
		strBuf.append(name);
		strBuf.append("'");
		List tempList = getHibernateTemplate().find(strBuf.toString());
		if (tempList != null && tempList.size() > 0) {
			return (User) tempList.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 用户列表
	 * 
	 * @return user List
	 */
	public List listUser() {
		StringBuffer strBuf = new StringBuffer();
		strBuf.append("select u from User as u ");
		return getHibernateTemplate().find(strBuf.toString());
	}

}

3)新建管理层,UserManager接口和其实现UserManagerImpl。

UserManager接口:

package org.yoo.service;

 import java.util.List;

 import org.yoo.model.User;

 public interface UserManager {
 
 /** 
 * 根据uid查找用户
 * @param uid
 * @return user
 */ 
 public User getUserByUid( int uid);
 /** 
 * 增加用户
 * @param user
 */ 
 public void saveUser(User user);
 /** 
 * 删除用户
 * @param uid
 */ 
 public void deleteUser( int uid);
 
 /** 
 * 更新用户信息
 * @param user
 */ 
 public void updateUser(User user);
 
 /** 
 * 根据用户名查找用户
 * @param name
 * @return user
 */ 
 public User getUserByName(String name);
 
 /** 
 * 用户列表
 * @return user List
 */ 
 public List listUser();
}

UserManagerImpl如下:

package com.zuidaima.service.impl;

import java.util.List;

import com.zuidaima.dao.UserDAO;
import com.zuidaima.model.User;
import com.zuidaima.service.UserManager;

public class UserManagerImpl implements UserManager {
	private UserDAO userDAO = null;

	public void deleteUser(int uid) {
		userDAO.deleteUser(uid);

	}

	public User getUserByName(String name) {

		return userDAO.getUserByName(name);
	}

	public User getUserByUid(int uid) {

		return userDAO.getUser(uid);
	}

	public List listUser() {

		return userDAO.listUser();
	}

	public void saveUser(User user) {
		userDAO.saveUser(user);

	}

	public void updateUser(User user) {
		userDAO.updateUser(user);

	}

	/*
	 * Ioc By Spring
	 */
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

}

 

4)配置xml文件。

Spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

	<!-- ==DATA SOURCE======================================== -->
	<!-- Data Source for MYSQL -->
	<bean id="dataSource_MYSQL"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<value>org.gjt.mm.mysql.Driver</value>
		</property>
		<property name="url">
			<value>jdbc:mysql://127.0.0.1:3306/webservice?useUnicode=true&amp;characterEncoding=GBK</value>
		</property>
		<property name="username">
			<value>root</value>
		</property>
		<property name="password">
			<value>111111</value>
		</property>
	</bean>

	<!--==SESSION FACTORY===================================== -->
	<!-- Hibernate SessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref local="dataSource_MYSQL" />
		</property>

		<property name="mappingResources">
			<list>
				<value>com/zuidaima/model/mysql/User.hbm.xml</value>
			</list>
		</property>

		<property name="hibernateProperties">
			<props>
				<!--sql dialect for MYSQL -->
				<prop key="hibernate.dialect">
					net.sf.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="connection.pool.size">10</prop>
				<prop key="statement_cache.size">25</prop>
				<prop key="jdbc.fetch_size">50</prop>
				<prop key="jdbc.batch_size">30</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="cglib.use_reflection_optimizer">true</prop>
			</props>
		</property>
	</bean>
	<!--==TRANSACTION======================================= -->
	<!-- Transaction manager for a single Hibernate SessionFactory -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
	</bean>
</beans>

Spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="userDAO" class="com.zuidaima.dao.UserDAO">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>
</beans>

Spring-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="userManager" class="com.zuidaima.service.impl.UserManagerImpl">
		<property name="userDAO">
			<ref bean="userDAO" />
		</property>
	</bean>
</beans>

(您也可以将这三个文件合并在一个文件中,我将它们分开是觉得便于管理。另外如果这部分的配置您不明白,请先查看有关spring+hibernate的相关文章)

5)构建bean工厂

在此只前,都是和利用spring+hibernate搭建web项目一致,这一步开始要有些不同了。由于axis1不支持spring,所以无法直接创建spring的容器,我们需要自己构建bean工厂。

创建BeanxmlFactoryl类,如下:

package com.zuidaima.beanfactory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zuidaima.service.UserManager;

/**
 * 单列模式的bean工厂类 SpringBean Factory
 * 
 * @author yoo
 * 
 */
public class BeanxmlFactory {
	private static BeanxmlFactory beanxmlfactory = null;
	private UserManager userManager = null;

	/*
	 * 私有的构造方法
	 */
	private BeanxmlFactory() {
		/**
		 * 读取spring+hibernate的配置文件
		 */
		String[] configs = { "/spring-config.xml", "/spring-dao.xml",
				"/spring-service.xml" };
		ApplicationContext context = new ClassPathXmlApplicationContext(configs);
		/*
		 * 获取制定的bean
		 */
		this.userManager = (UserManager) context.getBean("userManager");
	}

	/*
     * 
     */
	public synchronized static BeanxmlFactory getInstance() {
		if (beanxmlfactory == null) {
			beanxmlfactory = new BeanxmlFactory();
		}
		return beanxmlfactory;
	}

	public UserManager getUserManager() {
		return userManager;
	}

}

到此我们的web项目已经搭建完成了,余下的事情就是构建webservice的服务了。

三构建service

1)新建一个类,我们命名它为UserService。该类利用由Spring提供的UserManager Bean,生产用户的增加和删除服务,如下:

package com.zuidaima.webservice;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.zuidaima.beanfactory.BeanxmlFactory;
import com.zuidaima.model.User;
import com.zuidaima.service.UserManager;

public class UserService {
	private static Log log = LogFactory.getLog(UserService.class);
	private UserManager userManager = null;

	/*
	 * 获取spring提供的userManager bean
	 */
	public UserService() {
		this.userManager = BeanxmlFactory.getInstance().getUserManager();
	}

	/**
	 * 使用信息创建用户
	 * 
	 * @param name
	 *            用户名
	 * @param password
	 *            密码
	 * @param nickname
	 *            昵称
	 * @return user‘uid or error code 0 用户名已存在 -1 创建用户出错
	 */
	public int createUserByUserInfo(String name, String password,
			String nickname) {
		log.info("come in createUser method");
		int resultCode = 0;
		try {
			User userTemp = userManager.getUserByName(name);
			if (userTemp == null) {
				User user = new User(name, password, nickname);
				userManager.saveUser(user);
				resultCode = user.getUid().intValue();
			} else {
				resultCode = 0;
			}
		} catch (Exception e) {
			log.error("createUser have error:", e);
			resultCode = -1;
		}
		return resultCode;
	}

	/**
	 * 删除用户
	 * 
	 * @param uid
	 * @return boolean value
	 */
	public boolean deleteUser(int uid) {
		log.info("come in deleteUser method");
		boolean resultCode = true;
		try {
			userManager.deleteUser(uid);
		} catch (Exception e) {
			log.error("deleteUser have error:", e);
			resultCode = false;
		}
		return resultCode;
	}

}

2)添加axis1所需要的jar包。

复制axis-1_4"lib下所有的包到你的项目lib下。

(可以到apache网站上下载axis-1——4,或者在本文附件中获取)

3)Ok,最重要的一步,也是最奇妙的一步来了,构建server-config.wsdd,即利用axis1搭建webservice服务的描述文件。在web.xml同目录下,新建一xml文件,命名为server-config.wsdd文件类容如下:

<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="http://xml.apache.org/axis/wsdd/"
	xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
	<globalConfiguration>
		<parameter name="wsdlTargetNamespace" value="http://model.yoo.org" />
		<parameter name="adminPassword" value="admin" />
		<parameter name="attachments.implementation"
			value="org.apache.axis.attachments.AttachmentsImpl" />
		<parameter name="sendXsiTypes" value="true" />
		<parameter name="sendMultiRefs" value="true" />
		<parameter name="sendXMLDeclaration" value="true" />
		<parameter name="axis.sendMinimizedElements" value="true" />
		<requestFlow>
			<handler type="java:org.apache.axis.handlers.JWSHandler">
				<parameter name="scope" value="session" />
			</handler>
			<handler type="java:org.apache.axis.handlers.JWSHandler">
				<parameter name="scope" value="request" />
				<parameter name="extension" value=".jwr" />
			</handler>
		</requestFlow>
	</globalConfiguration>
	<handler name="LocalResponder"
		type="java:org.apache.axis.transport.local.LocalResponder" />
	<handler name="URLMapper" type="java:org.apache.axis.handlers.http.URLMapper" />
	<handler name="Authenticate"
		type="java:org.apache.axis.handlers.SimpleAuthenticationHandler" />
	<!--服务的名称 -->
	<service name="UserService" provider="java:RPC">
		<parameter name="scope" value="Request" />
		<!--所有的方法都可以访问 -->
		<parameter name="allowedMethods" value="*" />
		<!-- 服务指向的类 -->
		<parameter name="className" value="com.zuidaima.webservice.UserService" />
	</service>
	<!-- other service -->
	<!-- 可以部署多个服务 -->
	<!-- <service name="balabala" provider="java:RPC"> <parameter name="allowedMethods" 
		value="*"/> <parameter name="scope" value="Request"/> <parameter name="className" 
		value="balabala"/> </service> -->
	<!-- axis1 -->
	<service name="AdminService" provider="java:MSG">
		<parameter name="allowedMethods" value="AdminService" />
		<parameter name="enableRemoteAdmin" value="false" />
		<parameter name="className" value="org.apache.axis.utils.Admin" />
		<namespace>http://xml.apache.org/axis/wsdd/</namespace>
	</service>
	<service name="Version" provider="java:RPC">
		<parameter name="allowedMethods" value="getVersion" />
		<parameter name="className" value="org.apache.axis.Version" />
	</service>
	<transport name="http">
		<requestFlow>
			<handler type="URLMapper" />
			<handler type="java:org.apache.axis.handlers.http.HTTPAuthHandler" />
		</requestFlow>
	</transport>
	<transport name="local">
		<responseFlow>
			<handler type="LocalResponder" />
		</responseFlow>
	</transport>
</deployment>

4)最后一步,需要使用tomcat支持我们搭建的webservice。编辑web.xml,编辑后的文件内容如下:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
	<display-name>aoservice-axis1</display-name>

	<listener>
		<listener-class>org.apache.axis.transport.http.AxisHTTPSessionListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>AxisServlet</servlet-name>
		<display-name>Apache-Axis Servlet</display-name>
		<servlet-class>
			org.apache.axis.transport.http.AxisServlet
		</servlet-class>
	</servlet>

	<servlet>
		<servlet-name>AdminServlet</servlet-name>
		<display-name>Axis Admin Servlet</display-name>
		<servlet-class>
			org.apache.axis.transport.http.AdminServlet
		</servlet-class>
		<load-on-startup>100</load-on-startup>
	</servlet>

	<servlet>
		<servlet-name>SOAPMonitorService</servlet-name>
		<display-name>SOAPMonitorService</display-name>
		<servlet-class>
			org.apache.axis.monitor.SOAPMonitorService
		</servlet-class>
		<init-param>
			<param-name>SOAPMonitorPort</param-name>
			<param-value>5001</param-value>
		</init-param>
		<load-on-startup>100</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>AxisServlet</servlet-name>
		<url-pattern>/servlet/AxisServlet</url-pattern>
	</servlet-mapping>

	<servlet-mapping>
		<servlet-name>AxisServlet</servlet-name>
		<url-pattern>*.jws</url-pattern>
	</servlet-mapping>

	<servlet-mapping>
		<servlet-name>AxisServlet</servlet-name>
		<url-pattern>/services/*</url-pattern>
	</servlet-mapping>

	<servlet-mapping>
		<servlet-name>SOAPMonitorService</servlet-name>
		<url-pattern>/SOAPMonitor</url-pattern>
	</servlet-mapping>

	<!-- uncomment this if you want the admin servlet -->
	<!-- <servlet-mapping> <servlet-name>AdminServlet</servlet-name> <url-pattern>/servlet/AdminServlet</url-pattern> 
		</servlet-mapping> -->

	<session-config>
		<!-- Default to 5 minute session timeouts -->
		<session-timeout>5</session-timeout>
	</session-config>

	<!-- currently the W3C havent settled on a media type for WSDL; http://www.w3.org/TR/2003/WD-wsdl12-20030303/#ietf-draft 
		for now we go with the basic 'it's XML' response -->
	<mime-mapping>
		<extension>wsdl</extension>
		<mime-type>text/xml</mime-type>
	</mime-mapping>


	<mime-mapping>
		<extension>xsd</extension>
		<mime-type>text/xml</mime-type>
	</mime-mapping>

	<welcome-file-list id="WelcomeFileList">
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.jws</welcome-file>
	</welcome-file-list>

</web-app>

到此,我们可以歇口气啦,我们已经搭建好了一个简单的webservice了。

项目截图:

使用axis1+spring+hibernate搭建webservice框架_第1张图片

该项目由于我对webservice不熟悉,所以只是把文档涉及到的代码搭建成了maven工程,花了不少时间也没验证通过,大家谁有能力的帮忙验证下吧。

你可能感兴趣的:(spring,Hibernate,webservice,axis,框架搭建)