java中ServletContext 物件的獲取方法
阿新 • • 發佈:2019-02-12
1.在javax.servlet.Filter中直接獲取
ServletContext context = config.getServletContext();
2.在HttpServlet中直接獲取
this.getServletContext()
3.在其他方法中,通過HttpRequest獲得
request.getSession().getServletContext();
當然struts2中還有常見的兩種方法獲得
獲取HttpServletRequest / HttpSession / ServletContext / HttpServletResponse物件
方法一,通過ServletActionContext.類直接獲取:
public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession()
HttpServletResponse response = ServletActionContext.getResponse();
return "scope";
}
方法二,實現指定介面,由struts框架執行時注入:
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public void setServletResponse(HttpServletResponse res) {
this.response=res;
}
public void setServletContext(ServletContext ser) {
this.servletContext=ser;
}
}
ServletContext context = config.getServletContext();
2.在HttpServlet中直接獲取
this.getServletContext()
3.在其他方法中,通過HttpRequest獲得
request.getSession().getServletContext();
當然struts2中還有常見的兩種方法獲得
獲取HttpServletRequest / HttpSession / ServletContext / HttpServletResponse物件
方法一,通過ServletActionContext.類直接獲取:
public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession()
HttpServletResponse response = ServletActionContext.getResponse();
return "scope";
}
方法二,實現指定介面,由struts框架執行時注入:
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public void setServletResponse(HttpServletResponse res) {
this.response=res;
}
public void setServletContext(ServletContext ser) {
this.servletContext=ser;
}
}