在 WebService 請求過程中動態操作請求/響應資料。分類:按位置 (客戶端/服務端)、按方向 (入/出)、按定義者 (系統/自定義)。
public class AddUserInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
private String name, password;
public AddUserInterceptor(String name, String password) {
super(Phase.PRE_PROTOCOL); // 準備協議化階段攔截
this.name = name; this.password = password;
}
@Override
public void handleMessage(SoapMessage msg) throws Fault {
List<Header> headers = msg.getHeaders();
Document doc = DOMUtils.createDocument();
Element root = doc.createElement("apple");
Element nameEl = doc.createElement("name"); nameEl.setTextContent(name); root.appendChild(nameEl);
Element pwdEl = doc.createElement("password"); pwdEl.setTextContent(password); root.appendChild(pwdEl);
headers.add(new Header(new QName("apple"), root));
System.out.println("client handleMessage...");
}
}
public class CheckUser extends AbstractPhaseInterceptor<SoapMessage> {
public CheckUser() { super(Phase.PRE_PROTOCOL); }
@Override
public void handleMessage(SoapMessage message) throws Fault {
Header header = message.getHeader(new QName("apple"));
if (header != null) {
Element apple = (Element) header.getObject();
String name = apple.getElementsByTagName("name").item(0).getTextContent();
String pwd = apple.getElementsByTagName("password").item(0).getTextContent();
if ("bo ram".equals(name) && "520".equals(pwd)) {
System.out.println("Server 通過攔截器"); return;
}
}
System.out.println("server 未通過攔截器");
throw new Fault(new Exception("請求需要正確的用戶名和密碼"));
}
}
Client client = ClientProxy.getClient(port);
client.getOutInterceptors().add(new AddUserInterceptor("bo ram", "520"));
EndpointImpl ep = (EndpointImpl) Endpoint.publish(address, new Simpleimpl());
ep.getInInterceptors().add(new CheckUser());
完整代碼結構包含:客戶端攔截器、服務端攔截器、客戶端啟動類、服務端發布類。