【问题标题】:Retrieve list of defined roles in java ee 5检索 java ee 5 中已定义角色的列表
【发布时间】:2008-10-03 11:29:33
【问题描述】:

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

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

【问题讨论】:

    标签: java security jakarta-ee


    【解决方案1】:

    据我所知,在 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;
    }
    

    【讨论】:

    • 太糟糕了,容器无法提供获取该信息的方法,但这似乎是一个很好的解决方法。谢谢!
    【解决方案2】:

    这是 Ian 使用更新的 DOM API 的答案版本:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 2011-06-04
      • 2014-12-09
      • 2013-05-14
      • 2019-10-19
      • 2013-12-12
      • 1970-01-01
      • 2015-07-16
      • 2011-01-14
      相关资源
      最近更新 更多