英雄联盟s6火男视频:CXF方式发布WebService全步骤111

来源:百度文库 编辑:九乡新闻网 时间:2024/04/27 21:46:11
    发布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.   
  5. import javax.jws.WebParam;   
  6. import javax.jws.WebResult;   
  7. import javax.jws.WebService;   
  8.   
  9. import com.transnal.user.model.ProfileValue;  //根据自己设定,我就不删了   
  10. import com.transnal.user.model.UserDTO;   //最好你也创建一个DTO   
  11.   
  12. /**  
  13.  *  说明:对内 用户模块   webservice接口   
  14.  *  ******************   
  15.  *  日期        人员   
  16.  *  2010-11-1 RenWeigang */  
  17. @WebService  
  18. public interface UserService {   
  19.   
  20.     @WebResult(name="msg")   
  21.     public int  login(@WebParam(name="userName")String userName,@WebParam(name="password")String password);   
  22.        
  23.     @WebResult(name="msg")   
  24.     public String register(@WebParam(name="userName")String userName,@WebParam(name="password")String password,@WebParam(name="email")String email)throws Exception;   
  25.   
  26.     @WebResult(name="msg")   
  27.     public boolean verifyUserByUserNameAndPassword(@WebParam(name="userName")String userName,@WebParam(name="password")String password);   
  28.        
  29.     @WebResult(name="userDTO")   
  30.     public UserDTO getUserByUserName(@WebParam(name="userName")String username);   
  31.        
  32.     @WebResult(name="msg")   
  33.     public String userEdit(@WebParam(name="userName")String userName, @WebParam(name="email")String email,   
  34.             @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);     
  35.        
  36.     @WebResult(name="result")   
  37.     public boolean verifyEmail(@WebParam(name="email")String email);   
  38.     @WebResult(name="result")   
  39.     public boolean verifyUser(@WebParam(name="userName")String userName);   
  40.        
  41.     @WebResult(name="msg")   
  42.     public String resetPassword(@WebParam(name="userName")String userName,@WebParam(name="newPassowrd")String newPassword);   
  43.   
  44.     @WebResult(name="msg")   
  45.     public String changePassword(@WebParam(name="userName")String userName,@WebParam(name="oldPassword")String oldPassword,   
  46.             @WebParam(name="newPassword")String newPassword);   
  47.        
  48.     @SuppressWarnings("unchecked")   
  49.     public void updateUserProperties(@WebParam(name="userName")String userName, @WebParam(name="userProperties")List values);   
  50.        
  51.     @SuppressWarnings("unchecked")   
  52.     @WebResult(name="ProfileValue")   
  53.     public ProfileValue getUserProperties(@WebParam(name="userName")String userName, @WebParam(name="key")String key);   
  54.        
  55. }  

 

 

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

