您的位置:首页 > 其它

CXF方式发布WebService全步骤

2013-02-25 10:20 513 查看
发布webService有多种方式,不过企业中最常用的还是 以 CXF 的方式。

接下来,我来诉说以下 CXF方式 发布WebService的全步骤,供新朋友参考。

1:准备的包: cxf-bundle-2.1.3.jar | wss4j-1.5.4.jar | axis-1.4.jar

2: 创建WebService 接口,范例代码如下:

Java代码



package com.transnal.ws;

import java.util.List;

import javax.jws.WebParam;

import javax.jws.WebResult;

import javax.jws.WebService;

import com.transnal.user.model.ProfileValue; //根据自己设定,我就不删了

import com.transnal.user.model.UserDTO; //最好你也创建一个DTO

/**

* 说明:对内 用户模块 webservice接口

* ******************

* 日期 人员

* 2010-11-1 RenWeigang */

@WebService

public interface UserService {

@WebResult(name="msg")

public int login(@WebParam(name="userName")String userName,@WebParam(name="password")String password);

@WebResult(name="msg")

public String register(@WebParam(name="userName")String userName,@WebParam(name="password")String password,@WebParam(name="email")String email)throws Exception;

@WebResult(name="msg")

public boolean verifyUserByUserNameAndPassword(@WebParam(name="userName")String userName,@WebParam(name="password")String password);

@WebResult(name="userDTO")

public UserDTO getUserByUserName(@WebParam(name="userName")String username);

@WebResult(name="msg")

public String userEdit(@WebParam(name="userName")String userName, @WebParam(name="email")String email,

@WebParam(name="nickName")String nickName,@WebParam(name="realName")String realName,@WebParam(name="sex")int sex,@WebParam(name="birthday")String birthday,@WebParam(name="mobile")String mobile);

@WebResult(name="result")

public boolean verifyEmail(@WebParam(name="email")String email);

@WebResult(name="result")

public boolean verifyUser(@WebParam(name="userName")String userName);

@WebResult(name="msg")

public String resetPassword(@WebParam(name="userName")String userName,@WebParam(name="newPassowrd")String newPassword);

@WebResult(name="msg")

public String changePassword(@WebParam(name="userName")String userName,@WebParam(name="oldPassword")String oldPassword,

@WebParam(name="newPassword")String newPassword);

@SuppressWarnings("unchecked")

public void updateUserProperties(@WebParam(name="userName")String userName, @WebParam(name="userProperties")List<ProfileValue> values);

@SuppressWarnings("unchecked")

@WebResult(name="ProfileValue")

public ProfileValue getUserProperties(@WebParam(name="userName")String userName, @WebParam(name="key")String key);

}

3: 创建 WebService 接口实现类,代码如下:

Java代码



package com.transnal.openplatform.ws.user;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;

import javax.jws.WebService;

import net.sxinfo.common.enums.Sex;

import org.apache.commons.lang.StringUtils;

import org.apache.commons.validator.EmailValidator;

import com.transnal.profile.model.Profile;

import com.transnal.profile.model.ProfileInfo;

import com.transnal.user.entity.UserEntity;

import com.transnal.user.exceptions.AuthenticationException;

import com.transnal.user.model.ProfileValue;

import com.transnal.user.model.User;

import com.transnal.user.model.UserDTO;

import com.transnal.user.service.UserRemote;

import com.transnal.web.ProfileExtInfo;

import com.transnal.web.UserFactory;

import com.transnal.ws.UserService;

/**

* 说明:用户webservice实现

* ******************

* 日期 人员 2010-11-1 RenWeigang

*/

@WebService(endpointInterface = "com.transnal.ws.UserService", serviceName = "userService")

