在JAX WS標準中,作websevice變得容易,都是用註解等就能夠實現了,其中用來作
webservice的權限也是很容易的,好比要根據用戶名和密碼才能訪問ws,下面直接代碼,
給出對應的例子,使用的是cxf了.
1 ws接口類
[code="java"]
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld {
@WebMethod
String getHelloWorldMessage();
}
[/code]
2 WS 接口實現類:
[code="java"]
@WebService(endpointInterface = "com.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Resource WebServiceContext wsctx; @Override public String getHelloWorldMessage() { 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("password")) { return "Hello " + username + " to world of Jax WS - Valid User!"; } else { return " User No Valid!"; } } } [/code] 其中,其實就是取出header的信息取進行判斷是否有這個權限了,很容易明白. 3 而後是發佈這個ws [code="java"] public static void main(String[] args){ Endpoint.publish( "http://localhost:9000/ws/hello", new HelloWorldImpl()); } [/code] 4 客戶端去調用這個WS,其中注意要用戶名和密碼的傳遞,這裏爲了簡單,沒用證書等了, 只是示意,其實是複雜多了: [code="java"] public class HelloWorldClient { private static final String WS_URL = "http://localhost:9000/ws/hello?wsdl"; public static void main(String[] args) throws Exception { URL url = new URL(WS_URL); QName qname = new QName( "http://ws.test.com/", "HelloWorldImplService"); Service service = Service.create(url, qname); HelloWorld hello = service.getPort(HelloWorld.class); BindingProvider provider = (BindingProvider) hello; Map<String, Object> req_ctx = provider.getRequestContext(); req_ctx.put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL); //調用的用戶名和密碼,用map Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Username", Collections.singletonList("test")); headers.put("Password", Collections.singletonList("password")); req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } } [/code] 其實核心就是: headers.put("Username", Collections.singletonList("test")); headers.put("Password", Collections.singletonList("password")); req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); 在消息頭中設置好MAP就能夠了.