[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How a getServlet context should be called ?

Posted on 2005-05-16
15
Medium Priority
?
3,267 Views
Last Modified: 2008-03-17
How a getServlet context should be called ?

example :
======

public class SimpleServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// should i call it here ? like this

ServletContext context = getServletContext();  // is it correct ?

}

}


is the above correct ?

But i saw some other place like getServletContext()  is called in a different way like below,

ServletContext context = servlet.getServletContext(); //  what is "servlet"  here ? It was not present in my  earlier code. It seems there  are many ways to invoke this function.

how many ways i can invoke this function ?



0
Comment
Question by:cofactor
  • 8
  • 7
15 Comments
 
LVL 29

Expert Comment

by:bloodredsun
ID: 14008901
>>ServletContext context = getServletContext();  // is it correct ?
Yes

also,
ServletContext context = this.getServletContext();  // refers directly to the current servlet

Have a look here for examples of what you can call http://www.unix.org.ua/orelly/java-ent/servlet/ch04_02.htm

>>ServletContext context = servlet.getServletContext();

Servlet must be a reference to the servlet itself e.g. "this", it's an odd piece of code
0
 

Author Comment

by:cofactor
ID: 14008949
>>ServletContext context = getServletContext();  // is it correct ?
>Yes

>also,
>ServletContext context = this.getServletContext();  // refers directly to the current >servlet

VERY GLAD


>>ServletContext context = servlet.getServletContext();
>Servlet must be a reference to the servlet itself e.g. "this", it's an odd piece of code.

hmm,

Its a Struts code.

some more snippet >>
=================


ServletContext context = servlet.getServletContext();
DataSource dataSource = (DataSource)context.getAttribute(Action.DATA_SOURCE_KEY);
// blah
//blah


yea, i see also  "http://struts.apache.org/api/org/apache/struts/action/Action.html" in the field summary.

docs  are saying "protected  ActionServlet |servlet|The servlet to which we are attached."

plz answer my following questions >

1)  I am not comfortable to use this syntax here . can i write simply using "this" instead of servlet (as you posted) or in a simple way i have shown. will that be applicable in Struts ?

YES/NO ? or do i have write "servlet" whenever i call getservletContext() in Struts ?


2) note  "Action.DATA_SOURCE_KEY".  i dont see the   DATA_SOURCE_KEY as a static field in the Action class !!  how do they write it ? its illegal !    


0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 14009015
>>1)  I am not comfortable to use this syntax here . can i write simply using "this" instead of servlet (as you posted) or in a simple way i have shown. will that be applicable in Struts ?

No, see below for how to do it.

>>YES/NO ? or do i have write "servlet" whenever i call getservletContext() in Struts ?
>>ServletContext context = servlet.getServletContext();
>>Its a Struts code.

That makes a difference.

here's how in struts...

ServletContext sc = getServlet().getServletConfig().getServletContext();
or
ServletContext sc = getServlet().getServletContext(); //better method as it's more obvious

>>2) note  "Action.DATA_SOURCE_KEY".  i dont see the   DATA_SOURCE_KEY as a static field in the Action class !!  how do they write it ? its illegal !  

I'm not sure about how comprehensive the JavaDocs are, but the String constant is "Action.DATA_SOURCE" so it's wrong anyway.
I'm pretty sure that it's valid in the earlier versions of struts (http://www.jsn-server3.com/struts-documentation/api/constant-values.html) but I'm not sure whether it's still there.

Where did you ge this code? It doesn't seem to be very good...



0
Technology Partners: 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!

 

Author Comment

by:cofactor
ID: 14009055

>ServletContext sc = getServlet().getServletConfig().getServletContext();
or
>ServletContext sc = getServlet().getServletContext(); //better method as it's more >obvious

i guess its linking with the "web.xml"  where servlet has been defined . right ?
and i can call this servlet from any bean also. is not it ?



and in the earlier case , i was inside the HttpServlet and i was calling from thereon ...here is a big difference i see.

OK so far so good.



>>>>Where did you ge this code? It doesn't seem to be very good...

Its from one of the best book of struts.

"Mastering Jakarta Struts " by James Goodwill  and in the chapter  JDBC connection pool

0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 14009115
>>i guess its linking with the "web.xml"  where servlet has been defined . right ?

Nope. It's using a method of ActionServlet (getServlet()) and then a method it inheirits from GenericServlet (getServletContext()) so it's nothing to do with the web.xml :-)

From here you can get web.xml parameters and the like but that's it.

>>and i can call this servlet from any bean also. is not it ?
No, as ActionForm does not extend ActionServlet or HttpServlet interfaces.

