将参数传递给 REST Web 服务

Passing parameters to REST web-service

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

我已经创建了网络服务,它适用于来自语言 = "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 的 class。

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 的参数有问题,但我不明白具体是什么。 提前致谢。

正如我在评论中提到的,您在 getTranslation() 方法的开头将 fromLanguagetoLanguage 变量硬编码为 engbos。因此,fromLanguage 和 'toLangugaevalues passed togetTranslation()` 方法丢失。

其次,不是用 , 分隔 @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

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

@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

删除或注释 getTranslation() 方法中的以下行:

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

注意:要解决您的问题,上述解决方案就足够了。但是,为了让您更好地编写代码,请参阅以下建议。 除了上述之外,我还看到了两个问题:

  • 您正在 translation 实例变量中存储翻译后的值。如果您使用相同的 Translator 对象(单实例)并且当前翻译失败,getTranslation() 将 return 之前翻译的值。
  • 你为什么用下面的初始化 expr
   XPathExpression expr = xpath.compile("//word['" + wordForTransl + "'='" + wordForTransl + "']/bos/text()");
  • 最后,每次调用 getTranslation() 时都会解析 XML。相反,在 init() 方法中解析一次,然后在 getTranslation() 方法中使用它。

我根据以上几点修改了你的Translatorclass:

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