java中怎样获取类的context,java中action请求是什么
今天小编为大家分享Windows系统下载、Windows系统教程、windows相关应用程序的文章,希望能够帮助到大家!
在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息,甚至需要直接对JavaServlet Http的请求(HttpServletRequest),响应(HttpServletResponse)操作.我们需要在Action中取得request请求参数"username"的值:
ActionContext context= ActionContext.getContext();
Map params= context.getParameters();
String username=(String) params.get("username");
on执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个Map而已),它存放的是Action在执行时需要用到的对象.一般情况,我们的ActionContext都是通过: ActionContext context=(ActionContext) actionContext.get();来获取的.我们再来看看这里的actionContext对象的创建:
static ThreadLocal actionContext= new ActionContextThreadLocal();
ActionContextThreadLocal是实现ThreadLocal的一个内部类.ThreadLocal可以命名为"线程局部变量",它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突.这样,我们ActionContext里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的.
通过ActionContext取得HttpSession: Map session= ActionContext.getContext().getSession();
ServletActionContext(com.opensymphony.webwork. ServletActionContext),这个类直接继承了我们上面介绍的ActionContext,它提供了直接与Servlet相关对象访问的功能,它可以取得的对象有:
(1)javax.servlet.http.HttpServletRequest: HTTPservlet请求对象
(2)javax.servlet.http.HttpServletResponse: HTTPservlet相应对象
(3)javax.servlet.ServletContext: Servlet上下文信息
(4)javax.servlet.ServletConfig: Servlet配置对象
(5)javax.servlet.jsp.PageContext: Http页面上下文
如何从ServletActionContext里取得Servlet的相关对象:
<1>取得HttpServletRequest对象: HttpServletRequest request= ServletActionContext. getRequest();
<2>取得HttpSession对象: HttpSession session= ServletActionContext. getRequest().getSession();
3. ServletActionContext和ActionContext联系
ServletActionContext和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢?我们遵循的原则是:如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问Servlet的相关对象.
注意:在使用ActionContext时有一点要注意:不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null;同样,HttpServletRequest req= ServletActionContext.getRequest()也不要放在构造函数中,也不要直接将req作为类变量给其赋值。至于原因,我想是因为前面讲到的static ThreadLocal actionContext= new ActionContextThreadLocal(),从这里我们可以看出ActionContext是线程安全的,而ServletActionContext继承自ActionContext,所以ServletActionContext也线程安全,线程安全要求每个线程都独立进行,所以req的创建也要求独立进行,所以ServletActionContext.getRequest()这句话不要放在构造函数中,也不要直接放在类中,而应该放在每个具体的方法体中(eg:login()、queryAll()、insert()等),这样才能保证每次产生对象时独立的建立了一个req。
4. struts2中获得request、response和session
方法一:使用org.apache.struts2.ActionContext类,通过它的静态方法getContext()获取当前Action的上下文对象。
ActionContext ctx= ActionContext.getContext();
ctx.put("liuwei","andy");//request.setAttribute("liuwei","andy");
Map session= ctx.getSession();//session
HttpServletRequest request= ctx.get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
HttpServletResponse response= ctx.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
细心的朋友可以发现这里的session是个Map对象,在Struts2中底层的session都被封装成了Map类型.我们可以直接操作这个Map对象进行对session的写入和读取操作,而不用去直接操作HttpSession对象.
方法二:使用org.apache.struts2.ServletActionContext类
public class UserAction extends ActionSupport{
private HttpServletRequest req;
// private HttpServletRequest req= ServletActionContext.getRequest();这条语句放在这个位置是错误的,同样把这条语句放在构造方法中也是错误的。
req= ServletActionContext.getRequest();//req的获得必须在具体的方法中实现
req.getSession().setAttribute("user", user);
req= ServletActionContext.getRequest();//req的获得必须在具体的方法中实现
req.getSession().setAttribute("uList", uList);
(2)IoC方式(即使用Struts2 Aware拦截器)
要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。
public class UserAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware{
private HttpServletRequest request;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest request){
public void setServletResponse(HttpServletResponse response){
HttpSession session= request.getSession();
为了让用户开发的Action类更加规范,Struts2提供了一个Action接口,这个接口定义了Struts2的Action处理类应该实现的规范。下面是标准Action接口的代码:
//定义Action接口里包含的一些结果字符串
public static final String ERROR="error";
public static final String INPUT="input";
public static final String LOGIN="login";
public static final String NONE="none";
public static final String SUCCESS="success";
//定义处理用户请求的execute()方法
public String execute() throws Exception;
上面的Action接口里只定义了一个execute()方法,该接口规范规定了Action类应该包含一个execute()方法,该方法返回一个字符串,此外,该接口还定义了5个字符串常量,他的作用是统一execute()方法的返回值。
例如,当Action类处理用户处理成功后,有人喜欢返回welcome字符串,有人喜欢返回success字符串,如此不利于项目的统一管理,Struts2的Action接口定义加上了如上的5个字符串常量:ERROR,NONE,INPUT,LOGIN,SUCCESS等,分别代表了特定的含义。当然,如果开发者依然希望使用特定的字符串作为逻辑视图名,开发者依然可以返回自己的视图名。
另外,Struts2还为Action接口提供了一个实现类:ActionSupport,下面是该实现类的代码:
package com.opensymphony.xwork2;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import java.util.ResourceBundle;
* Provides a default implementation for the most common actions.
* See the documentation for all the interfaces this class implements for more detailed information.
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable{
protected static Logger LOG= LoggerFactory.getLogger(ActionSupport.class);
private final ValidationAwareSupport validationAware= new ValidationAwareSupport();
private transient TextProvider textProvider;
public void setActionErrors(Collection<String> errorMessages){
validationAware.setActionErrors(errorMessages);
public Collection<String> getActionErrors(){
return validationAware.getActionErrors();
public void setActionMessages(Collection<String> messages){
validationAware.setActionMessages(messages);
public Collection<String> getActionMessages(){
return validationAware.getActionMessages();
*@deprecated Use{@link#getActionErrors()}.
public Collection<String> getErrorMessages(){
*@deprecated Use{@link#getFieldErrors()}.
public Map<String, List<String>> getErrors(){
public void setFieldErrors(Map<String, List<String>> errorMap){
validationAware.setFieldErrors(errorMap);
public Map<String, List<String>> getFieldErrors(){
return validationAware.getFieldErrors();
ActionContext ctx= ActionContext.getContext();
LOG.debug("Action context not initialized");
public boolean hasKey(String key){
return getTextProvider().hasKey(key);
public String getText(String aTextName){
return getTextProvider().getText(aTextName);
public String getText(String aTextName, String defaultValue){
return getTextProvider().getText(aTextName, defaultValue);
public String getText(String aTextName, String defaultValue, String obj){
return getTextProvider().getText(aTextName, defaultValue, obj);
public String getText(String aTextName, List<Object> args){
return getTextProvider().getText(aTextName, args);
public String getText(String key, String[] args){
return getTextProvider().getText(key, args);
public String getText(String aTextName, String defaultValue, List<Object> args){
return getTextProvider().getText(aTextName, defaultValue, args);
public String getText(String key, String defaultValue, String[] args){
return getTextProvider().getText(key, defaultValue, args);
public String getText(String key, String defaultValue, List<Object> args, ValueStack stack){
return getTextProvider().getText(key, defaultValue, args, stack);
public String getText(String key, String defaultValue, String[] args, ValueStack stack){
return getTextProvider().getText(key, defaultValue, args, stack);
public ResourceBundle getTexts(){
return getTextProvider().getTexts();
public ResourceBundle getTexts(String aBundleName){
return getTextProvider().getTexts(aBundleName);
public void addActionError(String anErrorMessage){
validationAware.addActionError(anErrorMessage);
public void addActionMessage(String aMessage){
validationAware.addActionMessage(aMessage);
public void addFieldError(String fieldName, String errorMessage){
validationAware.addFieldError(fieldName, errorMessage);
//默认Input方法,直接访问input字符串
public String input() throws Exception{
public String doDefault() throws Exception{
* A default implementation that does nothing an returns"success".
* Subclasses should override this method to provide their business logic.
* See also{@link com.opensymphony.xwork2.Action#execute()}.
*@return returns{@link#SUCCESS}
*@throws Exception can be thrown by subclasses.
//默认处理用户请求的方法,直接返回SUCCESS字符串
public String execute() throws Exception{
public boolean hasActionErrors(){
return validationAware.hasActionErrors();
public boolean hasActionMessages(){
return validationAware.hasActionMessages();
return validationAware.hasErrors();
public boolean hasFieldErrors(){
return validationAware.hasFieldErrors();
* Clears field errors. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
public void clearFieldErrors(){
validationAware.clearFieldErrors();
* Clears action errors. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
public void clearActionErrors(){
validationAware.clearActionErrors();
* Clears messages. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
validationAware.clearMessages();
* Clears all errors. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
validationAware.clearErrors();
* Clears all errors and messages. Useful for Continuations and other situations
* where you might want to clear parts of the state on the same action.
public void clearErrorsAndMessages(){
validationAware.clearErrorsAndMessages();
* A default implementation that validates nothing.
* Subclasses should override this method to provide validations.
public Object clone() throws CloneNotSupportedException{
*<!-- START SNIPPET: pause-method-->
* Stops the action invocation immediately(by throwing a PauseException) and causes the action invocation to return
* the specified result, such as{@link#SUCCESS},{@link#INPUT}, etc.
* The next time this action is invoked(and using the same continuation ID), the method will resume immediately
* after where this method was called, with the entire call stack in the execute method restored.
* Note: this method can<b>only</b> be called within the{@link#execute()} method.
*<!-- END SNIPPET: pause-method-->
*@param result the result to return- the same type of return value in the{@link#execute()} method.
public void pause(String result){
* If called first time it will create{@link com.opensymphony.xwork2.TextProviderFactory},
* inject dependency(if{@link com.opensymphony.xwork2.inject.Container} is accesible) into in,
* then will create new{@link com.opensymphony.xwork2.TextProvider} and store it in a field
* for future references and at the returns reference to that field
*@return reference to field with TextProvider
private TextProvider getTextProvider(){
TextProviderFactory tpf= new TextProviderFactory();
textProvider= tpf.createInstance(getClass(), this);
public void setContainer(Container container){
正如上面代码中的,ActionSupport是一个默认的Action实现类,该类里已经提供了许多默认方法,这些方法包括获取国际化信息的方法、数据校验的方法、默认的处理用户请求的方法等,实际上,ActionSupport是Struts2的默认的Action处理类,如果让开发者的Action类继承该ActionSupport类,则会大大简化Action的开发。
wwW.Xtw.Com.cN系统网专业的PC、手机系统开发下载平台,HarmonyOS系统、安卓、OS、windows电脑重装系统在线下载安装,操作系统平台技术学习,攻略教程,技术交流。
免责声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。内容仅供参考使用,不准确地方联系删除处理!
联系邮箱:773537036@qq.com