五、Struts2框架中如何使用Servlet的API

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mChenys/article/details/84861046

有两种方式,一种是调用框架提供的api间接的使用Servlet的api,也叫完全解耦的方式,另一种直接使用原生Servlet的API。

完全解耦合的方式

如果使用该种方式,Struts2框架中提供了一个类,ActionContext类,该类中提供一些方法,通过方法获取Servlet的API,一些常用的方法如下:

  • static ActionContext getContext() :获取ActionContext对象实例
  • java.util.Map<java.lang.String,java.lang.Object> getParameters() :获取请求参数,相当于request.getParameterMap();
  • java.util.Map<java.lang.String,java.lang.Object> getSession() :获取的代表session域的Map集合,就相当于操作session域。
  • java.util.Map<java.lang.String,java.lang.Object> getApplication() :获取代表application域的Map集合
  • void put(java.lang.String key, java.lang.Object value) :向request域中存入值。

例如:

/**
 * 完全接耦合的方式
 * 
 * @author mChenys
 *
 */
public class Demo1Action extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Override
	public String execute() throws Exception {
		// 获取ActionContext对象
		ActionContext context = ActionContext.getContext();
		// 获取请求参数
		Map<String, Object> map = context.getParameters();
		for (String key : map.keySet()) {
			// 通过key获取值
			String[] values = (String[]) map.get(key);
			System.out.println(key + ":" + Arrays.toString(values));
		}

		// request域
		context.put("msg", "request域值");
		// 操作session域
		context.getSession().put("msg", "session域值");
		// 操作application域
		context.getApplication().put("msg", "application域值");

		return SUCCESS;
	}
}

使用原生Servlet的API的方式

Struts2框架提供了一个类,ServletActionContext,该类中提供了一些静态的方法,具体的方法如下:

  • getPageContext():获取PageContext对象
  • getRequest():获取HttpServletRequest对象
  • getResponse():获取HttpServletResponse对象
  • getServletContext():获取ServletContext对象

例如:

/**
 * 使用原生api方式
 * @author mChenys
 *
 */
public class Demo2Action extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Override
	public String execute() throws Exception {
		PageContext pageContext = ServletActionContext.getPageContext();
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		ServletContext servletContext = ServletActionContext.getServletContext();
		
		//然后就可以正常使用Servlet的api了...
		
		return SUCCESS;
	}
}

猜你喜欢

转载自blog.csdn.net/mChenys/article/details/84861046