public class UserServiceImpl implements UserService {

@Override

public UserDTO getUserByUserName(String username) {

UserDTO dto = new UserDTO();

UserEntity entity = (UserEntity) UserFactory.getUserRemote(null)

.findUser(username);

dto.setUserId(entity.getUserId());

dto.setUserName(entity.getUserName());

dto.setEmail(entity.getEmail());

dto.setAnswer(entity.getAnswer());

dto.setQuestion(entity.getQuestion());

dto.setApproved(entity.getApproved());

dto.setLockedOut(entity.getLockedOut());

dto.setLastLockoutDate(entity.getLastLoginDate());

dto.setFailedCount(entity.getFailedCount());

dto.setFailedAnswerCount(entity.getFailedAnswerCount());

dto.setFailedAnswerDate(entity.getFailedDate());

dto.setFailedDate(entity.getFailedDate());

dto.setLastPwdChange(entity.getLastPwdChange());

dto.setPassword(entity.getPassword());

dto.setLastLoginDate(entity.getLastLoginDate());

dto.setPwdFormat(entity.getPwdFormat().name());

Profile profile = UserFactory.getProfileRemote(null).findUserByName(

username);

ProfileExtInfo profileInfo = new ProfileExtInfo(UserFactory

.getPropertySetAccessor(), profile);

dto.setRealName(profile.getRealName());

if(null!=profileInfo.getBirthday()){

Date birthday = profileInfo.getBirthday();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

dto.setBirthday(sdf.format(birthday));

}

if(StringUtils.isNotEmpty(profileInfo.getMobile())){

dto.setMobile(profileInfo.getMobile());

}

dto.setSex(profileInfo.getSex().ordinal());

dto.setNickName(profileInfo.getNickName());

return dto;

}

public String register(String userName, String password, String email)

throws Exception {

// 判断 用户名是否重复

if (UserFactory.getUserRemote(null).findUser(userName) != null) {

return Constants.userNameExist;

}

if (!EmailValidator.getInstance().isValid(email)) {

return Constants.emailIsNotValid;

}

// 判断用户email是否被注册

if (UserFactory.getUserRemote(null).checkEmail(email)) {

return Constants.emailExist;

}

User user = UserFactory.getUserRemote(null).createUser(userName,

password, email, null, null);

if (user == null) {

return Constants.registFail;

}

UserFactory.getRoleRemote(null).addRoleToUser(userName, "guest");

return Constants.registSuccess;

}

@Override

public String changePassword(String userName, String oldPassword,

String newPassword) {

UserRemote userRemote = UserFactory.getUserRemote(null);

if (userRemote.findUser(userName) == null) {

return Constants.userNotFound;

}

if (StringUtils.isBlank(newPassword)

&& StringUtils.isBlank(oldPassword)) {

return Constants.passwordIsRequired;

}

if (!userRemote.verify(userName, oldPassword)) {

return Constants.oldPasswordIsNotValid;

}

try {

userRemote.changePwd(userName, oldPassword, newPassword);

} catch (AuthenticationException e) {

return Constants.changePasswordFail;

}

return Constants.changePasswordSuccess;

}

@Override

public boolean verifyEmail(String email) {

if (UserFactory.getUserRemote(null).checkEmail(email)) {

return true;

}

return false;

}

@Override

public boolean verifyUser(String userName) {

// 判断 用户名是否重复

if (UserFactory.getUserRemote(null).findUser(userName) != null) {

return true;

}

return false;

}

@Override

public String userEdit(String userName, String email, String nickName,

String realName, int sex, String birthday, String mobile) {

// email 格式

if (!EmailValidator.getInstance().isValid(email)) {

return Constants.emailIsNotValid;

}

// 是否占用

if (!UserFactory.getUserRemote(null).isValidEmail(userName, email)) {

return Constants.emailExist;

}

// 修改信息

UserFactory.getUserRemote(null).updateUser(userName, email);

Profile profile = UserFactory.getProfileRemote(null).findUserByName(

userName);

if(StringUtils.isNotBlank(realName)){

profile.setRealName(realName);

}

ProfileExtInfo profileInfo = new ProfileExtInfo(UserFactory

.getPropertySetAccessor(), profile);

if(StringUtils.isNotBlank(nickName)){

profileInfo.setNickname(nickName);

}

switch (sex) {

case 1:

profileInfo.setSex(Sex.male);

break;

case 2:

profileInfo.setSex(Sex.famale);

break;

default:

profileInfo.setSex(Sex.unknown);

break;

}

if(StringUtils.isNotBlank(birthday)){

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

try {

profileInfo.setBirthday(sdf.parse(birthday));

} catch (ParseException e) {

System.out.println("设置生日出错!!!!!!!");

profileInfo.setBirthday(new Date());

// e.printStackTrace();

}

}

if(StringUtils.isNotBlank(mobile)){

profileInfo.setMobile(mobile);

}

UserFactory.getProfileRemote(null).storeUser(profile);

UserFactory.getProfileRemote(null).storeUser(profileInfo);

return Constants.userEditSuccess;

}

@Override

public String resetPassword(String userName, String newPassword) {

if (StringUtils.isBlank(userName)) {

return Constants.usernameIsRequired;

}

User user = UserFactory.getUserRemote(null).findUser(userName);

if (null == user) {

return Constants.userNotFound;

}

String username = UserFactory.getUserRemote(null).resetPwd(

user.getUserName(), newPassword);

if (username == null) {

return Constants.oldPasswordIsNotValid;

}

return Constants.resetPasswordSuccess;

}

@Override

public boolean verifyUserByUserNameAndPassword(String userName,

String password) {

return UserFactory.getUserRemote(null).verify(userName, password);

}

@Override

public int login(String userName, String password) {

// 登录验证

try {

System.out.println("1");

User user = UserFactory.getUserRemote(null).login(userName, password);

System.out.println(user.getUserName());

System.out.println("2");

} catch (Exception e) {

e.printStackTrace();

System.out.println("3");

if (e instanceof com.transnal.user.exceptions.BadUserNameOrPasswordAuthenticationException) {

return -1;

} else if (e instanceof com.transnal.user.exceptions.DisableUserAuthenticationException) {

return -2;

} else if (e instanceof com.transnal.user.exceptions.NotApprovedAuthenticationException) {

return -3;

} else if (e instanceof com.transnal.user.exceptions.BadPasswordAuthenticationException) {

return -4;

}

}

return Constants.authenticateSuccess;

}

@SuppressWarnings("unchecked")

public void updateUserProperties(String userName, List<ProfileValue> values) {

Profile profile = UserFactory.getProfileRemote(null).findUserByName(

userName);

UserFactory.getProfileRemote(null).storeUser(profile);

// 其他属性

ProfileInfo info = new ProfileInfo(

UserFactory.getPropertySetAccessor(), profile);

for (ProfileValue value : values) {

if (value.getValue() instanceof java.lang.Integer) {

info.setProperty(value.getKey(), Integer.parseInt(value

.getValue().toString()));

} else if (value.getValue() instanceof java.lang.Long) {

info.setProperty(value.getKey(), Long.parseLong(value

.getValue().toString()));

} else if (value.getValue() instanceof java.lang.Double) {

info.setProperty(value.getKey(), Double.parseDouble(value

.getValue().toString()));

} else if (value.getValue() instanceof java.lang.Boolean) {

info.setProperty(value.getKey(), Boolean.parseBoolean(value

.getValue().toString()));

}

else if (value.getKey().equals("birthday")) {

Date date = null;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

try {

String a = value.getValue().toString();

date = sdf.parse(a);

} catch (ParseException e) {

e.printStackTrace();

}

info.setProperty(value.getKey(), date);

}

else {

info.setProperty(value.getKey(), value.getValue());

}

}

}

@SuppressWarnings("unchecked")

public ProfileValue getUserProperties(String userName, String key) {

Profile profile = UserFactory.getProfileRemote(null).findUserByName(

userName);

UserFactory.getProfileRemote(null).storeUser(profile);

ProfileInfo info = new ProfileInfo(

UserFactory.getPropertySetAccessor(), profile);

ProfileValue value = new ProfileValue();

value.setKey(key);

//根据不同的类型设置不同的value

if (value.getValue() instanceof java.lang.Integer) {

value.setValue(info.getPropertySet().getInt(key));

} else if (value.getValue() instanceof java.lang.Long) {

value.setValue(info.getPropertySet().getLong(key));

} else if (value.getValue() instanceof java.lang.Double) {

value.setValue(info.getPropertySet().getDouble(key));

} else if (value.getValue() instanceof java.lang.Boolean) {

value.setValue(info.getPropertySet().getBoolean(key));

}

else if (value.getKey().equals("birthday")) {

Date date = null;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

try {

String a = value.getValue().toString();

date = sdf.parse(a);

value.setValue(date);

} catch (ParseException e) {

e.printStackTrace();

}

}

else {

value.setValue(info.getPropertySet().getString(key));

}

return value;

}

}

