Servlet API & ActionContext

Servlet API
  • struts2获取servlet api的方式

    • 解耦
      • 使得使用struts2来进行测试时,不需要启动服务器
      • 在一定程度上提高了开发效率
      • 一般情况下的分层结构: 
        • action -> service -> dao
    • 耦合
  • 使用解耦:

    • 通过ActionContext对象获取session/request/parameter

      //获取session
      ActionContext.getContext().getSession().put("user", name);
      //获取request---获取HttpServletRequest对象的attribute
      Map<String, Object> request =(Map) ActionContext.getContext().get("request");
      
      //获取application---servlet context
      Map<String, Object> application = ActionContext.getContext().getApplication();
      
      //获取parameters
      Map parameters = ActionContext.getContext().getParameters();
      //相当于request.getParameter("name");
      System.out.println("name = " + parameters.get("name") + "---" + parameters.get("pwd"));
    • 通过ActionContext获取HttpServletRequest

      HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
      request.getSession().setAttribute("user", name);
  • 通过耦合:

    • 实现ServletRequestAware接口

      @Override
      public void setServletRequest(HttpServletRequest request) {
          this.request = request;
      }
    • 通过ServletActionContext获取HttpServletRequest

      HttpServletRequest request = ServletActionContext.getRequest();
      request.getSession().setAttribute("user", name);
      System.out.println("3:" + name);
  • 解耦建议使用第一种,耦合建议使用第二种

ActionContext
  • ActionContext基础

    • 是一个map结构的容器
    • 是Action的上下文,存放Action执行过程中的数据信息(ActionInvocation, request, session, application, locale)
    • 每次请求都会为当前线程创建一个新的ActionContext
    • ActionContext采用ThreadLocal来存放数据,所以ActionContext是线程安全的
  • 获取ActionContext

    • ActionContext.getAction()
    • ActionContext是通过静态方法获取的,所以在本线程中的非Action类中,也可以直接访问使用
    • 注意: ActionContext是基于请求创建的,所以在非请求的线程中不能使用ActionContext对象(例如过滤器filter中的init方法)
  • ThreadLocal模式

    • ThreadLocal存放线程局部变量的容器
    • 存放在ThreadLocal中的变量是线程安全的
    • 只能存放一个值,且会被覆盖
    • 示例
      final ThreadLocal<String> ac = new ThreadLocal<String> ();
      ac.set("char");
      ac.set("test");
      
      new Thread(new Runnable() {
          public void run() {
              //打印的值为:thead:null
              System.out.println("thread:" + ac.get());
          }
          }).start();
      System.out.println(ac.get()); //打印结果为test
  • ActionContext的六大对象:

    • application
    • session
    • request
    • parameters
    • attr
      • 取值顺序: page->request->session->application
    • ValueStack(值栈)
      • stack结构,先进后出
      • struts2中存放的数据是Action对象

猜你喜欢

转载自blog.csdn.net/weixin_40683252/article/details/81048194
今日推荐