Java代码
  1. package com.transnal.openplatform.ws.user;   
  2.   
  3. import java.text.ParseException;   
  4. import java.text.SimpleDateFormat;   
  5. import java.util.Date;   
  6. import java.util.List;   
  7.   
  8. import javax.jws.WebService;   
  9.   
  10. import net.sxinfo.common.enums.Sex;   
  11.   
  12. import org.apache.commons.lang.StringUtils;   
  13. import org.apache.commons.validator.EmailValidator;   
  14.   
  15. import com.transnal.profile.model.Profile;   
  16. import com.transnal.profile.model.ProfileInfo;   
  17. import com.transnal.user.entity.UserEntity;   
  18. import com.transnal.user.exceptions.AuthenticationException;   
  19. import com.transnal.user.model.ProfileValue;   
  20. import com.transnal.user.model.User;   
  21. import com.transnal.user.model.UserDTO;   
  22. import com.transnal.user.service.UserRemote;   
  23. import com.transnal.web.ProfileExtInfo;   
  24. import com.transnal.web.UserFactory;   
  25. import com.transnal.ws.UserService;   
  26.   
  27. /**  
  28.  * 说明:用户webservice实现   
  29.  * ******************   
  30.  * 日期 人员 2010-11-1 RenWeigang  
  31.  */  
  32. @WebService(endpointInterface = "com.transnal.ws.UserService", serviceName = "userService")   
  33. public class UserServiceImpl implements UserService {   
  34.     @Override  
  35.     public UserDTO getUserByUserName(String username) {   
  36.         UserDTO dto = new UserDTO();   
  37.   
  38.         UserEntity entity = (UserEntity) UserFactory.getUserRemote(null)   
  39.                 .findUser(username);   
  40.         dto.setUserId(entity.getUserId());   
  41.         dto.setUserName(entity.getUserName());   
  42.         dto.setEmail(entity.getEmail());   
  43.         dto.setAnswer(entity.getAnswer());   
  44.         dto.setQuestion(entity.getQuestion());   
  45.         dto.setApproved(entity.getApproved());   
  46.         dto.setLockedOut(entity.getLockedOut());   
  47.         dto.setLastLockoutDate(entity.getLastLoginDate());   
  48.         dto.setFailedCount(entity.getFailedCount());   
  49.         dto.setFailedAnswerCount(entity.getFailedAnswerCount());   
  50.         dto.setFailedAnswerDate(entity.getFailedDate());   
  51.         dto.setFailedDate(entity.getFailedDate());   
  52.         dto.setLastPwdChange(entity.getLastPwdChange());   
  53.         dto.setPassword(entity.getPassword());   
  54.         dto.setLastLoginDate(entity.getLastLoginDate());   
  55.         dto.setPwdFormat(entity.getPwdFormat().name());   
  56.         Profile profile = UserFactory.getProfileRemote(null).findUserByName(   
  57.                 username);   
  58.         ProfileExtInfo profileInfo = new ProfileExtInfo(UserFactory   
  59.                 .getPropertySetAccessor(), profile);   
  60.         dto.setRealName(profile.getRealName());   
  61.         if(null!=profileInfo.getBirthday()){   
  62.             Date birthday = profileInfo.getBirthday();   
  63.             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
  64.             dto.setBirthday(sdf.format(birthday));             
  65.         }   
  66.         if(StringUtils.isNotEmpty(profileInfo.getMobile())){   
  67.             dto.setMobile(profileInfo.getMobile());   
  68.         }   
  69.         dto.setSex(profileInfo.getSex().ordinal());   
  70.         dto.setNickName(profileInfo.getNickName());   
  71.   
  72.         return dto;   
  73.     }   
  74.   
  75.     public String register(String userName, String password, String email)   
  76.             throws Exception {   
  77.         // 判断 用户名是否重复   
  78.         if (UserFactory.getUserRemote(null).findUser(userName) != null) {   
  79.             return Constants.userNameExist;   
  80.         }   
  81.         if (!EmailValidator.getInstance().isValid(email)) {   
  82.             return Constants.emailIsNotValid;   
  83.         }   
  84.         // 判断用户email是否被注册   
  85.         if (UserFactory.getUserRemote(null).checkEmail(email)) {   
  86.             return Constants.emailExist;   
  87.         }   
  88.         User user = UserFactory.getUserRemote(null).createUser(userName,   
  89.                 password, email, nullnull);   
  90.         if (user == null) {   
  91.             return Constants.registFail;   
  92.         }   
  93.         UserFactory.getRoleRemote(null).addRoleToUser(userName, "guest");   
  94.   
  95.         return Constants.registSuccess;   
  96.     }   
  97.   
  98.     @Override  
  99.     public String changePassword(String userName, String oldPassword,   
  100.             String newPassword) {   
  101.         UserRemote userRemote = UserFactory.getUserRemote(null);   
  102.         if (userRemote.findUser(userName) == null) {   
  103.             return Constants.userNotFound;   
  104.         }   
  105.         if (StringUtils.isBlank(newPassword)   
  106.                 && StringUtils.isBlank(oldPassword)) {   
  107.   
  108.             return Constants.passwordIsRequired;   
  109.         }   
  110.         if (!userRemote.verify(userName, oldPassword)) {   
  111.             return Constants.oldPasswordIsNotValid;   
  112.         }   
  113.   
  114.         try {   
  115.             userRemote.changePwd(userName, oldPassword, newPassword);   
  116.         } catch (AuthenticationException e) {   
  117.             return Constants.changePasswordFail;   
  118.         }   
  119.         return Constants.changePasswordSuccess;   
  120.     }   
  121.   
  122.     @Override  
  123.     public boolean verifyEmail(String email) {   
  124.         if (UserFactory.getUserRemote(null).checkEmail(email)) {   
  125.             return true;   
  126.         }   
  127.         return false;   
  128.     }   
  129.   
  130.     @Override  
  131.     public boolean verifyUser(String userName) {   
  132.         // 判断 用户名是否重复   
  133.         if (UserFactory.getUserRemote(null).findUser(userName) != null) {   
  134.             return true;   
  135.         }   
  136.         return false;   
  137.     }   
  138.        
  139.     @Override  
  140.     public String userEdit(String userName, String email, String nickName,   
  141.             String realName, int sex, String birthday, String mobile) {   
  142.         // email 格式   
  143.         if (!EmailValidator.getInstance().isValid(email)) {   
  144.             return Constants.emailIsNotValid;   
  145.         }   
  146.         // 是否占用   
  147.         if (!UserFactory.getUserRemote(null).isValidEmail(userName, email)) {   
  148.             return Constants.emailExist;   
  149.         }   
  150.         // 修改信息   
  151.         UserFactory.getUserRemote(null).updateUser(userName, email);   
  152.         Profile profile = UserFactory.getProfileRemote(null).findUserByName(   
  153.                 userName);   
  154.         if(StringUtils.isNotBlank(realName)){   
  155.             profile.setRealName(realName);     
  156.         }   
  157.         ProfileExtInfo profileInfo = new ProfileExtInfo(UserFactory   
  158.                 .getPropertySetAccessor(), profile);   
  159.         if(StringUtils.isNotBlank(nickName)){   
  160.             profileInfo.setNickname(nickName);   
  161.         }   
  162.   
  163.         switch (sex) {   
  164.         case 1:   
  165.             profileInfo.setSex(Sex.male);   
  166.             break;   
  167.         case 2:   
  168.             profileInfo.setSex(Sex.famale);   
  169.             break;   
  170.         default:   
  171.             profileInfo.setSex(Sex.unknown);   
  172.             break;   
  173.         }   
  174.   
  175.         if(StringUtils.isNotBlank(birthday)){   
  176.             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
  177.             try {   
  178.                 profileInfo.setBirthday(sdf.parse(birthday));   
  179.             } catch (ParseException e) {   
  180.                 System.out.println("设置生日出错!!!!!!!");   
  181.   
  182.                 profileInfo.setBirthday(new Date());   
  183.                 // e.printStackTrace();   
  184.             }              
  185.         }   
  186.            
  187.         if(StringUtils.isNotBlank(mobile)){   
  188.             profileInfo.setMobile(mobile);   
  189.         }   
  190.            
  191.         UserFactory.getProfileRemote(null).storeUser(profile);   
  192.         UserFactory.getProfileRemote(null).storeUser(profileInfo);   
  193.   
  194.         return Constants.userEditSuccess;   
  195.     }   
  196.   
  197.     @Override  
  198.     public String resetPassword(String userName, String newPassword) {   
  199.         if (StringUtils.isBlank(userName)) {   
  200.             return Constants.usernameIsRequired;   
  201.         }   
  202.         User user = UserFactory.getUserRemote(null).findUser(userName);   
  203.         if (null == user) {   
  204.             return Constants.userNotFound;   
  205.         }   
  206.   
  207.         String username = UserFactory.getUserRemote(null).resetPwd(   
  208.                 user.getUserName(), newPassword);   
  209.         if (username == null) {   
  210.             return Constants.oldPasswordIsNotValid;   
  211.         }   
  212.   
  213.         return Constants.resetPasswordSuccess;   
  214.     }   
  215.   
  216.     @Override  
  217.     public boolean verifyUserByUserNameAndPassword(String userName,   
  218.             String password) {   
  219.         return UserFactory.getUserRemote(null).verify(userName, password);   
  220.     }   
  221.   
  222.     @Override  
  223.     public int login(String userName, String password) {   
  224.   
  225.         // 登录验证   
  226.         try {   
  227.             System.out.println("1");   
  228.             User user = UserFactory.getUserRemote(null).login(userName, password);   
  229.             System.out.println(user.getUserName());   
  230.                
  231.             System.out.println("2");   
  232.         } catch (Exception e) {   
  233.             e.printStackTrace();   
  234.             System.out.println("3");   
  235.             if (e instanceof com.transnal.user.exceptions.BadUserNameOrPasswordAuthenticationException) {   
  236.                 return -1;   
  237.             } else if (e instanceof com.transnal.user.exceptions.DisableUserAuthenticationException) {   
  238.                 return -2;   
  239.             } else if (e instanceof com.transnal.user.exceptions.NotApprovedAuthenticationException) {   
  240.                 return -3;   
  241.             } else if (e instanceof com.transnal.user.exceptions.BadPasswordAuthenticationException) {   
  242.                 return -4;   
  243.             }   
  244.         }   
  245.   
  246.         return Constants.authenticateSuccess;   
  247.     }   
  248.   
  249.     @SuppressWarnings("unchecked")   
  250.     public void updateUserProperties(String userName, List values) {   
  251.   
  252.         Profile profile = UserFactory.getProfileRemote(null).findUserByName(   
  253.                 userName);   
  254.         UserFactory.getProfileRemote(null).storeUser(profile);   
  255.         // 其他属性   
  256.         ProfileInfo info = new ProfileInfo(   
  257.                 UserFactory.getPropertySetAccessor(), profile);   
  258.         for (ProfileValue value : values) {   
  259.   
  260.             if (value.getValue() instanceof java.lang.Integer) {   
  261.                 info.setProperty(value.getKey(), Integer.parseInt(value   
  262.                         .getValue().toString()));   
  263.             } else if (value.getValue() instanceof java.lang.Long) {   
  264.                 info.setProperty(value.getKey(), Long.parseLong(value   
  265.                         .getValue().toString()));   
  266.             } else if (value.getValue() instanceof java.lang.Double) {   
  267.                 info.setProperty(value.getKey(), Double.parseDouble(value   
  268.                         .getValue().toString()));   
  269.             } else if (value.getValue() instanceof java.lang.Boolean) {   
  270.                 info.setProperty(value.getKey(), Boolean.parseBoolean(value   
  271.                         .getValue().toString()));   
  272.             }   
  273.   
  274.             else if (value.getKey().equals("birthday")) {   
  275.                 Date date = null;   
  276.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
  277.                 try {   
  278.                     String a = value.getValue().toString();   
  279.                     date = sdf.parse(a);   
  280.   
  281.                 } catch (ParseException e) {   
  282.                     e.printStackTrace();   
  283.                 }   
  284.                 info.setProperty(value.getKey(), date);   
  285.             }   
  286.   
  287.             else {   
  288.                 info.setProperty(value.getKey(), value.getValue());   
  289.             }   
  290.   
  291.         }   
  292.     }   
  293.   
  294.     @SuppressWarnings("unchecked")   
  295.     public ProfileValue getUserProperties(String userName, String key) {   
  296.   
  297.         Profile profile = UserFactory.getProfileRemote(null).findUserByName(   
  298.                 userName);   
  299.   
  300.         UserFactory.getProfileRemote(null).storeUser(profile);   
  301.   
  302.         ProfileInfo info = new ProfileInfo(   
  303.                 UserFactory.getPropertySetAccessor(), profile);   
  304.   
  305.         ProfileValue value = new ProfileValue();   
  306.   
  307.         value.setKey(key);   
  308.            
  309.         //根据不同的类型设置不同的value   
  310.         if (value.getValue() instanceof java.lang.Integer) {   
  311.             value.setValue(info.getPropertySet().getInt(key));   
  312.   
  313.         } else if (value.getValue() instanceof java.lang.Long) {   
  314.             value.setValue(info.getPropertySet().getLong(key));   
  315.   
  316.         } else if (value.getValue() instanceof java.lang.Double) {   
  317.   
  318.             value.setValue(info.getPropertySet().getDouble(key));   
  319.         } else if (value.getValue() instanceof java.lang.Boolean) {   
  320.             value.setValue(info.getPropertySet().getBoolean(key));   
  321.   
  322.         }   
  323.         else if (value.getKey().equals("birthday")) {   
  324.             Date date = null;   
  325.             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
  326.             try {   
  327.                 String a = value.getValue().toString();   
  328.                 date = sdf.parse(a);   
  329.                 value.setValue(date);   
  330.             } catch (ParseException e) {   
  331.                 e.printStackTrace();   
  332.             }   
  333.         }   
  334.         else {   
  335.             value.setValue(info.getPropertySet().getString(key));   
  336.         }   
  337.         return value;   
  338.     }   
  339. }  

 

 

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

