加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

CXF方式发布WebService全步骤

发布时间:2020-12-17 00:26:20 所属栏目:安全 来源:网络整理
导读:发布webService有多种方式,不过企业中最常用的还是 以 CXF 的方式。? 接下来,我来诉说以下 CXF方式 发布WebService的全步骤,供新朋友参考。? 1:准备的包: cxf-bundle-2.1.3.jar? |?? wss4j-1.5.4.jar?? |? axis-1.4.jar? 2: 创建WebService 接口,范例代
发布webService有多种方式,不过企业中最常用的还是 以 CXF 的方式。?
接下来,我来诉说以下 CXF方式 发布WebService的全步骤,供新朋友参考。?

1:准备的包: cxf-bundle-2.1.3.jar? |?? wss4j-1.5.4.jar?? |? axis-1.4.jar?
2: 创建WebService 接口,范例代码如下:?
Java代码??

  1. package?com.transnal.ws;??
  2. ??
  3. import?java.util.List;??
  4. import?javax.jws.WebParam;??
  5. import?javax.jws.WebResult;??
  6. import?javax.jws.WebService;??
  7. import?com.transnal.user.model.ProfileValue;??//根据自己设定,我就不删了??
  8. import?com.transnal.user.model.UserDTO;???//最好你也创建一个DTO??
  9. /**?
  10. ?*??说明:对内?用户模块???webservice接口??
  11. ?*??******************??
  12. ?*??日期????????人员??
  13. ?*??2010-11-1?RenWeigang?*/??
  14. @WebService??
  15. public?interface?UserService?{??
  16. ????@WebResult(name="msg")??
  17. ????public?int??login(@WebParam(name="userName")String?userName,@WebParam(name="password")String?password);??
  18. ??????
  19. ????public?String?register(@WebParam(name="userName")String?userName,@WebParam(name="password")String?password,@WebParam(name="email")String?email)throws?Exception;??
  20. ????public?boolean?verifyUserByUserNameAndPassword(@WebParam(name="userName")String?userName,250)"> ????@WebResult(name="userDTO")??
  21. ????public?UserDTO?getUserByUserName(@WebParam(name="userName")String?username);??
  22. ????public?String?userEdit(@WebParam(name="userName")String?userName,?@WebParam(name="email")String?email,??
  23. ????????????@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);????
  24. ????@WebResult(name="result")??
  25. ????public?boolean?verifyEmail(@WebParam(name="email")String?email);??
  26. ????public?boolean?verifyUser(@WebParam(name="userName")String?userName);??
  27. ????public?String?resetPassword(@WebParam(name="userName")String?userName,@WebParam(name="newPassowrd")String?newPassword);??
  28. ????public?String?changePassword(@WebParam(name="userName")String?userName,@WebParam(name="oldPassword")String?oldPassword,250)"> ????????????@WebParam(name="newPassword")String?newPassword);??
  29. ????@SuppressWarnings("unchecked")??
  30. ????public?void?updateUserProperties(@WebParam(name="userName")String?userName,?@WebParam(name="userProperties")List<ProfileValue>?values);??
  31. ????@WebResult(name="ProfileValue")??
  32. ????public?ProfileValue?getUserProperties(@WebParam(name="userName")String?userName,?@WebParam(name="key")String?key);??
  33. }??


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实现??
  • ?*?******************??
  • ?*?日期?人员?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,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)?{??
  • ????????//?email?格式??
  • ????????//?是否占用??
  • ????????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());??
  • ????????????????//?e.printStackTrace();??
  • ????????????}?????????????
  • ??????????
  • ????????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);??
  • ????????//根据不同的类型设置不同的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;??
  • ????????????????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?{??
  • ?????????????????//凡是角色为?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代码?? <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?

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读