tags:

views:

84

answers:

2

I am writing a class in JSP to retrieve a bunch of config values from an XML file. My plan is to have a class "XMLConfig" that loads in the values from the file, and then uses access methods to get at the values in the config object.

My problem is that i cannot seem to call application.getRealPath() from within the class, since eclipse tells me that "application cannot be resolved". I suspect that I must change "application" to something else but I am unsure what.

My code for the class:

<%!
//Config object
public class XMLConfig {

 public boolean loadConfigFile(String strName) {
  String XMLfileName = application.getRealPath(strName);
  try {
   DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document doc = null;
   doc = db.parse(XMLFileName);
  }catch(Exception e)
  {
   System.out.println(e.getMessage());
   return false;
  }
  return true;

 }
}
%>
A: 

application isn't a global var. If you want to use it in your method then you'll need to pass it as a parameter.

Not sure why you're defining the class within the jsp though instead of just creating a 'normal' java class.

objects
Thanks for that tip. I read up on importing my own java classes and now have the class in a separate .java file. The getRealPath() problem is not really an issue anymore, but this was very useful.
Kris M
A: 

That's a job for a servlet instead of JSP. Create a class which extendsHttpServlet and implement the doGet() method as follows:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String strName = getOrDefineItSomehow();
    Document doc = loadConfigFile(getServletContext().getRealPath(strName));
    // Do whatever you want with it and then display JSP page.
    request.getRequestDispatcher("/WEB-INF/config.jsp").forward(request, response);
}

Map this servlet in web.xml on an url-pattern of for example /config and invoke it by for example http://example.com/context/config. It'll run the code in doGet().

See also:

BalusC