Java代码
  1. package com.transnal.openplatform.ws.security;   
  2.   
  3. import java.util.Arrays;   
  4. import javax.security.auth.callback.Callback;   
  5. import javax.security.auth.callback.CallbackHandler;   
  6. import org.apache.ws.security.WSConstants;   
  7. import org.apache.ws.security.WSPasswordCallback;   
  8. import org.apache.ws.security.WSSecurityException;   
  9. import com.transnal.user.entity.UserEntity;   
  10. import com.transnal.web.UserFactory;   
  11.   
  12.   
  13. public class PasswordHandler implements CallbackHandler {   
  14.   
  15.                  //凡是角色为 ws  的用户 才可访问你的这个 WebService   
  16.     private static final String ROLE_SERVICES="ws";   
  17.        
  18.     public void handle(Callback[] callbacks) throws WSSecurityException {   
  19.   
  20.         WSPasswordCallback callback = (WSPasswordCallback) callbacks[0];   
  21.         String userName = callback.getIdentifer();   
  22.        
  23.         //判断角色   
  24.         String[] roles=UserFactory.getRoleRemote(null).findByUser(userName);   
  25.         if(!Arrays.asList(roles).contains(ROLE_SERVICES)){   
  26.             throw new WSSecurityException(String.format("not '%s' role privilege ", ROLE_SERVICES));   
  27.         }   
  28.            
  29.         if (WSConstants.PASSWORD_TEXT.equals(callback.getPasswordType())) {   
  30.             String pw = callback.getPassword();   
  31.             if (!UserFactory.getUserRemote(null).verify(userName, pw)) {   
  32.                 throw new WSSecurityException("password not match");   
  33.             }   
  34.         } else {   
  35.             UserEntity user = (UserEntity)UserFactory.getUserRemote(null).findUser(userName);   
  36.             callback.setPassword(user.getPassword());   
  37.         }   
  38.   
  39.     }   
  40.   
  41. }  

 

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

