九、在动作类中访问ServletAPI

九、在动作类中访问ServletAPI

1、方式一:(简单,推荐使用)ServletActionContext

public String execute() throws Exception {

        //获取Servlet的相关对象引用,HttpServletRequest HttpSession HttpServletResponse ServletContext

        //PageContext等等

        HttpServletRequest request = ServletActionContext.getRequest();

        PageContext pc = ServletActionContext.getPageContext();

        HttpServletResponse response = ServletActionContext.getResponse();

        ServletContext sc = ServletActionContext.getServletContext();

        HttpSession session = request.getSession();

        //打印相关对象引用

        System.out.println(request);

        System.out.println(pc);

        System.out.println(response);

        System.out.println(sc);

        System.out.println(session);

        return "none";

    }

 

 

  1. 方式二:(麻烦)

    动作类实现特定的接口。就必须实现特定的方法,调用动作方法前,框架会把响应的对象给注入进来。

    public class UserAction implements ServletRequestAware, ServletResponseAware, ServletContextAware {

        private HttpServletRequest request;

        private HttpServletResponse response;

        private ServletContext sc;

        public String execute() {

            //打印相关对象引用

            System.out.println(request);

            System.out.println(response);

            System.out.println(sc);

            return "none";

        }

     

        //在调用动作方法执行前,框架会把ServletContext对象给注入进来

        @Override

        public void setServletContext(ServletContext sc) {

            this.sc = sc;

            

        }

        //在调用动作方法执行前,框架会把HttpServletResponse对象给注入进来

        @Override

        public void setServletResponse(HttpServletResponse response) {

            this.response = response;

            

        }

        //在调用动作方法执行前,框架会把HttpServletRequest对象给注入进来

        @Override

        public void setServletRequest(HttpServletRequest request) {

            this.request = request;

            

        }

    }

     

     

    原理:是一个拦截器给你注入进来的。struts-default.xml

    <interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>

    一看源码便知。

     

posted @ 2016-09-19 19:42  runningto  阅读(269)  评论(0编辑  收藏  举报