2

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

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

4

2 回答 2

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;
}
于 2008-10-03T14:29:19.353 回答
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;
}
于 2016-03-17T10:52:08.343 回答