我正在处理将参数传递给Web服务的问题。

我已经创建了Web服务,对于fromLanguage =“ eng”的情况来说可以正常工作

但是,当我通过Glassfish控制台测试服务并从fromLanguage =“ bos”发送时,没有得到适当的结果。

package pckgTranslator;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/MyRestService/{wordToTranslate},{fromLanguage},{toLanguage}")
public class clsTranslate {
@GET
public String doGet(@PathParam("wordToTranslate") String wordToTranslate,
        @PathParam("fromLanguage") String fromLanguage, @PathParam("toLanguage")  String toLanguage)
        throws Exception{
    Translator translator = new Translator();
    return translator.getTranslation(wordToTranslate,fromLanguage, toLanguage);
}


}

这是我尝试解析的XML fajl:

<?xml version="1.0" encoding="utf-8" ?>
<gloss>
    <word id="001">
        <eng>ball</eng>
        <bos>lopta</bos>
    </word>
    <word id="002">
        <eng>house</eng>
        <bos>kuca</bos>
    </word>
    <word id="003">
        <eng>game</eng>
        <bos>igra</bos>
    </word>
</gloss>


这是我用于解析XML的类。

package pckgTranslator;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Translator {

String translation = null;

String getTranslation(String wordForTransl, String fromLanguage, String toLanguage)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    //fromLanguage = "eng";
    //toLanguage = "bos";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream is = Translator.class.getResourceAsStream("/resource/glossary.xml");
    Document doc = builder.parse(new InputSource(is));

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    //XPathExpression expr = null; //xpath.compile("//word[eng='house']/bos/text()");
    XPathExpression expr = xpath.compile("//word['" + wordForTransl + "'='" + wordForTransl + "']/bos/text()");
    if (fromLanguage == "eng") {
        expr = xpath.compile("//word[eng='" + wordForTransl + "']/bos/text()");
    } else if (fromLanguage == "bos") {
        expr = xpath.compile("//word[bos='" + wordForTransl + "']/eng/text()");

    }

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        //System.out.println(nodes.item(i).getNodeValue());
        translation = nodes.item(i).getNodeValue();
    }
    //return nodes.item(i).getNodeValue();
    if (translation != null) {
        return translation;
    } else {
        return "We are sorry, there is no translation for this word!";
        }
    }
}


在我看来,参数fromLanguage和toLanguage出了点问题,但是我无法确切地知道是什么。
提前致谢。

最佳答案

正如我在评论中提到的,您已经在fromLanguage方法的开头将toLanguageeng变量硬编码为bosgetTranslation()。因此,fromLanguage和'toLangugae values passed to getTranslation()`方法丢失了。

其次,不要用@PathParm分隔,。它看起来像:

@Path("/MyRestService/{wordToTranslate}/{fromLanguage}/{toLanguage}")
@GET
public String doGet(@PathParam("wordToTranslate") String wordToTranslate,
@PathParam("fromLanguage") String fromLanguage, @PathParam("toLanguage")  String toLanguage) throws Exception

Invocation: curl -X GET http://localhost:8080/MyRestService/x/y/z


或者使用/。在这种情况下,您的路径将是:

@Path("/MyRestService")
public String doGet(@QueryParam("wordToTranslate") String wordToTranslate,
@QueryParam("fromLanguage") String fromLanguage, @QueryParam("toLanguage")  String toLanguage) throws Exception

Invocation: curl -X GET http://localhost:8080/MyRestService?wordToTranslate=x&fromLanguage=y&toLanguage=z


@QueryParam方法中删除或注释以下行:

fromLanguage = "eng";
toLanguage = "bos";




注意:要解决您的问题,上述解决方案就足够了。但是,为了使您的代码更好,请参见以下建议。
除了上述内容,我还看到了另外两个问题:


您将转换后的值存储在getTranslation()实例变量中。如果您使用相同的Translator对象(单个实例)并且当前转换失败,则translation将返回先前转换的值。
为什么用以下内容初始化getTranslation()


   XPathExpression expr = xpath.compile("//word['" + wordForTransl + "'='" + wordForTransl + "']/bos/text()");



最后,每次调用expr时,都会对XML进行解析。而是在getTranslation()方法中解析一次,然后在init()方法中使用它。


我根据以上几点修改了您的getTranslation()类:

package org.openapex.samples.misc.parse.xml;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.IOException;
import java.io.InputStream;

public class ParseXMLAndTranslate {
    public static void main(String[] args) throws Exception{
        Translator translator = new Translator();
        translator.init();
        System.out.println(translator.getTranslation("house","eng", "bos"));
        System.out.println(translator.getTranslation("igra","bos", "eng"));
    }

    private static class Translator {
        //String translation = null;
        private Document doc;
        public void init() throws ParserConfigurationException, SAXException, IOException{
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputStream is = Translator.class.getResourceAsStream("/resource/glossary.xml");
            this.doc = builder.parse(new InputSource(is));
        }

        String getTranslation(String wordForTransl, String fromLanguage, String toLanguage)
                throws XPathExpressionException {
            //fromLanguage = "eng";
            //toLanguage = "bos";
            XPathFactory xpathfactory = XPathFactory.newInstance();
            XPath xpath = xpathfactory.newXPath();

            //XPathExpression expr = null; //xpath.compile("//word[eng='house']/bos/text()");
            //XPathExpression expr = xpath.compile("//word['" + wordForTransl + "'='" + wordForTransl + "']/bos/text()");
            XPathExpression expr = null;
            if (fromLanguage == "eng") {
                expr = xpath.compile("//word[eng='" + wordForTransl + "']/bos/text()");
            } else if (fromLanguage == "bos") {
                expr = xpath.compile("//word[bos='" + wordForTransl + "']/eng/text()");
            }

            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            String translation = null;
            /*for (int i = 0; i < nodes.getLength(); i++) {
                //System.out.println(nodes.item(i).getNodeValue());
                translation = nodes.item(i).getNodeValue();
            }*/
            if(nodes.getLength() > 0){
                translation = nodes.item(0).getNodeValue();
            }
            //return nodes.item(i).getNodeValue();
            if (translation != null) {
                return translation;
            } else {
                return "We are sorry, there is no translation for this word!";
            }
        }
    }
}


这是输出:

kuca
game

10-04 23:25