发布webService有多种方式,不过企业中最常用的还是 以 CXF 的方式。?
接下来,我来诉说以下 CXF方式 发布WebService的全步骤,供新朋友参考。?
1:准备的包: cxf-bundle-2.1.3.jar? |?? wss4j-1.5.4.jar?? |? axis-1.4.jar?
2: 创建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;????
- import?com.transnal.user.model.UserDTO;?????
- ?
- ?
- ?
- ?
- ??
- @WebService??
- public?interface?UserService?{??
- ????@WebResult(name="msg")??
- ????public?int??login(@WebParam(name="userName")String?userName,@WebParam(name="password")String?password);??
- ??????
- ????public?String?register(@WebParam(name="userName")String?userName,@WebParam(name="password")String?password,@WebParam(name="email")String?email)throws?Exception;??
- ????public?boolean?verifyUserByUserNameAndPassword(@WebParam(name="userName")String?userName,250)"> ????@WebResult(name="userDTO")??
- ????public?UserDTO?getUserByUserName(@WebParam(name="userName")String?username);??
- ????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);??
- ????public?boolean?verifyUser(@WebParam(name="userName")String?userName);??
- ????public?String?resetPassword(@WebParam(name="userName")String?userName,@WebParam(name="newPassowrd")String?newPassword);??
- ????public?String?changePassword(@WebParam(name="userName")String?userName,@WebParam(name="oldPassword")String?oldPassword,250)"> ????????????@WebParam(name="newPassword")String?newPassword);??
- ????@SuppressWarnings("unchecked")??
- ????public?void?updateUserProperties(@WebParam(name="userName")String?userName,?@WebParam(name="userProperties")List<ProfileValue>?values);??
- ????@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?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(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;??
??????????
????????if?(UserFactory.getUserRemote(null).checkEmail(email))?{??
????????????return?Constants.emailExist;??
????????User?user?=?UserFactory.getUserRemote(null).createUser(userName,250)"> ????????????????password,?email,?null,?null);??
????????if?(user?==?null)?{??
????????????return?Constants.registFail;??
????????UserFactory.getRoleRemote(null).addRoleToUser(userName,?"guest");??
????????return?Constants.registSuccess;??
????public?String?changePassword(String?userName,?String?oldPassword,250)"> ????????????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;??
????public?boolean?verifyEmail(String?email)?{??
????????????return?true;??
????????return?false;??
????public?boolean?verifyUser(String?userName)?{??
????public?String?userEdit(String?userName,?String?email,?String?nickName,250)"> ????????????String?realName,?int?sex,?String?birthday,?String?mobile)?{??
??????????
??????????
????????if?(!UserFactory.getUserRemote(null).isValidEmail(userName,?email))?{??
??????????
????????UserFactory.getUserRemote(null).updateUser(userName,?email);??
????????????????userName);??
????????if(StringUtils.isNotBlank(realName)){??
????????????profile.setRealName(realName);????
????????if(StringUtils.isNotBlank(nickName)){??
????????????profileInfo.setNickname(nickName);??
????????switch?(sex)?{??
????????case?1:??
????????????profileInfo.setSex(Sex.male);??
????????????break;??
????????case?2:??
????????????profileInfo.setSex(Sex.famale);??
????????default:??
????????????profileInfo.setSex(Sex.unknown);??
????????if(StringUtils.isNotBlank(birthday)){??
????????????try?{??
????????????????profileInfo.setBirthday(sdf.parse(birthday));??
????????????}?catch?(ParseException?e)?{??
????????????????System.out.println("设置生日出错!!!!!!!");??
????????????????profileInfo.setBirthday(new?Date());??
??????????????????
????????????}?????????????
??????????
????????if(StringUtils.isNotBlank(mobile)){??
????????????profileInfo.setMobile(mobile);??
????????UserFactory.getProfileRemote(null).storeUser(profile);??
????????UserFactory.getProfileRemote(null).storeUser(profileInfo);??
????????return?Constants.userEditSuccess;??
????public?String?resetPassword(String?userName,?String?newPassword)?{??
????????if?(StringUtils.isBlank(userName))?{??
????????????return?Constants.usernameIsRequired;??
????????User?user?=?UserFactory.getUserRemote(null).findUser(userName);??
????????if?(null?==?user)?{??
????????String?username?=?UserFactory.getUserRemote(null).resetPwd(??
????????????????user.getUserName(),250)"> ????????if?(username?==?null)?{??
????????return?Constants.resetPasswordSuccess;??
????public?boolean?verifyUserByUserNameAndPassword(String?userName,250)"> ????????????String?password)?{??
????????return?UserFactory.getUserRemote(null).verify(userName,?password);??
????public?int?login(String?userName,?String?password)?{??
??????????
????????????System.out.println("1");??
????????????User?user?=?UserFactory.getUserRemote(null).login(userName,250)"> ????????????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;??
????public?void?updateUserProperties(String?userName,?List<ProfileValue>?values)?{??
??????????
????????ProfileInfo?info?=?new?ProfileInfo(??
????????????????UserFactory.getPropertySetAccessor(),250)"> ????????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)?{??
????????????}?else?if?(value.getValue()?instanceof?java.lang.Double)?{??
????????????}?else?if?(value.getValue()?instanceof?java.lang.Boolean)?{??
????????????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();??
????????????????}??
????????????else?{??
????public?ProfileValue?getUserProperties(String?userName,?String?key)?{??
????????ProfileValue?value?=?new?ProfileValue();??
????????value.setKey(key);??
??????????
????????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;??
????????????????String?a?=?value.getValue().toString();??
????????????????date?=?sdf.parse(a);??
????????????????value.setValue(date);??
????????????????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;??
public?class?PasswordHandler?implements?CallbackHandler?{??
???????????????????
????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:??
http:??
????<!--??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代码??
<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>??
????????<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?
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|