wood burning stoves*
The moose likes Servlets and the fly likes context parameter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Servlets
Bookmark "context parameter" Watch "context parameter" New topic
Author

context parameter

meera rao
Ranch Hand

Joined: Jun 30, 2005
Posts: 67
I am developing a web based application using struts. I am new to the J2EE concepts, so I am not sure how to approach this problem.

I have a sql table with some codes that I need to load when the application starts , so that i don't have to call the stored procedure everytime.

I ws wondering , if i could write a java class that loads on application startup etc. but i have no clue how to approach it.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

I would read up on ServletContextListener
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContextListener.html


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
meera rao
Ranch Hand

Joined: Jun 30, 2005
Posts: 67
I wrote something like this, can you please tell me if this is a correct way


public class ApplStartServlet extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {

Connection conn= null;
try{

conn= ETAConnectionPool.getInstance().getConnection();
OracleCallableStatement cs=null;
ResultSet rs=null;
cs = (OracleCallableStatement) conn.prepareCall("{call GETCODES(?)}");
cs.registerOutParameter (1, OracleTypes.CURSOR);
cs.executeQuery();
rs = cs.getCursor(1);
Map codesData = new HashMap();
while (rs.next())
{
String codeValue=rs.getString("VALUE");
String codeMeaning=rs.getString("MEANING");
codesData.put(codeValue,codeMeaning);
}
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

The doGet method responds to an HTTP GET request.
If you want the code to be executed when the app loads, you will need to put the code in the contextInitialized method of a ServletContextListener.

Another way of doing this (pre Servlet 2.3 spec) is to put the code in the init method of a servlet and have the servlet load when the app starts with the load-on-startup attribute of the servlet entry in your deployment descriptor (web.xml).
meera rao
Ranch Hand

Joined: Jun 30, 2005
Posts: 67
I put the code in Init in a servlet, I put the following in web.xml file

<servlet>
<servlet-name>ApplStartup</servlet-name>
<servlet-class>
com.odps.eta.servlets.ApplStartServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
I started Tomcat , but i don't see the msg that gets printed in init() method. Is this the correct way.

public class ApplStartServlet {

Map codesData = new HashMap();
public void init(ServletConfig config) throws ServletException {
try{
getCodes();
System.out.println("in Init");
}catch (Exception e) {
}
}

public void getCodes()throws Exception
{
Connection conn= null;
try{
conn= ETAConnectionPool.getInstance().getConnection();
OracleCallableStatement cs=null;
ResultSet rs=null;
cs = (OracleCallableStatement) conn
.prepareCall("{call CODES(?)}");
cs.registerOutParameter (1, OracleTypes.CURSOR);
cs.executeQuery();
rs = cs.getCursor(1);
codesData = new HashMap();
while (rs.next())
{
String codeValue=rs.getString("VALUE");
String codeMeaning=rs.getString("MEANING");
codesData.put(codeValue,codeMeaning);
}

} catch (Exception e) {
throw new Exception(e.toString());
}
finally{
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

public String getMeaning(String value)
{
String meaning=(String)codesData.get(value);
System.out.println("Meaning "+meaning);
return meaning;
}
}
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

A few things:

First, anytime you override init(ServletConfig config) you need to call
super.init(config) from within that method. Weird things happen otherwise.

Second, a Javaranch tip: Whenever posting more than a line or two of your code, wrapp the code in UBB Code tags. These help to make your code more legible by preserving your indenting. The result is almost always, more people reading your code and thus, more people willing to help you out.

Third, I believe that tomcat sends stdout lines to a different log file when called from the init method. Check all of your logs to see if your message got printed.

At a quick glance, your code looks OK. Is it working (other than the print statment not showing up)?

Also is this data only to be used by this one servlet or will other servlets need access to it?
meera rao
Ranch Hand

Joined: Jun 30, 2005
Posts: 67
Thanks for all your help. I used the ServletContextListener and I see the messages get printed when Tomcat starts.

I need to access the HashMap from other classes.
I am using something like this, but i am getting null value.
How can I solve this problem?

ApplStartServlet applServlet= new ApplStartServlet();
String abc=applServlet.getMeaning("SMO");
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Don't use "new" to create a new servlet. Just put the init code into your context listener.
Then, to make the data available to the other components, bind the map to context scope.
Makarand Parab
Ranch Hand

Joined: Dec 10, 2004
Posts: 121
Hi Meera
That won't work. Do one thing either paste the code of the class which implements the contextlistener or you can mail me your code at makarandparab@indiatimes.com. I will make the changes and send back to you. Idea is in the listener class, once the collection object is ready, place it in the context object, context object is a application level object and can be used in all other classes.

Let me know if u have any concerns

Regards
Makarand Parab
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Originally posted by Makarand Parab:
Hi Meera
That won't work. Do one thing either paste the code of the class which implements the contextlistener or you can mail me your code at makarandparab@indiatimes.com. I will make the changes and send back to you. Idea is in the listener class, once the collection object is ready, place it in the context object, context object is a application level object and can be used in all other classes.

Let me know if u have any concerns

Regards
Makarand Parab


Taking a thread off line (except for personal discussions) degrades the value of the forum. Someone else searching for help with a similar problem may find this thread and benefit from it. If the solution is only posted in a private message or email, then that person will not benefit.
Please see: http://faq.javaranch.com/view?UseTheForumNotEmail and don't offer pull the thread off line.
Makarand Parab
Ranch Hand

Joined: Dec 10, 2004
Posts: 121
Hi Meera

Write a class like this
public class listener implements ServletContextListener
{
private HashMap data;

public void contextDestroyed(ServletContextEvent sce)
{
data = null; //releasing hashmap
}

public void contextInitialized(ServletContextEvent sce)
{
1. connect to db
2. populate ur hashmap *data*
3. see the steps from here
ServletContext scontext = sce.getServletContext();
scontext.setAttribute("DataList", data);
}
}

In any other class in the same web application u can access the hashmap
Lets take eg as servlet
public class InitServlet extends HttpServlet(req, res)
{
HashMap data = (HashMap)(req.getSession().getServletContext
().getAttribute("DataList"));
}
}

Then print the hashmap.

Let me know if it is working fine. It should work fine.

Regards
Makarand Parab
Makarand Parab
Ranch Hand

Joined: Dec 10, 2004
Posts: 121
Ben Souther
Ben Sorry please don't take the thread out of the forum. I am sorry for providing my mailing address this won't be repeated.

Regards
Makarand Parab
meera rao
Ranch Hand

Joined: Jun 30, 2005
Posts: 67
Thanks a lot both of you , for helping me out. It is working.

Thanks again
Rajesh Agarwal
Ranch Hand

Joined: Aug 01, 2005
Posts: 79
Meera,

In one of your above message where you have pastewd the xml file contents too, the class that you have pasted is not a servlet. It does not extend any form of a servlet. That is why when you registerd it for on load, it did not load.
 
GeeCON Prague 2014
 
subject: context parameter