Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

JSP Configuration FIle

Posted on 2006-04-12
28
Medium Priority
?
1,711 Views
Last Modified: 2012-06-21
I am new to JSP develeopment.  I come from the .NET world.  In ASP.NET web applications, each web-app uses a web.confg XML file which is configuration info specific to the web application.  In addition to having built in configuration settings, I as the developer can add my own custom configuration values into the file, and read them using internal .NET classes.

Is there an equivelant or similar concept available in JSP, and if so, how do I use it?

Thanks
0
Comment
Question by:mmarksbury
  • 8
  • 8
  • 7
  • +2
28 Comments
 
LVL 23

Assisted Solution

by:Siva Prasanna Kumar
Siva Prasanna Kumar earned 400 total points
ID: 16437048
i think web.xml is similar to web.config.

just check out this link to see how to configure it.

http://edocs.bea.com/wls/docs61/webapp/webappdeployment.html

Thank you
0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16440097
Excellent.  Points coming, but one more question.

I have a class library that is separate from the Web App.  I guess you'd call that the Model tier in Java.

Is it possible to access the "Current" Servlet context from a class library?  I've done this several times in .NET, but haven't seen a way to in JAVA.  I don't want to be forced into instantiating everything with the Context as an argument.

More specifically, I'd like to store information such as my connection string, SMTP server host name, and other values in the config file, and access them from the class library.

Any suggestions?

By the way, our server is running 1.4.

Thanks.
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16442072
I think its possible to access the "Current" Servlet context from a class library.

just check

http://www.novocode.com/doc/servlet-essentials/chapter3.html

if not sufficient just check out

http://www.roseindia.net/servlets/servletslinks.shtml

& as J2ee 1.4 supports servlets 2.4 just check out the specifications for more advanced features supported.

Thank You.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16442978
Also you can sett a xml as Context-param and use suitably please check out the details of using context parameters its easy & effcient way.
0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16445902
I looked at Context Parameters from your orginal post, but they seem dependent on an active ServletContext, hence my second post.  I'll take a look and give a try in the next fe hours when I get into work.  Thank.
0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16446959
Thanks for the info.  This seems more like allowing one Servlet to communicate with another and reading static resources from servlets.

Does anyone have a specific example (in code) of how I can call the context paramters stored in the web.xml file from a class in a class library?
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16447341
http://www.phptr.com/articles/article.asp?p=26118&seqNum=3&rl=1

I will try to help with more example but for now check out this above link.

Thank You.
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16459058
http://forum.springframework.org/archive/index.php/t-14607.html

http://www.thearcmind.com/confluence/display/SpribernateSF/Configuring+Hibernate,+Spring,+OpenInSessionViewFilter+and+MyFaces+JSF
i think this will help you.

just only check the way of defining the context parameter and using it in web.xml other things are applicatopn or framework specific.

Actually they use applicationContext.xml with spring frame work in similar fashion if you want you can check out more about it in goolge

Thank You.
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16487001
is there some way i can help????
:-)
0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16488025
Please.

I can easily create context params in the web.xml file...that is straight forward.

What I have not received an answer for, is how I can access those variables from a Java Class that doesn't have access to the Servlet Context (i.e., I don't want to have to pass the session object to a method to get the values).

So, basically, I have two questions....

1. Can I access the "Current Context" from a class (without passing anything in)?

AND

2. How can I do it (sample code please).
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16490609
Just tell me weather the java class you are talking about is there in a Web Aplication or a Standalone application.

if it is a web application the you check out these

http://www.examcram2.com/articles/article.asp?p=31669&seqNum=2&rl=1

http://www.devshed.com/c/a/Java/Overview-of-Java-Web-Technologies-1/6/

especially concentrate on 2nd link read 6th & 7 th articales in the second Link.

Bye.


0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16490689
The class is a standalone class in a class library, hence the need to access the "Current" context.

This is easily accomplished in .NET, and being new to Java, I just want to know if it CAN be done, and how.  I am not seeing this in any of the links that have been posted.

In .NET, I do this with a simple line of code:
HttpContext TempContext = Application.Context.Current;

Now, I don't expect it to be that easy in Java, but I would like a more clear explanation of IF and HOW.
0
 
LVL 23

Expert Comment

by:Siva Prasanna Kumar
ID: 16527803
I think That can't be done even i check out my best as the context of a web application is created by the WebContainer you cannot access it from out the Web application any way if you want to access it from web application you can use the above link which i aske dyou to refer or can try this.

http://www.java2s.com/Code/Java/JSP/Page-Context.htm

Thank You.

It was a Superb experience answering your question as i was able to understand and go through lots of stuff which will be very useful for me in my career.

Thanks again and Bye.
0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16527903
It's too bad that the Java language does not make tasks like this possible.  By exposing a programatic pathway to the current Context, you are providing the programmer with a much more useful toolset.  

ASP.NET provides this functionality, and what it allows me to do is create object level class librararies that communicate directly with the Session as well as the application configuration XML file.

The simple ability to create static GET/SET functionality for session and configuration variables was my ultimate goal, but sadly it seems as though Java is again, dissapointing me.

I'll leave this question open a few more days in the event that someone else has found a tweak or workaround.  Thanks for all your help.
0
 
LVL 28

Expert Comment

by:rrz
ID: 16528621
I am not an expert on this aspect of J2EE, but I can't let this go unchallenged.  Here is all I can offer at the moment.  
http://tomcat.apache.org/tomcat-5.5-doc/jndi-resources-howto.html
I posted a link to here at the expert's thread. Maybe someone will help you.      rrz
0
 
LVL 35

Expert Comment

by:TimYates
ID: 16532287
Why not do it as a Filter?

Then you can add your filter in web.xml to intercept calls that match a particular URL, and manipulate the Session from there?

Tim
0
 
LVL 35

Expert Comment

by:TimYates
ID: 16532288
0
 
LVL 28

Expert Comment

by:rrz
ID: 16547697
Ok, I know you posted  this
>I don't want to be forced into instantiating everything with the Context as an argument.
but I guess that is about it.  Maybe a little better way would be to pass in the session.
YourObject  yourObject = new YourObject(HttpSession session);  
and get the context  within yourObject  with  
ServletContext  context =  session.getServletContext();
I know this more work as compared to asp.net.  I think what you want to do breaks reuseabliity in both camps. If you create your .net object with HttpContext TempContext = Application.Context.Current;   doesn't that limit the object  use to the web container(or whatever they call it) ?
I hope Tim will explain his comments because I don't understand how a Filter would help you in this case.      rrz

0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16548289
Aside from the cross-application use, this doesn't work internally to a single application.  You still have to "tell" the class what context your currently in.

Here is an example of this in true good usage...

1. I have all my configuration values for the entire application in the web.xml file.
2. I then create a class, let's call it "Configuration".
3. In my configuration class, I have a static property with GET methods for each configuration value in my web.xml file.

What this allows me to do, is call my configuration values very easily from an OOP standpoint.  So for example...

     String DBHostName = Configuration.DbHostName;
     String SmtpHost = Configuration.SmtpHost;

From a programming standpoint, the code becomes cleaner and more eaily maintained.  In .NET I create sub-classes within my Configuration class for even more granularity as indicated below...

     String DBHostName = Configuration.DatabaseSettings.DBHostName;
     String SmtpHost = Configuration.Email.SmtpHost;

From this conversation, I am gathering that I would have to do something like this in Java to achieve the same results.

     String DBHostName = new Configuration(pageContext).DatabaseSettings.DBHostName;

This works fine for a page calling a configration value, but it does not allow me to have one class call the methods of another class and gain access to the context unless I pass the context all the way through.

Assume I have a 3 tier web application (User Interface, Business Logic, and Data Access).  In theory, the DAL should be standalone, and should be able to access application configuration values specific to Data Access.  In .NET, no problem...but what I am hearing here is that I would have to pass an instance of the context throgh the tiers so that the DAL could read config values.  

I can live with that if I have to, but the purpose of this questions was to find out if that is truly the case.
   


0
 
LVL 28

Expert Comment

by:rrz
ID: 16549101
>but what I am hearing here is that I would have to pass an instance of the context throgh the tiers so that the DAL could read config values.  
Yes, if you are going to use the approach that you are carrying over from .NET.  I must tell you that my expertise is confined to JSP. There are others on this forum that are more qualified to explain this subject, but I will try.  As I tried to point out in my first post, the web app container manages a lot of the resources that you trying to configure in your utility classes.  In the page that I have linked above here, you can see that the web app container will look up resources on its own without programming in your utility classes. Specifically you should look at the way DataSources are obtained through the use of JNDI and the container's server.xml file. But I am getting over my head here. Additionally the context params, that "shivaspk" expained, come into play.  I had hoped that that an enterprise expert would step in here and help.    rrz
0
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 1200 total points
ID: 16554645
Sounds like you want to use a statically-accessed ThreadLocal initialized by a servlet Filter. Here's a trio of classes to get you started.

WebContextProvider is the access point for the context in your application. The ThreadLocal holds a different WebContext object for each thread of execution. Think of it as a JVM-managed HashMap with the key being the current thread id. You can get the WebContext object for your thread of execution from anywhere by calling WebContextProvider.get().

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebContextProvider {
    private static ThreadLocal user = new ThreadLocal();

    public static void set(HttpServletRequest request, HttpServletResponse response, ServletContext context) {
        user.set(new WebContext(request, response, context));
    }

    public static WebContext get() {
        return (WebContext) user.get();
    }

    public static void unset() {
        user.set(null);
    }
}

