在web api actionn中怎样获取web

用户名:leizhimin
文章数:1050
评论数:4181
注册日期:
阅读量:1297
阅读量:3317
阅读量:585003
阅读量:470545
51CTO推荐博文
JavaWeb应用中获取Spring的ApplicationContext
ApplicationContext是Spring的容器环境,通过ApplicationContext对象可以访问所有配置的bean。
在Web开发开发中,常常需要从JSP或者Servlet或者Action中获取ApplicationContext对象,这时候,就无法使用new关键字通过查找配置文件来实例化ApplicationContext这个对象了。Spring通过WebApplicationContextUtils可以方便实现您的需求。下面看个例子:
一、Spring2.5+Struts2环境下
1、配置web.xml,通过这个配置来获取的。
&?xml version="1.0" encoding="UTF-8"?& &web-app xmlns="/xml/ns/javaee" &&&&&&&&&&&&&&&&&&&& xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" &&&&&&&&&&&&&&&&&&&& xsi:schemaLocation="/xml/ns/javaee &&&&&&&&[url]/xml/ns/javaee/web-app_2_5.xsd[/url]" &&&&&&&&&&&&&&&&&&&& version="2.5"& &&&&&&&&&context-param& &&&&&&&&&&&&&&&&&param-name&contextConfigLocation&/param-name& &&&&&&&&&&&&&&&&&param-value&/WEB-INF/applicationContext.xml&/param-value& &&&&&&&&&/context-param& &&&&&&&&&filter& &&&&&&&&&&&&&&&&&filter-name&struts2&/filter-name& &&&&&&&&&&&&&&&&&filter-class&org.apache.struts2.dispatcher.FilterDispatcher&/filter-class& &&&&&&&&&/filter& &&&&&&&&&filter-mapping& &&&&&&&&&&&&&&&&&filter-name&struts2&/filter-name& &&&&&&&&&&&&&&&&&url-pattern&/*&/url-pattern& &&&&&&&&&/filter-mapping& &&&&&&&&&listener& &&&&&&&&&&&&&&&&&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class& &&&&&&&&&/listener& &&&&&&&&&servlet& &&&&&&&&&&&&&&&&&servlet-name&dispatcher&/servlet-name& &&&&&&&&&&&&&&&&&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class& &&&&&&&&&&&&&&&&&load-on-startup&1&/load-on-startup& &&&&&&&&&/servlet& &&&&&&&&&servlet-mapping& &&&&&&&&&&&&&&&&&servlet-name&dispatcher&/servlet-name& &&&&&&&&&&&&&&&&&url-pattern&*.form&/url-pattern& &&&&&&&&&/servlet-mapping& &/web-app&
2、在JSP、Servlet、Action中获取ApplicationContext
&%@ page import="lavasoft.service.TestService" %& &%@ page import="org.springframework.context.ApplicationContext" %& &%@ page import="org.springframework.web.context.support.WebApplicationContextUtils" %& &%@ page contentType="text/charset=UTF-8" language="java" %& &html& &head&&title&Simple jsp page&/title&&/head& &body& &% //&&&&&&&&ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); &&&&&&&&ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext()); &&&&&&&&TestService service = (TestService) ctx.getBean("testService"); &&&&&&&&String s = service.test(); &&&&&&&&out.print(s); %& &/body& &/html&
二、Spring+JSP的环境
在此环境下web.xml配置会有些变化:
&?xml version="1.0" encoding="UTF-8"?& &web-app xmlns="/xml/ns/javaee" &&&&&&&&&&&&&&&&&&&& xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" &&&&&&&&&&&&&&&&&&&& xsi:schemaLocation="/xml/ns/javaee &&&&&&&&[url]/xml/ns/javaee/web-app_2_5.xsd[/url]" &&&&&&&&&&&&&&&&&&&& version="2.5"& &&&&&&&&&context-param& &&&&&&&&&&&&&&&&&param-name&contextConfigLocation&/param-name& &&&&&&&&&&&&&&&&&param-value&/WEB-INF/applicationContext.xml&/param-value& &&&&&&&&&/context-param& &&&&&&&&&listener& &&&&&&&&&&&&&&&&&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class& &&&&&&&&&/listener& &&&&&&&&&servlet& &&&&&&&&&&&&&&&&&servlet-name&dispatcher&/servlet-name& &&&&&&&&&&&&&&&&&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class& &&&&&&&&&&&&&&&&&load-on-startup&1&/load-on-startup& &&&&&&&&&/servlet& &&&&&&&&&servlet-mapping& &&&&&&&&&&&&&&&&&servlet-name&dispatcher&/servlet-name& &&&&&&&&&&&&&&&&&url-pattern&*.form&/url-pattern& &&&&&&&&&/servlet-mapping& &/web-app&
获取的方式和上述完全一样。
下面给出本例子的工程源码,参看附件。本文出自 “” 博客,请务必保留此出处
了这篇文章
附件下载:    
类别:┆阅读(0)┆评论(0)
本文收录至博客专题:《》
11:53:47 11:53:56 11:54:40 16:20:48 11:59:34 09:18:39
请输入验证码:博客分类:
虽然Struts2的Action只是一个非常普通的Java对象,并不具备任何Web容器的特质,但是我们需要把Action放到一个更加大的环境中来看。事实上,Struts2为Action的执行,准备了完整的数据环境和执行环境。而这个执行环境,就保证了Action在Web容器中的顺利运行。 在Struts2中,每个Http的请求,会被发送到一个Filter。而这个Filter,就会针对每个请求,创建出一个代码的执行环境,并在这个基础上,为每个执行环境配备与之对应的数据环境,这个数据环境中的内容,就来自于Web容器中的一个又一个对象。这样,就能够顺利调用Action执行代码而无需担心它是否运行在Web容器中了。 至于这个执行环境和数据环境到底是什么,我们接下来会详细讲到。
刚刚我们提到Struts2会为每个Http的请求建立一个执行环境和数据环境。其中,数据环境就成为了Action获取Web容器的基础。所以,当Action需要获取Web容器的相关对象,需要通过数据环境来进行。 Struts2的Action的这一个重要特性,至少能为我们带来以下好处: 1. 使得Struts2的Action非常易于测试 如果我们完全不考虑Action的执行环境,仅仅把Action看作一个普通的Java对象,那么我们甚至可以直接new一个Action的对象,通过执行其中的方法完成测试。这样,我们就不需要任何的Mock,来模拟Web容器的环境。 2. 结合Action的执行环境,使得Struts2在Control这个层次上,能够定义更加丰富的执行层次 因为Action是一个普通的Java类,而不是一个Servlet类,完全脱离于Web容器,所以我们就能够更加方便地对Control层进行合理的层次设计,从而抽象出许多公共的逻辑,并将这些逻辑脱离出Action对象本身。事实上,Struts2也正是这么做的,无论是Interceptor,还是Result,其实都是抽象出了Action中公共的逻辑部分,将他们放到了Action的外面,从而更加简化了Action的开发。 3. 使得Struts2的Action看上去更像一个POJO,从而更加易于管理 Struts2的Action是一个线程安全的对象。而Web容器传递过来的参数,也会传递到Action中的成员变量中。这样,Action看上去就更像一个POJO,从而能够方便的被许多对象容器进行管理。比如说,你可以非常方便得把Action纳入到Spring的容器中进行管理。
younglibin
浏览: 759559 次
来自: 北京
“子类对象”都拥有了“父类对象的一个实例的引用”我晕,应该是“ ...
关于楼主最后的问题,我想可能是这样:InputFormat默认 ...
上述7点基本具备,可惜现在因为项目需要,做管理方面工作!
链接已经失效
看了以上7条, 自己 也不知道是否能够对上, 感觉没一点都有那 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'web项目中各种路径的获取
1.可以在servlet的init方法里
String path = getServletContext().getRealPath(&/&);
这将获取web项目的全路径
例如 :E:\eclipseM9\workspace\tree\
tree是我web项目的根目录
2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource(&/&).getPath();
这将获取 到classes目录的全路径
例如 : E:\eclipseM9/workspace/tree/WEB-INF/classes/
这个方法也可以不在web环境里确定路径,比较好用
3.request.getContextPath();
获得web根的上下文环境
tree是我的web项目的root context
/* 取得当前目录的路径
path=request.getRealPath(&&);
/*得到jbossWEB发布临时目录 warUrl=.../tmp/deploy/tmp14544test-exp.war/
path=C:\jboss-4.0.5.GA\server\default\tmp\deploy\tmp14544test-exp.war\
String path = (String)request.getContextPath();
/*得到项目(test)应用所在的真实的路径 path=/test&
String path = request.getRequestURI();
/*得到应用所在的真实的路径 path=/test/admin/admindex.jsp
String savePath=request.getRealPath(request.getServletPath());
/*得到当前文件的磁盘绝对路径
//JAVA 取得当前目录的路径
File file=new File(&.&);&
String path=file.getAbsolutePath();
path=file.getPath();
/*得到jboss运行目录 path=C:\jboss-4.0.5.GA\bin\
---------------------------------------------
相对路径/绝对路径总结
1.基本概念的理解
绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如:
C:xyz est.txt 代表了test.txt文件的绝对路径。/index.htm也代表了一个URL绝对路径。
相对路径:相对与某个基准目录的路径。包含Web的相对路径(HTML中的相对目录),例如:在
Servlet中,&/&代表Web应用的跟目录。和物理路径的相对表示。例如:&./& 代表当前目录,&../&代表上级目录。这种类似的表示,也是属于相对路径。
另外关于URI,URL,URN等内容,请参考RFC相关文档标准。
RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,
(https://www.ietf.org/rfc/rfc2396.txt)
2.关于JSP/Servlet中的相对路径和绝对路径。
2.1服务器端的地址
服务器端的相对地址指的是相对于你的web应用的地址,这个地址是在服务器端解析的(不同于html和javascript中的相对地址,他们是由客户端解析的)也就是说这时候在jsp和servlet中的相对地址应该是相对于你的web应用,即相对于http: //192.168.0.1/webapp/的。
其用到的地方有:
forward:servlet中的request.getRequestDispatcher(address);这个address是在服务器端解析的,所以,你要forward到a.jsp应该这么写:request.getRequestDispatcher(&/user/a.jsp&)这个/ 相对于当前的web应用webapp,其绝对地址就是:https://192.168.0.1/webapp/user/a.jsp。 sendRedirect:在jsp中&%response.sendRedirect(&/rtccp/user/a.jsp&);%&
2.22、客户端的地址
所有的html页面中的相对地址都是相对于服务器根目录(https://192.168.0.1/)的,而不是(跟目录下的该Web应用的目录) https://192.168.0.1/webapp/的。 Html中的form表单的action属性的地址应该是相对于服务器根目录(https://192.168.0.1/)的,所以,如果提交到a.jsp 为:action=&/webapp/user/a.jsp&或action=&&%=request.getContextPath()% &&/user/a.jsp;
提交到servlet为actiom=&/webapp/handleservlet& Javascript也是在客户端解析的,所以其相对路径和form表单一样。
因此,一般情况下,在JSP/HTML页面等引用的,Javascript.Action等属性前面最好都加上
&%=request.getContextPath()%&,以确保所引用的文件都属于Web应用中的目录。另外,应该尽量避免使用类似&.&,&./&,&../../&等类似的相对该文件位置的相对路径,这样当文件移动时,很容易出问题。
3. JSP/Servlet中获得当前应用的相对路径和绝对路径
3.1 JSP中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getRequestURI()
文件的绝对路径  :application.getRealPath(request.getRequestURI());
当前web应用的绝对路径 :application.getRealPath(&/&);
取得请求文件的上层目录:new File(application.getRealPath(request.getRequestURI())).getParent()
3.2 Servlet中获得当前应用的相对路径和绝对路径
根目录所对应的绝对路径:request.getServletPath();
文件的绝对路径 :request.getSession().getServletContext().getRealPath
(request.getRequestURI())
当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath(&/&);
(ServletContext对象获得几种方式:
javax.servlet.http.HttpSession.getServletContext()
javax.servlet.jsp.PageContext.getServletContext()
javax.servlet.ServletConfig.getServletContext()
4.java 的Class中获得相对路径,绝对路径的方法
4.1单独的Java类中获得绝对路径
根据java.io.File的Doc文挡,可知:
默认情况下new File(&/&)代表的目录为:System.getProperty(&user.dir&)。
一下程序获得执行类的当前路径
package org.cheng.&
import java.io.F&
public class FileTest ...{&
public static void main(String[] args) throws Exception ...{&
System.out.println(Thread.currentThread().getContextClassLoader().getResource(&&));&
System.out.println(FileTest.class.getClassLoader().getResource(&&));&
System.out.println(ClassLoader.getSystemResource(&&));&
System.out.println(FileTest.class.getResource(&&));&
System.out.println(FileTest.class.getResource(&/&));&
//Class文件所在路径&
System.out.println(new File(&/&).getAbsolutePath());&
System.out.println(System.getProperty(&user.dir&));&
4.2服务器中的Java类获得当前路径
(1).Weblogic
WebApplication的文件根目录是你的weblogic安装所在根目录。
例如:如果你的weblogic安装在c:beaweblogic700.....
那么,你的文件根路径就是c:.
所以,有两种方式能够让你访问你的服务器端的文件:
a.使用绝对路径:
比如将你的参数文件放在c:yourconfigyourconf.properties,
直接使用 new FileInputStream(&yourconfig/yourconf.properties&);
b.使用相对路径:
相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放
在yourwebappyourconfigyourconf.properties,
这样使用:
new FileInputStream(&./yourconfig/yourconf.properties&);
这两种方式均可,自己选择。
(2).Tomcat
在类中输出System.getProperty(&user.dir&);显示的是%Tomcat_Home%/bin
不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET
的路径为根.比如用新建文件法测试File f = new File(&a.htm&);
这个a.htm在resin的安装目录下
(4).如何读相对路径哪?
在Java文件中getResource或getResourceAsStream均可
例:getClass().getResourceAsStream(filePath);//filePath可以是&/filename&,这里的/代表web
发布根路径下WEB-INF/classes
默认使用该方法的路径是:WEB-INF/classes。已经在Tomcat中测试。
通过上面内容的使用,可以解决在Web应用服务器端,移动文件,查找文件,复制
删除文件等操作,同时对服务器的相对地址,绝对地址概念更加清晰。
建议参考URI,的RFC标准文挡。同时对Java.io.File. Java.net.URI.等内容了解透彻
对其他方面的理解可以更加深入和透彻。
这是在Java中去当前项目的根目录的方法
java 代码/** *//**&
* TODO 取得当前项目的根目录&
* @author PHeH
public class Application ...{&
/** *//**&
* TODO 获取根目录&
* @return&
* @author PHeH
public static String getRootPath()...{&
//因为类名为&Application&,因此& Application.class&一定能找到&
String result = Application.class.getResource(&Application.class&).toString();&
int index = result.indexOf(&WEB-INF&);&
if(index == -1)...{&
index = result.indexOf(&bin&);&
result = result.substring(0,index);&
if(result.startsWith(&jar&))...{&
// 当class文件在jar文件中时,返回&jar:file:/F:/ ...&样的路径&
result = result.substring(10);&
}else if(result.startsWith(&file&))...{&
// 当class文件在class文件中时,返回&file:/F:/ ...&样的路径&
result = result.substring(6);&
if(result.endsWith(&/&))result = result.substring(0,result.length()-1);//不包含最后的&/&&posts - 5,&
comments - 6,&
trackbacks - 1
为了在web容器启动时运行指定的类,我们可以在web.xml中配置一个自定义的servlet,复写init方法即可,如下:web.xml
&servlet&&servlet-name&tychoLoader&/servlet-name&&servlet-class&org.junesky.tycho.servlet.TychoLoaderServlet&/servlet-class&&&&load-on-startup&3&/load-on-startup&&/servlet&
TychoLoaderServlet.java
public class TychoLoaderServlet extends HttpServlet {public void init(ServletConfig config) throws ServletException {//在这里做相应的处理}public void destroy() {}}
在启动时,若要为其配置相应的参数又该如何处理呢?以下介绍几种常用的方法。1、在servlet中获取参数:web.xml
&servlet&&servlet-name&tychoLoader&/servlet-name&&servlet-class&org.junesky.tycho.servlet.TychoLoaderServlet&/servlet-class&&init-param&&param-name&filename&/param-name&&param-value&config/constants.properties&/param-value&&/init-param&&&&load-on-startup&3&/load-on-startup&&/servlet&
TychoLoaderServlet.java
public class TychoLoaderServlet extends HttpServlet {public void init(ServletConfig config) throws ServletException {super.init(config);// 利用ServletConfig的getInitParameter来获取参数String filename = config.getInitParameter("filename");……}public void destroy() {}}
2、在jsp中获取参数:web.xml
&context-param&&param-name&filename&/param-name&&param-value&config/constants.properties&/param-value&&/context-param&
String filename = new String(application.getInitParameter("filename"));
3、在struts中获取参数:web.xml
&servlet&&servlet-name&action&/servlet-name&&servlet-class&org.junesky.tycho.servlet.EncodeActionServlet&/servlet-class&&init-param&&param-name&config&/param-name&&param-value&/WEB-INF/config/struts-config.xml&/param-value&&/init-param&&init-param&&param-name&debug&/param-name&&param-value&3&/param-value&&/init-param&&init-param&&param-name&detail&/param-name&&param-value&3&/param-value&&/init-param&&load-on-startup&2&/load-on-startup&&/servlet&
ContorlSysInfoAction.java
public class ContorlSysInfoAction extends TychoAction {public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {try {javax.servlet.ServletConfig config = this.getServlet().getServletConfig();System.out.println("******" + config.getInitParameter("config"));} catch (Exception ex) {}return mapping.findForward("success");}}
根据使用的框架不同,取得方法都不仅相同。这里仅仅列出几种较常用的方法供大家参考。
阅读(...) 评论() &Action访问web资源的方式 - CSDN博客
Action访问web资源的方式
1 package com.dx.
3 import java.util.M
5 import com.opensymphony.xwork2.ActionC
7 public class TestActionContextFetchServletObjectAction {
public String execute() {
// 0.通过ActionContext调用其getContext方法,获取到一个ActionContext实例对象。
// ActionContext是Action的上下文对象,可以从中获取当前Action需要的一起信息。
ActionContext context = ActionContext.getContext();
// 1.获取ApplicationContext对应的Map,并向其中添加一个属性。
// 调用ActionContext对象的getApplication方法,获取application对象的Map对象。
Map&String, Object& applicationMap = context.getApplication();
// 设置属性
applicationMap.put(&applicationKey&, &applicationValue&);
// 获取属性
Object appPageKey = applicationMap.get(&applicationClientKey&);
System.out.println(appPageKey);
// 2.session
Map&String, Object& sessionMap = context.getSession();
sessionMap.put(&sessionKey&, &sessionValue&);
Object sessionClientKey = sessionMap.get(&sessionClientKey&);
System.out.println(sessionClientKey);
// 3.request
// ActionContext中並沒有提供getRequets方法來獲取request對應的Map.
// 需要手工调用ActionContext的get方法,并传入一个request字符串来获取request对象的Map对象。
Map&String, Object& requestMap = (Map&String, Object&) context.get(&request&);
//设置属性
requestMap.put(&requestKey&, &requestValue&);
// 获取属性
Object requestClientKey = requestMap.get(&requestClientKey&);
System.out.println(requestClientKey);
// 4.parameters
// 获取请求参数对应的Map,并获取指定的参数值。
// 键:请求参数的名字,值:请求参数的值对应的字符串数组。
// 注意: 1.getParameters返回的值为Map&String,Object&,而不是Map&String,String[]&
2.parameters这个Map是只读的,不能写入数据,如果写入,但不出错误,但也不起作用。
Map&String, Object& parametersMap = context.getParameters();
// 读取属性
Object parametersClientKey = parametersMap.get(&parametersClientKey&);
System.out.println(parametersClientKey);
// 设置值,并不起作用的。
parametersMap.put(&parameterKey&, &parametersValue&);
return &success&;
1 &?xml version=&1.0& encoding=&UTF-8& ?&
2 &!DOCTYPE struts PUBLIC
&-//Apache Software Foundation//DTD Struts Configuration 2.3//EN&
&http://struts.apache.org/dtds/struts-2.3.dtd&&
6 &struts&
&constant name=&struts.action.extension& value=&action& /&
&constant name=&struts.enable.DynamicMethodInvocation& value=&false& /&
&constant name=&struts.devMode& value=&false& /&
&package name=&default& namespace=&/& extends=&struts-default&&
&action name=&testServletObject& class=&com.dx.actions.TestActionContextFetchServletObjectAction&&
&result&/WEB-INF/test-context.jsp&/result&
&/package&
16 &/struts&
1 &%@ page language=&java& contentType=&text/ charset=UTF-8&
pageEncoding=&UTF-8&%&
3 &!DOCTYPE html PUBLIC &-//W3C//DTD HTML 4.01 Transitional//EN& &http://www.w3.org/TR/html4/loose.dtd&&
6 &meta http-equiv=&Content-Type& content=&text/ charset=UTF-8&&
7 &title&Insert title here&/title&
&a href=&testServletObject.action?parameterClientKey=hello&&Test
Fetch Servlet Object From ActionContext object.&/a&
& & & & &% application.setAttribute(&applicationClientKey&, &applicationClientValue&); %&
& & & &&&% session.setAttribute(&sessionClientKey&, &sessionClientValue&); %&
& & & &&&% request.setAttribute(&requestClientKey&, &requestClientValue&); %&
12 &/body&
13 &/html&
1 &%@ page language=&java& contentType=&text/ charset=UTF-8&
pageEncoding=&UTF-8&%&
3 &!DOCTYPE html PUBLIC &-//W3C//DTD HTML 4.01 Transitional//EN& &http://www.w3.org/TR/html4/loose.dtd&&
6 &meta http-equiv=&Content-Type& content=&text/ charset=UTF-8&&
7 &title&Insert title here&/title&
&h4&Test fetch Servlet object from ActionContext object&/h4&
applicationKey:${applicationScope.applicationKey}
sessionKey:${sessionScope.sessionKey}
requestKey:${requestScope.requestKey}
parameterKey:${parameters.parameterKey}
19 &/body&
20 &/html&
struts.xml
1 &?xml version=&1.0& encoding=&UTF-8& ?&
2 &!DOCTYPE struts PUBLIC
&-//Apache Software Foundation//DTD Struts Configuration 2.3//EN&
&http://struts.apache.org/dtds/struts-2.3.dtd&&
6 &struts&
&!-- action路径的扩展名:*.action,*.do,无扩展名 --&
&constant name=&struts.action.extension& value=&action,do,& /&
&constant name=&struts.enable.DynamicMethodInvocation& value=&false& /&
&constant name=&struts.devMode& value=&false& /&
&package name=&default& namespace=&/& extends=&struts-default&&
&action name=&testServletObject&
class=&com.dx.actions.TestActionContextFetchServletObjectAction&&
&result&/WEB-INF/test-context.jsp&/result&
&action name=&gotoLoginPage& class=&com.opensymphony.xwork2.ActionSupport& method=&execute&&
&result name=&success&&/login.jsp&/result&
&action name=&login& class=&com.dx.actions.TestWithXXXAware&
method=&login&&
&result name=&login-success&&/WEB-INF/login-success.jsp&/result&
&action name=&logout& class=&com.dx.actions.TestWithXXXAware&
method=&logout&&
&result name=&logout-success&&/login.jsp&/result&
&/package&
30 &/struts&
TestWithXXXAware.java:
1 package com.dx.
3 import java.util.M
5 import org.apache.struts2.ServletActionC
6 import org.apache.struts2.dispatcher.SessionM
7 import org.apache.struts2.interceptor.ApplicationA
8 import org.apache.struts2.interceptor.ParameterA
9 import org.apache.struts2.interceptor.RequestA
10 import org.apache.struts2.interceptor.SessionA
* XxxAware一般情況下,一個Action類中包含了多個Action方法,同時這個多個Action中都需要使用域對象或parameters.
* ActionContext的方式,一般情況下一個Action類中包含了一個Action方法,
* 或者需要使用SessionMap清楚session的時候會使用。
18 public class TestWithXXXAware implements ApplicationAware, RequestAware, SessionAware, ParameterAware {
public void setUsername(String username) {
this.username =
* login action
public String login() {
// 记录登录成功的用户信息。
// 从request中获取不到form提交的参数信息,为什么呢?
String usernameWithActionContext = (String) request.get(&username&);
String usernameWithServletActionContext=ServletActionContext.getRequest().getParameter(&username&);
session.put(&loginusername&, username);
System.out.println(&with setter:&+username);
System.out.println(&with ActionContext.get(\&request\&).get(\&username\&):&+usernameWithActionContext);
System.out.println(&with ServletActionContext.getRequest().getParameter(\&username\&):&+usernameWithServletActionContext);
// 实现成功登录计数
Integer count = (Integer) application.get(&count&);
if (count == null || count & 0) {
count = 0;
count++;
application.put(&count&, count);
return &login-success&;
* logout action
public String logout() {
// 实现成功登录计数
Integer count = (Integer) application.get(&count&);
if (count == null || count & 0) {
count = 0;
application.put(&count&, count);
// 使得session失效
((SessionMap) session).invalidate();
return &logout-success&;
private Map&String, String[]&
private Map&String, Object&
private Map&String, Object&
private Map&String, Object&
public void setParameters(Map&String, String[]& parameters) {
this.parameters =
public void setSession(Map&String, Object& session) {
this.session =
public void setRequest(Map&String, Object& request) {
this.request =
public void setApplication(Map&String, Object& application) {
this.application =
1 &%@ page language=&java& contentType=&text/ charset=UTF-8&
pageEncoding=&UTF-8&%&
3 &!DOCTYPE html PUBLIC &-//W3C//DTD HTML 4.01 Transitional//EN& &http://www.w3.org/TR/html4/loose.dtd&&
6 &meta http-equiv=&Content-Type& content=&text/ charset=UTF-8&&
7 &title&Insert title here&/title&
&form action=&login& method=&post&&
User Name:
&input type=&text& name=&username& /&
&input name=&submit& type=&submit& value=&submit&/&
16 &/body&
17 &/html&
1 &%@ page language=&java& contentType=&text/ charset=UTF-8&
pageEncoding=&UTF-8&%&
3 &!DOCTYPE html PUBLIC &-//W3C//DTD HTML 4.01 Transitional//EN& &http://www.w3.org/TR/html4/loose.dtd&&
6 &meta http-equiv=&Content-Type& content=&text/ charset=UTF-8&&
7 &title&Insert title here&/title&
欢迎${sessionScope.loginusername}登录!
当前登录人数:${applicationScope.count}
&a href=&logout.do&&logout&/a&
16 &/body&
17 &/html&
String usernameWithServletActionContext=ServletActionContext.getRequest().getParameter(&username&);
1 HttpServletResponse httpServletResponse=ServletActionContext.getResponse();
2 HttpServletRequest httpServletRequest=ServletActionContext.getRequest();
3 HttpSession httpSession=ServletActionContext.getRequest().getSession();
4 ActionContext actionContext=ServletActionContext.getContext();
1 package com.dx.
3 import javax.servlet.ServletC
4 import javax.servlet.http.HttpServletR
5 import javax.servlet.http.HttpServletR
7 import org.apache.struts2.interceptor.ServletRequestA
8 import org.apache.struts2.interceptor.ServletResponseA
9 import org.apache.struts2.util.ServletContextA
11 public class TestServletXxxAware implements ServletContextAware, ServletRequestAware,ServletResponseAware {
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
public void setServletContext(ServletContext arg0) {
// TODO Auto-generated method stub
本文已收录于以下专栏:
相关文章推荐
在传统的Web开发中,经常会用到ServletAPI中的HttpServletRequest、HttpSession和ServletContext。Struts 2框架让我们可以直接访问和设置acti...
一、什么是web资源?
  HttpServletRequest,HttpSession,ServletContext,等原生的Servlet api对象这些都是属于web中的资源
  
二、为什么...
struts2自主学习之配置国际化资源文件,传统异常处理方式, 拦截器,实现action 控制类,访问servletAPI,使用拦截器注解
1: Map IoC  方式
package com.
import java.util.M
import org.apache.struts2.interc...
1.创建Request,Session,Application的Map对象
一.通过com.opensymphony.xwork2.ActionContext
public Object get(Object key): ActionContext 类中没有提供类似 get...
方案一:Tomcat的defaultServlet来处理静态文件
要放在DispatcherServlet的前面, 让 defaultServlet先拦截请求,这样请求就不会进入Sp...
在说Action类之前先引入一个小action的概念,大家都知道struts2的默认请求格式是以  .action结尾或者不加(默认
常量配置在org.apache.struts2包下的defaul...
举例说明:火车站卖票,火车票总数是一定的,卖火车票的窗口有多个(2个),每个窗口就相当于一个线程,这么多的线程共用所有的火车票数量资源。如果在一个时间点上,两个线程同时使用这个资源,这样就会给乘客造成...
他的最新文章
讲师:宋宝华
讲师:何宇健
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)

我要回帖

更多关于 web action 的文章

 

随机推荐