简体   繁体   English

将参数传递到REST Web服务

[英]Passing parameters to REST web-service

I'm dealing with the problem with passing parameteres to web-service. 我正在处理将参数传递给Web服务的问题。

I have created web-service which works OK for the case fromLanguage = "eng" 我已经创建了Web服务,对于fromLanguage =“ eng”的情况来说可以正常工作

But, when I test service through Glassfish console and send fromLanguage = "bos" I don't get appropriate result. 但是,当我通过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);        
}

} }

This is XML fajl which I try to parse: 这是我尝试解析的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>

And this is the class which I'm using for parsing XML. 这是我用于解析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!";
        }
    }
}

It seems to me that something is wrong with the parameters fromLanguage and toLanguage, but I can't realize what exactly. 在我看来,参数fromLanguage和toLanguage出了点问题,但我无法确切知道是什么。 Thanks in advance. 提前致谢。

As I mentioned in the comment, you have hardcoded fromLanguage and toLanguage variables to eng and bos at the beginning of getTranslation() method. 正如我在评论中提到的,您已经在getTranslation()方法开始时将fromLanguagetoLanguage变量硬编码为engbos Due to this, the fromLanguage and 'toLangugae values passed to getTranslation()` method are lost. 因此, values passed to getTranslation()方法的fromLanguage和'toLangugae values passed to将丢失。

Secondly, instead of separating @PathParm by , separate those by / . 其次,代替分离@PathParm通过,分离那些通过/ It will look like: 它看起来像:

@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

Alternatively use @QueryParam . 或者使用@QueryParam In that case your path would be: 在这种情况下,您的路径将是:

@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

Remove or comment the below lines in getTranslation() method: getTranslation()方法中删除或注释以下行:

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

Note: To fix your issue the above solution is sufficient . 注意: 要解决您的问题,上述解决方案就足够了 However, to make you code better please see the below suggestions. 但是,为了使您的代码更好,请参见以下建议。 In addition to the above I see two more issues: 除了上述内容,我还看到了另外两个问题:

  • You are storing translated value in translation instance variable. 您将翻译后的值存储在translation实例变量中。 In case you are using the same Translator object (singleton instance) and the current translation fails, getTranslation() will return the previously translated value. 如果您使用相同的Translator对象(单个实例)并且当前转换失败,则getTranslation()将返回先前转换的值。
  • Why are you initializing expr with the below? 为什么用以下内容初始化expr
   XPathExpression expr = xpath.compile("//word['" + wordForTransl + "'='" + wordForTransl + "']/bos/text()");
  • Lastly, every time you are calling getTranslation() the XML is being parsed. 最后,每次调用getTranslation()时,都会对XML进行解析。 Instead, parse it once in init() method and then use it in getTranslation() method. 而是在init()方法中解析一次,然后在getTranslation()方法中使用它。

I have modified your Translator class based on the above points: 我根据以上几点修改了您的Translator类:

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!";
            }
        }
    }
}

Here is the output: 这是输出:

kuca
game

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM