接下來,我來訴說以下 CXF方式 發(fā)布WebService的全步驟,供新朋友參考。
1:準(zhǔn)備的包: cxf-bundle-2.1.3.jar | wss4j-1.5.4.jar | axis-1.4.jar
2: 創(chuàng)建WebService 接口,范例代碼如下:
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; //根據(jù)自己設(shè)定,我就不刪了import com.transnal.user.model.UserDTO; //最好你也創(chuàng)建一個DTO/*** 說明:對內(nèi) 用戶模塊 webservice接口* ******************* 日期 人員* 2010-11-1 RenWeigang */@WebServicepublic 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: 創(chuàng)建 WebService 接口實現(xiàn)類,代碼如下:
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實現(xiàn)* ******************* 日期 人員 2010-11-1 RenWeigang*/@WebService(endpointInterface = "com.transnal.ws.UserService", serviceName = "userService")public class UserServiceImpl implements UserService {@Overridepublic 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 {// 判斷 用戶名是否重復(fù)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;}@Overridepublic 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;}@Overridepublic boolean verifyEmail(String email) {if (UserFactory.getUserRemote(null).checkEmail(email)) {return true;}return false;}@Overridepublic boolean verifyUser(String userName) {// 判斷 用戶名是否重復(fù)if (UserFactory.getUserRemote(null).findUser(userName) != null) {return true;}return false;}@Overridepublic 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("設(shè)置生日出錯?。。。。。?!");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;}@Overridepublic 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;}@Overridepublic boolean verifyUserByUserNameAndPassword(String userName,String password) {return UserFactory.getUserRemote(null).verify(userName, password);}@Overridepublic 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);//根據(jù)不同的類型設(shè)置不同的valueif (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: 為所發(fā)布的WebService指定角色,代碼如下:
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 的用戶 才可訪問你的這個 WebServiceprivate 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的接口實現(xiàn)類以及WebService的用戶角色類都在此配置中加入.):
<?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.xsdhttp://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"><!-- CXF ,此處是配置發(fā)布的 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 指具體的實現(xiàn)類 address 指明這個web service的相對地址--><jaxws:endpoint id="userService"implementor="com.transnal.openplatform.ws.user.UserServiceImpl"address="/userService"><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 的配置,范例如下:
<?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><!-- 環(huán)境參數(shù)配置 --><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>/ws/*</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" 。
上面的紅色 標(biāo)題 說明的是在 瀏覽器中訪問的webservice 的 url 地址,例如你的工程名為:ucmanage.那么你要測試你是否已經(jīng)發(fā)布好 webservice, 在瀏覽器中輸入的地址為: http://127.0.0.1:8080/ucmanage/ws/userService