struts2如何得到siervlet对象

问题?struts2如何得到siervlet对象,有几种方式

我们用案例来说明:

1.首先是struts.xml文件的action设置

<package name="webObj" namespace="/webObj" extends="mypackage">
		<action name="webAction1" class="cn.itcast.action.WebObjectAction" 

method="execute1">
			<result name="success">/web.jsp</result>
		</action>
		<action name="webAction2" class="cn.itcast.action.WebObjectAction" 

method="execute2">
			<result name="success">/web.jsp</result>
		</action>
	</package>


2.得到servlet对象的action类

<span style="font-size:18px;">package cn.itcast.action;

import java.io.Serializable;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;
//获取Servlet中的常用对象的引用

//ServletContextAware、</span><span style="font-size:10px;"><span style="font-family: 'Microsoft YaHei';">ServletRequestAware、</span><span style="font-family: 'Microsoft YaHei';">ServletResponseAware</span></span><span style="font-size:18px;">接口这几个接口是依赖注入了servlet对象,我们可以通过他们的方//法得到

public class WebObjectAction extends ActionSupport implements Serializable,ServletContextAware,ServletRequestAware,ServletResponseAware {
	private ServletContext context;
	private HttpServletRequest request;
	private HttpServletResponse response;
	//方式一(推荐使用这种方式,简便点儿)
	public String execute1(){
		ServletContext sc = ServletActionContext.getServletContext();
		System.out.println(sc);
		ServletRequest request = ServletActionContext.getRequest();
		System.out.println(request);//seesion的对象可以通过request得到
		return SUCCESS;
	}
	//方式二
	public String execute2(){
		System.out.println(context);
		System.out.println(request);
		System.out.println(response);
		return SUCCESS;
	}
	public void setServletContext(ServletContext context) {//如果动作类实现了ServletContextAware接口,就会自动调用该方法
		this.context = context;
	}
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	
	
}
</span>





你可能感兴趣的:(struts2.0)