J2EE之wildfly 实践6 -- 编写webservice服务并跨语言调用
实践目标:
- 使用JAX-WS编写webservice服务并发布到wildfly中
- 使用c#调用webservice服务
- 增加webservice安全性
(转载请注明来源:cnblogs coder-fang)
- 在项目中编写webservice接口并部署到wildfly中,代码如下:
@WebService(serviceName="userservice",targetNamespace="http://192.168.50.253:8080") @SOAPBinding(style=Style.RPC) @BindingType(value="http://www.w3.org/2003/05/soap/bindings/HTTP/") public class UserWSService{ private final Logger logger = Logger.getLogger(UserWSService.class); @Resource WebServiceContext wsctx; //认证代码 private Boolean isValid() { MessageContext mctx = wsctx.getMessageContext(); Map http_headers = (Map) mctx.get( MessageContext.HTTP_REQUEST_HEADERS); List<String> userList = (List) http_headers.get("Username"); List<String> passList = (List) http_headers.get("Password"); String username = ""; String password = ""; if (userList != null) { username = userList.get(0); } if (passList != null) { password = passList.get(0); } if (username.equals("test")&&password.equals("123")) { return true; } else { return false; } } @WebMethod @WebResult(name="result") public String EqualTest(@WebParam(name="first") String fstring,@WebParam(name="second") String sstring) { if (!isValid()) { return "auth failed"; } if (fstring.equals(sstring)) { return "equal ok"; } return "equal error"; } }
注:isValid是认证函数,远程调用时需要在soap头加入认证信息才可调用相关方法
- 编写c#客户端代码(如何引用webservice服务简单百度一下):
UserServiceRef.UserWSServiceClient client = new UserServiceRef.UserWSServiceClient(); //add header OperationContextScope scope = new OperationContextScope(client.InnerChannel); var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers["Username"] = "test"; httpRequestProperty.Headers["Password"] = "123"; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; //end header Console.WriteLine(client.EqualTest("a", "b")); Console.WriteLine(client.EqualTest("a", "a"));
- 运行客户端输出结果:
- 如果 注释掉 //add header中的认证内容,再运行客户端,效果如下:
至此,wildfly部署webservice与跨语言调用已完成。