Struts2訪問資料(二)servletContextAction和ServletAware
阿新 • • 發佈:2019-02-16
1.ServletActionContext方式
可以訪問原始API
TestServletActionContextAction.java
package Demo2;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
public class TestServletActionContextAction {
public String execute()
{
/*
* Servlet ActionContext:可以從中獲取到當前Action物件需要的一切Servlet API物件
* 常用的方法:
* 獲取HttpServletRequest:ServletActionContext.getRequest()
* 獲取HttpSession:ServletActionContext.getRequest().getSession()
* 獲取ServletContext:ServletActionContext.getServletContext()
*/
HttpServletRequest request=ServletActionContext.getRequest();
HttpSession session=ServletActionContext.getRequest().getSession();
ServletContext servletContext=ServletActionContext.getServletContext();
System.out.println("execute...");
return "success";
}
}
總結:HttpServletRequest:ServletActionContext.getRequest()
2.ServletAware
TestServletAwareAction.java
實現 ServletRequestAware,ServletContextAware,ServletResponseAware
介面
package Demo2;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.util.ServletContextAware;
/*
* 通過實現ServletSxxAware介面的方式由Struts2注入
* 需要的Servlet相關的介面
* ServletRequestAware,ServletContextAware,ServletResponseAware
*/
public class TestServletAwareAction implements
ServletRequestAware,ServletContextAware{
@Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
System.out.println(request);
}
private ServletContext context;
@Override
public void setServletContext(ServletContext context) {
// TODO Auto-generated method stub
System.out.println(context);
this.context=context;
}
public String execute()
{
System.out.println("............");
System.out.println("ServletContext: "+context);
return "sussess";
}
}
總結:實現serrvletXxxAware介面,寫public void ServletXxxAware(ServletXxx xxx)方法