4: 为所发布的WebService指定角色,代码如下:

Java代码



package com.transnal.openplatform.ws.security;

import java.util.Arrays;

import javax.security.auth.callback.Callback;

import javax.security.auth.callback.CallbackHandler;

import org.apache.ws.security.WSConstants;

import org.apache.ws.security.WSPasswordCallback;

import org.apache.ws.security.WSSecurityException;

import com.transnal.user.entity.UserEntity;

import com.transnal.web.UserFactory;

public class PasswordHandler implements CallbackHandler {

//凡是角色为 ws 的用户 才可访问你的这个 WebService

private static final String ROLE_SERVICES="ws";

public void handle(Callback[] callbacks) throws WSSecurityException {

WSPasswordCallback callback = (WSPasswordCallback) callbacks[0];

String userName = callback.getIdentifer();

//判断角色

String[] roles=UserFactory.getRoleRemote(null).findByUser(userName);

if(!Arrays.asList(roles).contains(ROLE_SERVICES)){

throw new WSSecurityException(String.format("not '%s' role privilege ", ROLE_SERVICES));

}

if (WSConstants.PASSWORD_TEXT.equals(callback.getPasswordType())) {

String pw = callback.getPassword();

if (!UserFactory.getUserRemote(null).verify(userName, pw)) {

throw new WSSecurityException("password not match");

}

} else {

UserEntity user = (UserEntity)UserFactory.getUserRemote(null).findUser(userName);

callback.setPassword(user.getPassword());

}

}

}

