【问题标题】:How to read xml file present in Servlet request如何读取 Servlet 请求中存在的 xml 文件
【发布时间】:2014-08-13 06:20:12
【问题描述】:

标头请求

POST http://{URL} HTTP/1.1
Accept: */*
Accept-Language: en-us
Content-Type: text/xml; charset=UTF-8
Accept-Encoding: gzip, deflate
Content-Length: 1049
Connection: Keep-Alive
Pragma: no-cache
<?xml version="1.0"?>
 <userID>dummy</userID>
<password>pwd</password>

我有上面的请求,它被发送到 doFilter 中的 ServletRequest。 我可以使用如下的servet api来读取参数

HttpServletRequest req = (HttpServletRequest) request;
Enumeration<String> params = req.getParameterNames();

如何读取 xml 内容以便使用 Java 中的 servlet 检索该 xml 中的用户 ID

【问题讨论】:

标签: java xml servlets servlet-filters


【解决方案1】:

这就是我使用 org.dom4j.io.SAXReader 将 XML 从HTTPServletRequest 读入地图的方法

public  static Map<String, String>  parseXml(HttpServletRequest request) throws    IOException, DocumentException {
    Map<String,String> map=new HashMap<String,String>();
    InputStream is =request.getInputStream();
    SAXReader reader=new SAXReader();
    Document document=reader.read(is);      
    Element root =document.getRootElement();

    List<Element> elementList=root.elements();

    for(Element e: elementList){
        map.put(e.getName(), e.getText());
    }

    //now your map will have below mapping 
    //"userID"->"dummy"
    //"password"->"pwd"

    return map;     
}

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 2011-03-26
    • 1970-01-01
    • 2012-08-01
    • 2016-03-15
    • 2011-07-11
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多