Xml代码
  1.  version="1.0" encoding="UTF-8"?>  
  2.  xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"  
  4.     xsi:schemaLocation="   
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   
  6. http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">  
  7.   
  8.       
  9.   
  10.      resource="classpath:META-INF/cxf/cxf.xml" />  
  11.      resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  
  12.      resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
  13.   
  14.      id="utWss4jInHandler" class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">  
  15.           
  16.               
  17.                  key="action" value="UsernameToken Timestamp" />  
  18.                  key="passwordType" value="PasswordText" />  
  19.                  key="passwordCallbackClass"  
  20.                     value="com.transnal.openplatform.ws.security.PasswordHandler" />  
  21.               
  22.           
  23.       
  24.   
  25.       
  26.      id="userService"  
  27.         implementor="com.transnal.openplatform.ws.user.UserServiceImpl"  
  28.          address=" style="COLOR: #ff0000">/userService">  
  29.           
  30.              class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor" />  
  31.              bean="utWss4jInHandler" />  
  32.           
  33.       
  34.   

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

Xml代码
  1.  version="1.0" encoding="UTF-8"?>  
  2.  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">  
  3.   用户管理中心  
  4.   ucmange admin  
  5.     
  6.       
  7.       
  8.         contextConfigLocation  
  9.           
  10.             /WEB-INF/apache-cxf.xml   
  11.           
  12.       
  13.   
  14.          
  15.       
  16.         CXFServlet  
  17.           
  18.             org.apache.cxf.transport.servlet.CXFServlet   
  19.           
  20.         1    
  21.       
  22.       
  23.         CXFServlet  
  24.          style="COLOR: #ff0000">/ws/*  
  25.       
  26.   
  27.      
  28.     
  29.     index.jsp  
  30.     
  31.   

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

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