>>"Mastering Jakarta Struts "

It's a good book but I'd check the errata if I were you as these books were rushed out (2002) when struts was a bit younger. I'm pretty sure that the code you've shown me won't compile but I may be wrong. If you use a good IDE with contextual help, you should be able to find out what you can and can't call.


I'm curious so would you mind posting the source code for that Action.
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 14009182
           ServletContext context = getServlet().getServletContext() ;
            DataSource dataSource = (DataSource)context.getAttribute(Action.DATA_SOURCE_KEY);

The above line compiles with the notice that "Action.DATA_SOURCE_KEY" is depreciated (so it should no longer be used). This means that you should define your datasources in either struts-config.xml or server.xml so that you can use a Database Connection Pool (DBCP)
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 14009208
If your data-source is set up in the struts-config.xml you can then call this from execute( <args>) to get a connection

DataSource dataSource = getDataSource(pRequest);
Connection myConnection = dataSource.getConnection();

see here: http://struts.apache.org/faqs/database.html
0
 

Author Comment

by:cofactor
ID: 14009256
hi, i will respond after some time. i will post the source  code as u mentioned . i have to go some where .  plz bear with me.  thanks
0
 

Author Comment

by:cofactor
ID: 14009476
You know, you have given some information which i was about to ask shortly. those were my questions too.



Ok, let me put my confusions in step by step.



your comment :

>Nope. It's using a method of ActionServlet (getServlet()) and then a method it inheirits from >GenericServlet (getServletContext()) so it's nothing to do with the web.xml :-)


      But look , when  we use this inside a ACtion class we  DONT extend ActionServlet so how do you get the method "getServlet()" which belongs to ActionServlet class !!



i mean like below >
====================


public class LookupAction extends Action
{
// blah
// blah

public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {




// DO U WANT ME TO WRITE HERE LIKE BELOW ?


ServletContext sc = getServlet().getServletConfig().getServletContext();// i protest bcoz i have  not extended ActionServlet class so  getServlet() method is not available to me right here. i can not do it .


}








your comment:


>>and i can call this servlet from any bean also. is not it ?
>>No, as ActionForm does not extend ActionServlet or HttpServlet interfaces.

      yea, i agree. so it support my above justification . i.e i can not use getServlet()  in Action class too !









your comment:

>I'm curious so would you mind posting the source code for that Action.


      if you want i can send, but probabily u have pointed out in ur next post that it is  deprecated. well, i just read it from the book only . thanks,for the information , might be my pdf book of "Mastering Jakarta Struts " is old. i have to check it out.











your comment:

>If your data-source is set up in the struts-config.xml you can then call this from execute( ><args>) to get a connection



      thats a dream question to me! its a long cherished question to me. because i have noticed this Data Source both in Struts-Config.xml  and server.xml but did not know which one is better or whats the difference !

does it mean if i have many application which uses same database simultaneously  then i should declare in server.xml ?

and if i have  want the DB to work only for particular application then i should use that in Struts-config ?






      sorry, i have asked many questions. i have become greedy. i dont want to miss the opportunity to get answers from you bcoz these are very long and painful questions to me.

thanks.

0
 

Author Comment

by:cofactor
ID: 14010083
plz   tell me the answer. i am increasing the points
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 14010345
>>>Nope. It's using a method of ActionServlet (getServlet()) and then a method it inheirits from >GenericServlet (getServletContext()) so it's nothing to do with the web.xml :-)

>>But look , when  we use this inside a ACtion class we  DONT extend ActionServlet so how do you get the method "getServlet()" which belongs to ActionServlet class !!

You're right. I mis-typed. The method getServlet() is a method of the Action class, and returns the instance of the ActionServlet which you can then call getServletContext() on. So it is a method of the Action class not ActionServlet but it returns the ActionServlet which extends HttpServlet.

This means you can call this:
//imports and package
public class TestAction extends Action      {
      
      public ActionForward execute(
                  final ActionMapping pMapping,
                  final ActionForm pForm,
                  final HttpServletRequest pRequest,
                  final HttpServletResponse pResponse)
      throws Exception {
            
            ServletContext context = getServlet().getServletContext() ;
            DataSource dataSource = getDataSource(pRequest);
            
            return ( pMapping.findForward("success"));         
      } // execute      
}

>>  if you want i can send, but probabily u have pointed out in ur next post that it is  deprecated
Yes, don't bother sending as it's only going to be old code


>>does it mean if i have many application which uses same database simultaneously  then i should declare in server.xml ?
>>and if i have  want the DB to work only for particular application then i should use that in Struts-config ?

