Solved

Reading an XML file in WEB-INF with Bean

Posted on 2010-11-14
6
923 Views
Last Modified: 2012-05-10
Hi there experts,

i have a short question:
I'm currently writing my own Web Application with Java and this Webapplication has its own configuration xml files. These files are under the WEB-INF folder, so only the Servlet or JSP can access it.
Now i want to write a Java Bean that reads this config-files and provides some getter functions...
The reason, why i want to write a bean is, because this config files should be accessed by many servlets and some JSPs.

How can i access the config files with a java bean?
and what would be the best way to parse the XMLs?


thx for your help and best regards!
manuel
0
Comment
Question by:mesX
  • 3
  • 3
6 Comments
 
LVL 27

Expert Comment

by:rrz
ID: 34132880
Please read
previous discussion  
We can help you with anyway you want to go with this.
JSTL is the easy way to go.  
0
 

Author Comment

by:mesX
ID: 34134259
Hi and thx for your comment!
As i understand JSTL is only for JSP pages, isn't it?
... and i can't use it within a Java Bean?

Or is my understanding of a Java Bean wrong?
What i want to do is, that my Servlets and JSPs create an Object from my "ApplicationConfig" class which parses the XML and has some getter functions like "String[] getAllEmployeeNames()". So if i change the XML file one day, i just have to re-write my ApplicationConfig class.

Please correct me if my idea is not a good one, because i'm very new to all this :)

regards
Manuel
0
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
ID: 34138005
To get started, try this code.
The file employees.xml contains  
<?xml version="1.0"?>
<company>
	<employee>
		<firstname>John</firstname>
		<lastname>Smith</lastname>
	</employee>
	<employee>
		<firstname>Jane</firstname>
		<lastname>Doe</lastname>
	</employee>
	<employee>
		<firstname>Jerry</firstname>
		<lastname>Brown</lastname>
	</employee>
</company>

Open in new window


put that xml file into your web app's classes folder.

Create a JSP containing  
<jsp:useBean id="reader" class="rrz.XMLReader" />
<%=reader.read()%>

Open in new window


This is just quick and dirty demo code. We should create getter and setter methods for fields in your bean.
Show us an example of your XML and tell us what you want to access, if you want more help.

package rrz;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {
  public String read(){
      StringBuilder sb = new StringBuilder();
      try {
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
           Document doc = db.parse(getClass().getClassLoader().getResourceAsStream("employees.xml"));
           doc.getDocumentElement().normalize();
           sb.append("Root element " + doc.getDocumentElement().getNodeName() + "<br/>");
           NodeList nodeLst = doc.getElementsByTagName("employee");
           sb.append("Information of all employees" + "<br/>");
           for (int s = 0; s < nodeLst.getLength(); s++) {
              Node fstNode = nodeLst.item(s);
              if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                 Element fstElmnt = (Element) fstNode;
                 NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
                 Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                 NodeList fstNm = fstNmElmnt.getChildNodes();
                 sb.append("First Name : "  + ((Node) fstNm.item(0)).getNodeValue() + "<br/>");
                 NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
                 Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                 NodeList lstNm = lstNmElmnt.getChildNodes();
                 sb.append("Last Name : " + ((Node) lstNm.item(0)).getNodeValue() + "<br/>");
              }
           }
      } catch (Exception e) {
                             e.printStackTrace();
        }
      return sb.toString();
  }
}

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:mesX
ID: 34138573
You're absolutely awesome!!!! THANK YOU VERY MUCH!

I just have a very small question:
What if i put the employee.xml directly under the WEB-INF folder? Or in my case /WEB-INF/configs/employee.xml? How can i access files inside the WEB-INF folder but outside the classes folder?


best regards
Manuel
0
 
LVL 27

Assisted Solution

by:rrz
rrz earned 500 total points
ID: 34138969
>How can i access files inside the WEB-INF folder but outside the classes folder?  
There are several ways. One simple way is pass the path from JSP to bean.
<jsp:useBean id="reader" class="rrz.XMLReader" />
<%
  String path = application.getRealPath("/WEB-INF/configs/employees.xml");
  reader.setPath(path);
%>
<%=reader.read()%>

Open in new window

 
and in source code  
File file = new File(path);
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
           Document doc = db.parse(file);

Open in new window

 

Better to solution at  previous discussion
0
 

Author Closing Comment

by:mesX
ID: 34139232
Thank you so much for all your help! You're a truly expert ;)

I hope you can help me in my future questions too (and i will surely have many  ;) )

best regards
Manuel
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mockito example issue 8 62
How do i learn Story Board for IOS ? 3 81
.php tree directory? 5 55
Add image to into animation on website template 1 0
Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now