在Struts Action对象中得到类似jsp页面application的ServletContext

今天需要把数据存在网站程序全局范围,需要在struts Aciton对象中得到 ServletContext对象,与jsp页面的application一样。在google中搜索到如下帖子。转帖于此:

How to get 'application' in Struts Action class? (转自:http://forum.java.sun.com/thread.jspa?threadID=609998&messageID=3346689

×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

How to get 'application' in Struts Action class?  

Mar 23, 2005 7:45 PM

Click to email this message

 

Hello,

I have a question on how to get 'application' in Struts Action class.

In the jsp file, i have set an application attribute:

<%

applicaiton.setAttribute("userId", "testUser");

%>

But how to get this application attribute in Struts Action class?

So far I only know how to get session in Struts Action class by using:

(HttpServletRequest)request.getSession();

 

[Dukes Earned 1425] evnafets

Posts:7,577

Registered: 29/04/03

Re: How to get 'application' in Struts Action class?  

Mar 23, 2005 8:08 PM (reply 1 of 2)

Click to email this message

 

The "application" in a JSP page is the ServletContext object.

In a standard servlet you can use

ServletContext application = getServletConfig().getServletContext();

In a Struts Action class, just have to get hold of the servlet first

ServletContext application = getServlet().getServletConfig().getServletContext();

Cheers,

evnafets

 

[Dukes Earned 0] nonameisname

Posts:24

Registered: 8/13/03

Re: How to get 'application' in Struts Action class?  

Mar 23, 2005 8:33 PM (reply 2 of 2)

Click to email this message

 

Hi evnafets,

Thanks a lot for your help. It works.

By the way, i found that it is possible to get ServletContext in Struts in two ways:

ServletContext application = getServlet().getServletConfig().getServletContext();

or

ServletContext application = getServlet().getServletContext();

Both work fine. Any concern about the 2nd way? It does not getServletConfig() but instead it straight away getServletContext().

*********************************************************************************************************

                       转帖完毕

2 thoughts on “在Struts Action对象中得到类似jsp页面application的ServletContext”

  1. 在Struts Action对象中得到类似jsp页面application的ServletContext�还可以这样:


    HttpSession mySession = request.getSession();

    ServletContext application = mySession.getServletContext();

    因为getServlet()是所有Struts的Action类的基类org.apache.struts.action.Action中的方法,所以,必须有Action类的对象实例才能用这个方法。

    而用从javax.servlet.http.HttpServletRequest得到javax.servlet.http.HttpSession,再从session中得到ServletContext的办法只要传入方法中一个javax.servlet.http.HttpServletRequest对象就可以了。

Comments are closed.