package com.lx.Elements;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
public class WebAction implements RequestAware,SessionAware,ApplicationAware,
ServletRequestAware,ServletResponseAware{
private List<String> list ;
/* 获取四大属性范围总的来说可分为两大方式:
* 第一:与Servlet API解耦的访问方式(通过实现接口,注入属性,覆盖Setter方法实现)
* 第二:与Servlet API耦合的访问方式.(通过ActionContext的静态方法实现)
* 推荐使用第一种即通过注入获取
*/
//1、解耦方式获取web元素
//(1)通过实现接口,注入属性获取map格式的web元素。(推荐)
private Map map_request ;
private Map map_session ;
private Map map_application;
//(2)(推荐)通过实现接口(ServletRequestAware,ServletResponseAware),注获取map格式的web元素.
private HttpServletRequest h_req;
private HttpServletResponse h_resp;
public String execute() throws IOException{
System.out.println("进了action了===list");
list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
this.map_request.put("req", "map_request");
this.map_session.put("ses", "map_session");
this.map_application.put("app", "map_application");
this.h_req.setAttribute("h_req", "h_req.setAttribute");
PrintWriter out = this.h_resp.getWriter();
//------------------------
//(2)通过ActionContext的静态方法获取Map格式的web元素
Map mapRequest = (Map) ServletActionContext.getContext().get("request");
Map mapResponse = (Map) ServletActionContext.getContext().get("response");
Map mapApplication = ServletActionContext.getContext().getApplication();
Map mapSession = ServletActionContext.getContext().getSession();
//(3)通过ServletActionContext的静态方法获取真正的Web元素
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
//--------------------------
//2、跟Servlet API耦合
//获取真正的web元素
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse reps = ServletActionContext.getResponse();
HttpSession session = req.getSession();
ServletContext sc = ServletActionContext.getServletContext();
return "success";
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public void setRequest(Map request) {
this.map_request= request;
}
public void setSession(Map session) {
this.map_session = session ;
}
public void setApplication(Map application) {
this.map_application = application;
}
public void setServletRequest(HttpServletRequest request) {
this.h_req = request;
}
public void setServletResponse(HttpServletResponse response) {
this.h_resp = response;
}
}