Servlet存储数据的方式
在Servlet中,使用ServletContext对象来存储整个WebApp的数据,ServletContext中直接存储整个WebApp的公共数据,可使用set|get|removeAttribute()来操作数据。
此外ServletContext中还有3类众多的小对象:
- ServletConfig 一个ServletConfig存储一个Servlet的初始化配置参数
- request 一个request存储一个用户的请求参数
- session 一个session存储一个用户的会话信息
这3类对象也用于存储数据,也有对应的set|get|removeAttribute()方法。
一共是4类对象,这4类对象均使用Map来存储数据,这个Map叫做域。
Action操作数据的方式
Action是用来代替Servlet的,Servlet用ServletContext来存储数据,Action用ActionContext来存储数据。
ActionContext context = ActionContext.getContext(); //设置、修改、获取参数 context.put("age",18); int age =(int) context.get("age"); //返回值是Object,需要强转
ActionContext本身可以存储数据,ActionContext中也有其他的域对象。
ActionContext context = ActionContext.getContext();
Map<String, Object> application = context.getApplication(); //获取ServletContext的Map对象,即application域
Map<String, Object> session = context.getSession(); //获取session对象的Map对象,即session域
HttpParameters parameters = context.getParameters(); //获取所有的请求参数,此对象相当于EL内置的param、paramValues对象
Map对象、HttpParameters对象均有put()、get()、remove()方法,可通过这些方法来操作数据。
获取原生的Servlet对象,通过原生的Servlet对象来操作数据
Struts2提供了三种方式,来获取原生的Servlet对象。
1、ActionContext本身可以存储数据,也可以获取ServletContext、request、response三个原生的Servlet对象:
ActionContext context = ActionContext.getContext(); //获取原生的Servlet对象。因为get()返回值是Object,所以均需强转 ServletContext servletContext = (ServletContext) context.get("com.opensymphony.xwork2.dispatcher.ServletContext"); HttpServletRequest request = (HttpServletRequest) context.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest"); HttpServletResponse response = (HttpServletResponse) context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
2、key太复杂,记不住,所以Struts2提供了工具类ServletActionContext:
//均为ServletActionContext类的静态方法 ServletContext servletContext = ServletActionContext.getServletContext(); HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse();
3、通过实现接口来获取
public class LoginAction extends ActionSupport implements ServletContextAware { @Override public String execute() throws Exception { return super.execute(); } @Override public void setServletContext(ServletContext servletContext) { } }
实现ServletContextAware接口,只需实现一个方法。Tomcat会获取并传入一个ServletContext对象,我们要做的就是写一个ServletContext类型的成员变量,把传入的值赋给它,这样这个Action中就可以直接使用ServletContext对象了(成员变量)。
public class LoginAction extends ActionSupport implements ServletContextAware { private ServletContext servletContext; @Override public String execute() throws Exception { return super.execute(); } @Override public void setServletContext(ServletContext servletContext) { this.servletContext=servletContext; } }
要使用ServletContext对象,就实现ServletContextAware接口;
要使用HttpServletRequest对象,就实现ServletRequestAware接口;
要使用HttpServletResponset对象,就实现ServletResponseAware接口;
可同时实现这些接口。
其实第2、3种方式底层都是:调用第一种方式获取原生的Servlet对象,返回。
&n