【发布时间】:2011-08-05 12:51:11
【问题描述】:
我想为我的网络应用创建一个授权过滤器(以便能够限制对某些页面的访问)。
我创建了一个简单的 .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 方法内的 cmets 中解释了我需要做什么。有人可以给我一个提示,告诉我我应该如何遍历文件以查找每种用户类型的页面名称?我尝试从互联网上学习 JAXP 示例,但它们比我需要的要复杂。
更新 xml 存储在 WEB-INF/classes 中
【问题讨论】:
标签: java xml parsing jakarta-ee