更改(或设置)编码的网络服务

4
我有一个使用JAX-WS API(一种SOAP Web服务)的Web服务。
import javax.jws.WebService;

@WebService
public class Accounts {
    public String getFullName(String userID){
        AccountManager GFN = new AccountManager();
        return GFN.getFullName(userID);
    }

我应该怎样将它的编码改为“UTF-8”(用于非英语字符)?我找到了像“@Produces("text/html; charset=UTF-8")”这样的东西,但这是针对JAX-RS(restful web service)的,我需要针对JAX-WS的内容。谢谢。

1个回答

1
开始之前,您需要尽早获得SOAP消息。最好的起点是javax.xml.ws.handler.LogicalHandler(与更常见的处理程序类型SOAPHandler相对)。 LogicalHandlerSOAPHandler之前拦截SOAP有效载荷,因此这是理想的位置。
在此处理程序中,您可以随心所欲地处理消息,远在编码成问题之前。您的代码应该像这样。
public class YourHandler implements LogicalHandler{

    public boolean handleMessage(LogicalMessageContext context) {
    boolean inboundProperty= (boolean)context.get(MessageContext.MESSAGE_INBOUND_PROPERTY);

         if (inboundProperty) {
              LogicalMessage lm = context.getMessage();
              Source payload = lm.getPayload();
              Source recodedPayload = modifyEncoding(payload); //This is where you change the encoding. We'll talk more about this
              lm.setPayload(recodedPayload) //remember to stuff the payload back in there, otherwise your change will not be registered
         } 

    return true;
    }   

}

现在你已经有了这条消息。如何处理编码的更改可能会比较棘手,但完全由您决定。
您可以选择在整个消息上设置编码,或者通过导航(使用)到您感兴趣的字段并仅操作该字段。即使对于这两个选项,也有几种实现方式。我将采用懒惰的方式:在整个有效载荷上设置编码:
     private Source modifyEncoding(Source payload){
         StringWriter sw = new StringWriter();
         StreamSource newSource = null;     
             try {
                  TransformerFactory transformerFactory = TransformerFactory.newInstance();
                  Transformer transformer = transformerFactory.newTransformer();
                  transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //this determines the outcome of the transformation
                  StreamResult output =  new StreamResult(sw);
                  transformer.transform(source, output);
                  StringReader sReader = new StringReader(sw.toString());
                  newSource = new StreamSource(sReader);//Stuff the re-encoded xml back in a Source
             } catch(Exception e){
               ex.printStackTrace();
             }
         return newSource;
     }

在使用了LogicalHandler之后,现在你需要使用SOAPHandler。在这里,设置编码更加简单,但是它的行为依赖于具体实现。你的SOAPHandler可以像这样:
   public class YourSOAPHandler implements SOAPHandler{

        public boolean handleMessage(SOAPMessageContext msgCtxt){
        boolean inbound = (boolean)msgCtxt.get(MessageContext.MESSAGE_INBOUND_PROPERTY);

           if (inbound){
             SOAPMessage msg = msgCtxt.getMessage();
             msg.setProperty(javax.xml.soap.SOAPMessage.CHARACTER_SET_ENCODING,"UTF-8");

             msgCtxt.Message(msg); //always put the message back where you found it.
           } 
       }      
     return true;
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接