如果是一个普通的POJO类中如何获取request对象的引用
你可以在 POJO 类中写一个方法把 request对象作为参数传过去。

解决方案 »

  1.   

    我只是想知道这里为什么是null
    因为你没有在里面存放任何东西,当然是空啦
      

  2.   


    这是一个办法,但是我主要想弄清楚ServletActionContext.getRequest()为什么不行,它到顶怎么用?为什么在action中是有效的?
      

  3.   


    我取的request对象,不是放在request对象中的obj,再说现在练request对象都不能引用到!(用ServletActionContext.getRequest())
      

  4.   

    你可以功过在你的action中
    User user = new User();
    user.setName("aaa");
    ActionContext ctx = ActionContext.getContext();
    ctx.put("user",user);在你的JSP中
    可以用EL表达式${user.name}来得到
      

  5.   


    谢谢!你的回答没有错!不过我的问题是ServletActionContext的用法,用这个类如何获得request对象?这么问吧!假设我有一个自定义的ServletUitl类public class ServletUtil
    {
        public static void formate(String key)
        {
            HttpServletRequest request = ServletActionContext.getRequest();
            String value = (String)request.getAttribute(key);
            value = value + "经过格式化过程了!";
            request.setAttribute(key,value);
        }
    }jsp页面
    <%
        request.setAttribute("key","hello world!");
        ServletUtil.formate("key");
        String value = (String)request.getAttribute("key");
        out.println(value);
    %>但是页面上不会出现hello world!经过格式化过程了!再强调一下,我的目的是想知道ServletActionContext.getRequest()为什么是null,
    或者如何在一个普通的POJO类中获得request对象的引用? 
      

  6.   

    我不懂 struts2 但根据你的回答我猜测 ServletActionContext 这个类应该是 struts2 框架的一个类. 也就是说 
    ServletActionContext.getRequest(); 可以拿到请求是应该 在 你框架的 action中 耦合进来来的一个方法。
    但普通的jsp和 java类同你的 框架没有任何关系. 自然就得不到你的框架的支持.
      

  7.   

    我感觉是  你的那个类  不能直接用  还没有生成对象  怎么能直接ServletUtil.formate("key"); 
      

  8.   

    我想是这样的:继承ActionSupport必然就是一个Action,而ServletActionContext.getRequest()是struts2容器提供的,当服务器启动起来之后,通过ServletActionContext的静态方法getRequest()得到request对象,而这个request对象必须是在servlet容器中有效的。
      

  9.   

    在ServletActionContext源代码中有这么一段:
        public static void setRequest(HttpServletRequest request) {
            ActionContext.getContext().put(HTTP_REQUEST, request);
        }意思可能就是容器通过加载ServletActionContext将request对象设置进入了ServletActionContext,当我们调用的时候,
    由于struts包是由容器加载的,所以我们调用的ServletActionContext就是已经存在request对象的那个类,
    这样才能得到一个request对象;