2

Java コードの web.xml ファイルで定義されたセキュリティ ロールの完全なリストを取得できるかどうか疑問に思っていました。もしそうなら、どのようにそれを行うのですか?

「isUserInRole」メソッドは認識していますが、ロールが要求されているが、web.xml ファイルで定義されていない (またはスペルが異なる) ケースも処理したいと考えています。

4

2 に答える 2

2

私の知る限り、サーブレット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 に答える