You should use DataSource in server.xml as this feature will be removed from Struts in version 2. But if you want to use it for a single struts app and want the portablility then you can use it. See here from the docs:

" Ideally, the business logic layer should encapsulate the data access details, including acquiring a database connection. However, some older application designs expect that the caller be able to provide a database connection or DataSource instance. When you need to access a legacy design, the Struts DataSource manager can make it easy for your Action class to produce these resources on demand.

NOTE: It is preferred that data connectivity be handled directly by the business classes, usually via JNDI. The Struts DataSource manager should only be used with legacy business classes that don't provide their own connectivity. When possible, we strongly recommend use of the standard DAO pattern, so that the Action classes do not need to know anything about the persitence mechanism. The DataSource manager is being retained in Struts 1.x for backward compatibility but may not be retained in Struts 2.x or later. "

I hope I've answered all your questions but if you have anymore, feel free to ask...
0
 

Author Comment

by:cofactor
ID: 14016270
Hi, yes it was a very  nice answe. you have answered everything . i would like to ask 2 more questions. and thats final.

 2 questions are

1)

Your commment
===========
>>and i can call this servlet from any bean also. is not it ?
>>No, as ActionForm does not extend ActionServlet or HttpServlet interfaces.

Ok, then how do i call from a bean ? whats the way ? suppose you are developing a Struts application and somewhere in one of the bean you  need to call  servlet , ServletContext and access its configuration , web.xml's  initialized  parameters blah blah  , then how do u call ?


Do u want to tell  the bean must extend  Action class  so that i could avail  the getServlet() method and do like before ?

 but its really bad,  well  technically it would be OK, but it would be bad to  see to extend the WHOLE ACTION class . :(      . i dont know know , but may be  you know whats the proper way to call the  servlet inside a bean .

so, will you  plz tell me How do i call the servlet  from  a  bean  if i am developing a Struts applicaton ?



your comment
==========
>I'm pretty sure that the code you've shown me won't compile but I may be wrong. If >you use a good IDE with contextual help, you should be able to find out what you can >and can't call.

wow,  whats that IDE ? eclipse ?  i have not usued eclipse yet . if the IDE gives Struts functionality( autocompletion) it would be ammusing, very nice . do u use such any ?
i use Jcreator pro which does autocompletion for Java but not for Struts.



0
 
LVL 29

Accepted Solution

by:
bloodredsun earned 200 total points
ID: 14016736
>>Ok, then how do i call from a bean

You wouldn't in the bean. What you would do it call the parameters from the Action and then pass the parameters into the bean in the Action's execute method.

e.g. extending our example
//imports and package
public class TestAction extends Action     {
     
     public ActionForward execute(
               final ActionMapping pMapping,
               final ActionForm pForm,
               final HttpServletRequest pRequest,
               final HttpServletResponse pResponse)
     throws Exception {
         
          ServletContext context = getServlet().getServletContext() ;
          String initParam = context.getInitParameter("paramOne") ;//get init param
          ((MyActionForm)pForm).setParamOne( initParam );//pass into actionForm
         
          return ( pMapping.findForward("success"));        
     } // execute    
}

>> whats that IDE ? eclipse ?

Actually WebSphere Application Developer (WSAD) which is the IBM version of Eclipse. You really should be using Eclipse as there are many plugins such as "StrutsBox" that allow you to add the struts support into Eclipse.It's also the best IDE, the most commonly used in Development jobs and it's also free : http://www.eclipse.org/.
0
 

Author Comment

by:cofactor
ID: 14016774
ahh! , it was a  very nice discussion with  you.  I  have understood it. you are invincible. i see  you are approching towards level "WIZARD".
best of luck.
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 14016834
Well thanks for thinking that I'm "invincible" (great word by the way!! ) I'm just some dude who's coded JSP since 1999 :-P

Thanks also for the wishes on the JSP cert, I got my Java "Guru" cert yesterday so I'm quite happy.

Don't forget that it's guys and girls like you who ask the interesting questions that make this site what it is. I learn a lot from answering questions as it makes me think about things in a different way and then having to explain it to someone else.

So thanks for the discussion too. Where are you from by the way? I'm always curious to know where other people are when they're on EE...
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

In the below post we have mentioned the best hosting type for startups. Also, check out some of the superlative web hosting companies that are proposing affordable web hosting solutions to host your startup website.
Tech giants such as Amazon and Google have sold Alexa and Echo to such an extent that they have become household names. And soon they are expected to be used by commoners in their homes, ordering takeout, picking out a song, answering trivia questio…
Screencast - Getting to Know the Pipeline
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…

834 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