我正在开发一个Java Web服务。目前我可以获取HTTP头请求。但我希望添加更多的头请求。
我目前是在Servlet过滤器中完成此操作。
@WebFilter(urlPatterns = {"/*"})
public class AddHeader implements Filter {
@Resource
private WebServiceContext context;
public AddHeader() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(
ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request.getContentLength() != -1 && context != null) {
MessageContext mc = context.getMessageContext();
((HttpServletResponse) response).addHeader(
"Operation", "something"
);
}
chain.doFilter(request, response);
}
}
这种策略的问题在于添加的标题是静态的。使用SoapHandler类,我可以获取一个SOAP消息-动态的。public class SoapClass implements SOAPHandler<SOAPMessageContext> {
@Override
public boolean handleMessage(SOAPMessageContext messageContext) {
log(messageContext);
return true;
}
@Override
public Set<QName> getHeaders() {
Set<QName> qNames = Collections.EMPTY_SET;
return qNames;
}
@Override
public boolean handleFault(SOAPMessageContext messageContext) {
log(messageContext);
return true;
}
@Override
public void close(MessageContext context) {
}
public static String getMsgAsString(SOAPMessage message) {
String msg = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
msg = baos.toString();
} catch (SOAPException | IOException soape) {
}
return msg;
}
private String soapToString(SOAPMessage message, boolean indent) {
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(message.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return (indent ? sw.toString() : sw.toString().replaceAll("[\\r\\n]", ""));
}
所以,我真正想做的是将动态SOAP消息与过滤器结合起来。我该如何实现这一点?