如何读取Servlet请求中存在的xml文件

时间:2014-08-13 06:20:12

标签: java xml servlets servlet-filters

标题请求

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 apis读取参数,如下所示

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

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

1 个答案:

答案 0 :(得分:0)

这就是我使用 org.dom4j.io.SAXReader

HTTPServletRequest读取XML到地图的方法
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;     
}