Here's the WebContext object itself. Right now it just holds the current HttpServletRequest, HttpServletResponse, and ServletContext objects. You could always expand on this to suit your needs.

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebContext {
    private HttpServletRequest request;
    private HttpServletResponse response;
    private ServletContext context;

    public WebContext(HttpServletRequest request, HttpServletResponse response, ServletContext context) {
        this.request = request;
        this.response = response;
        this.context = context;
    }

    public HttpSession getSession() {
        return request.getSession();
    }

    public HttpSession getSession(boolean create) {
        return request.getSession(create);
    }

    public ServletContext getServletContext() {
        return context;
    }

    public HttpServletRequest getHttpServletRequest() {
        return request;
    }

    public HttpServletResponse getHttpServletResponse() {
        return response;
    }
}

Finally, here is the servlet Filter that intercepts all incoming requests and initializes the WebContext for the current thread:

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WebContextFilter implements Filter {
    public ServletContext context;

    public void init(FilterConfig filterConfig) throws ServletException {
        context = filterConfig.getServletContext();
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        try {
            WebContextProvider.set((HttpServletRequest) request, (HttpServletResponse) response, context);
            filterChain.doFilter(request, response);
        } finally {
            WebContextProvider.unset();
        }
    }

    public void destroy() {
    }
}

You configure the Filter in your web.xml. With the Filter in place, the WebContextProvider can be used by any class loaded from the same ClassLoader (typically most or all of your application classes) to acquire the thread's WebContext using the static get method.

Perhaps not as simple as what you might have done in .NET. But I imagine that this is basically what the .NET plumbing does under the covers.

Regards,
Jim Cakalic
0
 
LVL 28

Expert Comment

by:rrz
ID: 16555075
jim, thanks for coming to the rescue.  I always learn a lot from your posts.   rrz
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 16555269
everybody knows something. :-)
0
 
LVL 28

Expert Comment

by:rrz
ID: 16555544
No points for me here. The education was much more valuable anyway.   rrz
0
 
LVL 28

Assisted Solution

by:rrz
rrz earned 400 total points
ID: 16558431
Now that jim has given us a lesson, I have been playing around with some ideas.
If you don't need the Session object in your configuration class, then things would get a lot easier.  You could use a Servlet that could be loaded upon startup. You could use something like this in your web.xml.
    <servlet>      
                   <servlet-name>webContext</servlet-name>
                   <servlet-class>test.WebContextServlet</servlet-class>
                   <load-on-startup/>
    </servlet>  

and you could use something like the following code.  
 ---------------------------
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WebContextServlet extends HttpServlet {
    public void init(ServletConfig config){
                   try{
                       super.init(config);
                       WebContextHolder.set(config.getServletContext());
                       System.out.println("init of WebContextServlet");
                      }catch(ServletException se){System.out.println("error in WebContextSrevlet init");}
    }
}
-------------------------------------
package test;
import javax.servlet.ServletContext;
public class WebContextHolder{
   private static ServletContext currentContext;
   public static void set(ServletContext context) {
                                                   currentContext = context;
   }
   public static ServletContext getContext(){
                                             return currentContext;
   }
}
-------------------------------------------
package test;
import javax.servlet.ServletContext;
public class Configuration{
   public ServletContext context;
   public Configuration(){
                   context = WebContextHolder.getContext();
   }
}
---------------------

What do you think everybody ?    rrz




0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 16562754
rrz,

I suppose that would be fine if all that mmarksbury is interested in is the ServletContext. I was basing my proposed implementation on the what I was reading about HttpContext on the MSDN site since that seems to be what we're trying to emulate.
    http://msdn2.microsoft.com/en-us/library/system.web.httpcontext_members.aspx

Some of the HttpContext members might not make sense in a servlet environment or maybe I just don't know enough about ASP.NET to know how to emulate them. But Session, Request, and Response were all object members of HttpContext so my proposal included them.

Regards,
Jim
0
 
LVL 7

Author Comment

by:mmarksbury
ID: 16562934
Thanks everyone....working on a few of these now.  I appreciate the help and great discussion
0
 
LVL 28

Expert Comment

by:rrz
ID: 16563269
Thanks for the points and for starting such an interesting discussion. Please post back later and tell us your final thoughts.    

jim, thanks for the feedback.  I agree that your solution is more robust and complete. I also agree that your solution matches the functionality of the ASP.NET counterpart.  I just thought that a more lightweight solution might be useful as well.  Frankly I can't see the usefullness of having the request and the response in the WebContext object.  I will keep working and see if I can incorporate these ideas into my web apps.  
rrz
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Dropbox has a relatively new feature called Smart Sync.  This feature allows Dropbox Professional (not plus) and Dropbox Business (if enabled) users to store information in Dropbox WITHOUT storing any files on their computer.
A quick solution showing how to control and open a POS Cash Register Drawer using VBA with MS Access.
Loops Section Overview
Enter Foreign and Special Characters Enter characters you can't find on a keyboard using its ASCII code ... and learn how to make a handy reference for yourself using Excel ~ Use these codes in any Windows application! ... whether it is a Micr…

564 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