Struts2学习之二(受管理 BEAN得到 REQUEST与 RESPONSE对象 )
有两种方法:
1,IOC方式:实现ServletRequestAware与ServletResponseAware接口。
2,非IOC方式:ServletActionContext.getRequest()等静态方法。
public class HelloActionReqAndRes
implements ServletRequestAware,ServletResponseAware {
//IOC方式得到request实现接口
private String hello;
private HttpServletRequest request;
private HttpServletResponse response;
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public String execute() throws Exception {
//非IOC方式得到request
HttpServletRequest request2 =
ServletActionContext.getRequest();
//ServletActionContext.getResponse();
System.out.println("request.getParameter('hello'): "
+ request.getParameter("hello"));
System.out.println("request.getAttribute('hello'): "
+ request.getAttribute("hello"));
this.hello = "Action Change Hello";
System.out.println("request.getAttribute('hello'): "
+ request.getAttribute("hello"));
return "ok";
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
System.out.println("setServletRequest");
}
public void setServletResponse(HttpServletResponse respons) {
this.response = respons;
System.out.println("setServletResponse");
}
}