Java Web之Struts2訪問Servlet API

YungFan發表於2017-12-13

方法一:直接獲取 Map型別

Map request = (Map)Actioncontext.getContext().get("request");
Map session = ActionContext.getContext.getSession();
Map application = ActionContext.getContext.getApplication();

比如使用:request.put("name",name);
可以在Jsp頁面獲取 <s:property value="#request.name"/> 
說明:<s:property/>為struts2的標籤。
複製程式碼

方法二:實現介面,依賴struts2注入 Map 型別

public class LoginAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware{
     private Map<String, object> request;
     private Map<String, object> session;
     private Map<String, object> application;
     @override
     public void setRequest(Map<String,object> request){
            this.request=request;
     } 
     @override
      public void setSession(Map<String,object> session){
            this.session=session;
     } 
     @override
      public void setApplication(Map<String,object> application){
            this.application=application;
     } 
}
複製程式碼

方法三:獲取httpServlet型別的

private HttpServletRequest request = ServletActionContext.getRequest();
private HttpSession session = request.getSession();
private ServletContext application = session.getServletContext();
比如使用request :request.setAttribute("name",name);
複製程式碼

方法四:獲取httpServlet型別的,實現ServletRequestAware 介面

public class LoginAction extends ActionSupport implements ServletRequestAware{
     private HttpServletRequest request;
     private HttpSession session;
     private ServletContext application;
     public void setServletRequest(HttpServletRequest ruequst){
          this.request = request;
          this.session = request.getSession();
          this.application = session.getServletContext();
     }
}
複製程式碼

相關文章