在java ee 5中检索已定义角色的列表

时间:2008-10-03 11:29:34

标签: java security java-ee

我想知道是否有可能检索java代码中web.xml文件中定义的完整安全角色列表?如果是这样的话怎么办?

我知道'isUserInRole'方法,但我也想处理在web.xml文件中请求但未定义(或拼写不同)角色的情况。

2 个答案:

答案 0 :(得分:2)

据我所知,在Servlet API中无法做到这一点。但是,您可以直接解析web.xml并自行提取值。我在下面使用了dom4j,但你可以使用你喜欢的任何XML处理:

protected List<String> getSecurityRoles() {
    List<String> roles = new ArrayList<String>();
    ServletContext sc = this.getServletContext();
    InputStream is = sc.getResourceAsStream("/WEB-INF/web.xml");

    try {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(is);

        Element webApp = doc.getRootElement();

        // Type safety warning:  dom4j doesn't use generics
        List<Element> roleElements = webApp.elements("security-role");
        for (Element roleEl : roleElements) {
            roles.add(roleEl.element("role-name").getText());
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    return roles;
}

答案 1 :(得分:0)

以下是使用较新DOM API的Ian答案的版本:

private List<String> readRoles() {
    List<String> roles = new ArrayList<>();
    InputStream is = getServletContext().getResourceAsStream("/WEB-INF/web.xml");

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new InputSource(is));

        NodeList securityRoles = doc.getDocumentElement().getElementsByTagName("security-role");
        for (int i = 0; i < securityRoles.getLength(); i++) {
            Node n = securityRoles.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                NodeList roleNames = ((Element) n).getElementsByTagName("role-name");
                roles.add(roleNames.item(0).getTextContent().trim()); // lets's assume that <role-name> is always present
            }
        }
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new IllegalStateException("Exception while reading security roles from web.xml", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.warn("Exception while closing stream", e);
            }
        }
    }

    return roles;
}