struts2.0学习笔记三(struts2.0action中获得request,response)

在Strutx 2.0你可以有两种方式获得这些对象:非IoC(控制反转Inversion of Control)方式和IoC方式。

1.非IOC方式

在struts2.0中存在一个com.opensymphony.xwork2.ActionContext类,通过该类的getContext()方法可以获得Struts的上下文环境,或者通过org.apache.struts2.ServletActionContext作为一个辅助类来得到.

HttpServletRequest request = ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContext.getResponse();

HttpSession session = request.getSession();

2.IOC方式

通过实现SessionAware, ServletRequestAware, ServletResponseAware接口

public class IoCServlet extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {
   
private String message;
   
private Map att;
   
private HttpServletRequest request;
   
private HttpServletResponse response;    
   
   
public String getMessage() {
       
return message;        
   }

   
   
publicvoid setSession(Map att) {
       
this.att = att;
   }

   
   
publicvoid setServletRequest(HttpServletRequest request) {
       
this.request = request;
   }

   
   
publicvoid setServletResponse(HttpServletResponse response) {
       
this.response = response;
   }

   
   @Override
   
public String execute() {        
       att.put(
"msg", "Hello World from Session!");
       
       HttpSession session
= request.getSession();
       
       StringBuffer sb
=new StringBuffer("Message from request: ");
       sb.append(request.getParameter(
"msg"));
       sb.append(
"<br>Response Buffer Size: ");
       sb.append(response.getBufferSize());
       sb.append(
"<br>Session ID: ");
       sb.append(session.getId());
       
       message
= sb.toString();
       
return SUCCESS;
   }

}

你可能感兴趣的:(apache,struts,IOC)