Hi: I have a JSP that instantiates an object from a Java class. I now need to pass a parameter from a properties file to the Java class, but I realize that the Java class has no access to the ServletContext (a good and a bad thing I guess). Is it wise to import the servlet package into the Java class? Would it be better to create a method in the Java class that sets this parameter and let the servlet access the ServletContext for the parameter? Any other ideas? Thanks much. Karen
Is it wise to import the servlet package into the Java class?
The ServletContext is not accessable outside of the Servlet container, so simply importing the servlet package into your java class is not enough to use it. You will have to let the Servlet call a getter method in this Java class; have it handle the parsing of the properties file and the setting of this parameter.
Making a class "servlet-aware" obviously hampers its possibility for reuse and restricts it for usage only within web applications. Whether this is acceptable or not is up to the purpose of the class. Is it a class that performs general-purpose processing that could be used elsewhere? Or is it a class whose purpose makes sense only in the servlet environment? The goal of keeping JSP pages as Java-free as possible, means that you will indeed have classes that only make sense in the web app environment. And that's fine. The trick is knowing where to draw the line. If you have classes that are general purpose, one way to keep them that way, yet still use them in the web app scenario, is to create facade or delegate classes that are servlet-aware, and serve as 'adapters' between the servlet environment and the servlet-agnostic utility classes.
Thank you Paul and Bear. Currently the class only makes sense in the web environment. However, I think the idea of keeping it a non-servlet is a good one. I will have the JSP access the ServletContext for the attribute and use a setter method in the Java class to set this parameter. Thanks for your help. Karen
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Accessing Servlet Context from a Java Class