使用JAXP解析简单的XML文档(JEE6)

时间:2011-04-14 12:57:11

标签: java xml parsing java-ee

我想为我的网络应用创建授权过滤器(以便能够限制对某些网页的访问)。

我创建了一个简单的.xml文件,其中包含允许每个用户访问的页面:

  <access>
    <buyer>
        <page>buyoffer.xhtml</page>
        <page>faq.xhtml</page>
        <page>index.jsp</page>
        <page>login.xhtml</page>
        <page>main.xhtml</page>
        <page>registrationSucceded.xhtml</page>     
    </buyer>
    <seller>
        <page>sellerpanel.xhtml</page>
        <page>faq.xhtml</page>
        <page>index.jsp</page>
        <page>login.xhtml</page>
        <page>main.xhtml</page>
        <page>registrationSucceded.xhtml</page>     
    </seller>
    <administrator>
        <page>sellerpanel.xhtml</page>
        <page>faq.xhtml</page>
        <page>index.jsp</page>
        <page>login.xhtml</page>
        <page>main.xhtml</page>
        <page>registrationSucceded.xhtml</page>     
    </administrator>
</access>

然后我需要进行解析以提取页面的值,以便能够创建允许或重定向的条件(依赖)。我只需要告诉某人如何从xml中提取这些页面的值。这就是我现在所做的:

public class RestrictPageFilter implements Filter {

    private FilterConfig fc;
    private DocumentBuilder builder;
    private Document document;

    public void init(FilterConfig filterConfig) throws ServletException {
        // The easiest way to initialize the filter
        fc = filterConfig;
        // Get the file that contains the allowed pages
        File f = new File("/allowedpages.xml");
        // Prepare the file parsing
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            document = builder.parse(f);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);
        String pageRequested = req.getRequestURL().toString();

        // Get the value of the current logged user
        Role currentUser = (Role) session.getAttribute("userRole");
        if (currentUser != null) {
            if(currentUser.getType().equals("BUYER")) {
                //Loop BUYER Element of the .xml
                //if pageRequested.contains(value of the page at buyer element)             
                // chain.doFilter(request, response);
                // Else
                // Redirect the user to the main page
            }
            else if(currentUser.getType().equals("SELLER")) {
                //Same as above just for seller element
            }
            else if(currentUser.getType().equals("ADMINISTRATOR")) {
                //Same as above just for administrator element
            }           
        }
    }

    public void destroy() {
        // Not needed
    }
}

在doFilter方法内的注释中解释了我需要做什么。有人可以给我一个提示,我应该如何遍历文件来查找每个用户类型的页面名称?我尝试从互联网上关注JAXP示例,但它们比我需要的更复杂。

更新的 xml存储在WEB-INF / classes

3 个答案:

答案 0 :(得分:10)

而是使用JAXB。 JAXP是一个古老且非常详细的API。 JAXB倾向于Javabeans,因此干净且相对容易。首先创建一个Javabean,它使用javax.xml.bind注释将1:1映射到XML文件。

@XmlRootElement
public class Access {

    @XmlElement
    private User buyer;

    @XmlElement
    private User seller;

    @XmlElement
    private User administrator;

    public User getBuyer() {
        return buyer;
    }

    public User getSeller() {
        return seller;
    }

    public User getAdministrator() {
        return administrator;
    }

    public static class User {

        @XmlElement(name="page")
        private List<String> pages;

        public List<String> getPages() {
            return pages;
        }

    }

}

然后执行以下部分来映射它(假设allowedpages.xml放在类路径的根目录中)。

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("allowedpages.xml");
Access access = (Access) JAXBContext.newInstance(Access.class).createUnmarshaller().unmarshal(input);

请注意,您不应使用new File()。另请参阅getResourceAsStream() vs FileInputStream

最后,您可以按如下方式访问所有买家页面:

List<String> buyerPages = access.getBuyer().getPages();
// ...

毋庸置疑,养老保障并不总是最佳做法。 Java EE 6附带容器管理的安全性。

答案 1 :(得分:1)

我可以问你为什么要重新发明轮子?如果您正在使用Java EE 6,为什么不使用类似于您所做的内置安全机制,但本质上是声明性的?

请阅读this article

基本上,它将归结为在web.xml中写下这个:

<security-constraint>
   <display-name>For users in buyer role</display-name>
   <web-resource-collection>
      <web-resource-name>Restricted Access - Buyers Only</web-resource-name>
      <url-pattern>buyoffer.xhtml</url-pattern>
      <url-pattern>faq.xhtml</url-pattern>
      <url-pattern>index.jsp</url-pattern>
      <url-pattern>login.xhtml</url-pattern>
      <url-pattern>main.xhtml</url-pattern>
      <url-pattern>registrationSucceded.xhtml</url-pattern> 
      <http-method>GET</http-method>
   </web-resource-collection>
   <auth-constraint>
      <role-name>Buyer</role-name>
   </auth-constraint>
   <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
   </user-data-constraint>
</security-constraint>

以上示例适用于买方角色。

答案 2 :(得分:0)

使用NodeList nodes = document.getElementsByTagName(tagname);标记名应该是买方或卖方等,因为您需要它。迭代节点列表并读取数据。