4: 在 WEB-INF下添加一个apache-cxf.xml 的配置文件,xml文件如下(注意:WebService的接口实现类以及WebService的用户角色类都在此配置中加入.):

Java代码



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

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"

xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

<!-- CXF ,此处是配置发布的 web service -->

<import resource="classpath:META-INF/cxf/cxf.xml" />

<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />

<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

<bean id="utWss4jInHandler" class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">

<constructor-arg>

<map>

<entry key="action" value="UsernameToken Timestamp" />

<entry key="passwordType" value="PasswordText" />

<entry key="passwordCallbackClass"

value="com.transnal.openplatform.ws.security.PasswordHandler" />

</map>

</constructor-arg>

</bean>

<!--

id指 在spring配置的bean的Id implementor 指具体的实现类 address 指明这个web service的相对地址

-->

<jaxws:endpoint id="userService"

implementor="com.transnal.openplatform.ws.user.UserServiceImpl"

address="<span style="color: #ff0000;">/userService</span>">

<jaxws:inInterceptors>

<bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />

<ref bean="utWss4jInHandler" />

</jaxws:inInterceptors>

</jaxws:endpoint>

</beans>

5: 在 WEB-INF下的 web.xml 文件中加入 CXF 的配置,范例如下:

Java代码



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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<display-name>用户管理中心</display-name>

<description>ucmange admin</description>

<!-- 环境参数配置 -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/apache-cxf.xml

</param-value>

</context-param>

<!-- CXF -->

<servlet>

<servlet-name>CXFServlet</servlet-name>

<servlet-class>

org.apache.cxf.transport.servlet.CXFServlet

</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>CXFServlet</servlet-name>

<url-pattern><span style="color: #ff0000;">/ws/*</span></url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

注意web.xml文件中配置的 servlet 的 <url-pattern>/ws/*</url-pattern> ,和 在 apache-cxf.xml文件中配置的 address="/userService" 。

上面的红色 标题 说明的是在 浏览器中访问的webservice 的 url 地址,例如你的工程名为:ucmanage.那么你要测试你是否已经发布好 webservice, 在浏览器中输入的地址为:
http://127.0.0.1:8080/ucmanage/ws/userService

结束语: 至此完毕了 WebService的发布,如要建立客户端调用 webService,请参考: http://rwg109.iteye.com/blog/812873
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: