使用JAXP解析简单的XML文档

使用JAXP解析简单的XML文档

本文介绍了使用JAXP解析简单的XML文档(JEE6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create an authorization filter for my web app(To be able to restrict access to certain pages).

我创建了一个简单的.xml文件每个用户都可以访问的页面:

I created a simple .xml file with the pages that each user is allowed to visit:

  <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中提取这些页面的值。这就是我现在所做的:

Then i need to do parsing to extract the value of the pages, to be able to create conditions to allow or redirect(Depending). I just need somebody to tell be how to extract the values of those pages from the xml. This is what i did till now:

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示例,但它们比我需要的更复杂。

In the comments inside the doFilter method is explained what i need to do. Could someone give me a tip on how i should iterate through the file to find the page names for each of the user types? I try to follow JAXP examples from the internet, but they are more complex than what i need.

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

UpdateThe xml is stored in WEB-INF/classes

推荐答案

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

Rather use JAXB. JAXP is an old and very verbose API. JAXB leans on Javabeans and is therefore clean and relatively easy. First create a Javabean which maps 1:1 to the XML file using javax.xml.bind annotations.

@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 放在类路径的根目录中)。

Then execute the following piece to map it (assuming that allowedpages.xml is placed in root of the classpath).

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

请注意,您不应使用 new File()为此。另请参见。

Note that you should NOT use new File() for this. See also getResourceAsStream() vs FileInputStream.

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

Finally you can access all buyer pages as follows:

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

毋庸置疑,家庭安保并非总是最好的实践。 Java EE 6附带容器管理的安全性。

Needless to say that homegrowing security isn't always the best practice. Java EE 6 ships with container managed security.

这篇关于使用JAXP解析简单的XML文档(JEE6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:37
查看更多