日期:2014-05-17  浏览次数:20621 次

struts2中,action里如何获取session的值,我菜
我在一个Action里面设置了session 
Map session = ActionContext.getContext().getSession(); 
session.put("userName", userName); --这里userName在前面已经有值了
我在另一个Action里面怎么把这个session取出来?
 
我用的是 
Map session = ActionContext.getContext().getParameters(); 
temp = (String)session.get("userName"); --这里temp为String型,有get和set方法

我用
temp = (String)session.get("userName")+“111”;
第二个action返回的页面上写
<s:property value="#session.userNm"/>
进行测试
结果页面显示为:
null111

表示这种方法取出来的值是null。请问哪里出错,我在另一个ACtion里面怎么把这个session取出来?
有具体实现的代码吗?
谢谢!

------解决方案--------------------
Java code

Map map = ActionContext.getContext().getSession();
temp = (String) map.get("userName");

------解决方案--------------------
确定两个Action都继成了ActionSupport
在确定下两个Action的先后顺序

建议在项目中自己先写个class ABaseAction extends ActionSupport
实现常用的方法如:


public Map getStruts2Session()
{
return ActionContext.getContext().getSession();
}

public Map getStrus2Application()
{
return ActionContext.getContext().getApplication();
}


public HttpServletRequest getRequest()
{
return ServletActionContext.getRequest();
}

public HttpServletResponse getResponse()
{
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
return response;
}

public HttpSession getHttpSession()
{
return getRequest().getSession();
// or return ServletActionContext.getRequest().getSession();
// or return (HttpSession)ServletActionContext.getContext().get(ServletActionContext.SESSION);
等等。。。。。


然后你的Action都继成ABaseAction
------解决方案--------------------
Java code

    public Object get(String name) {        
       return ActionContext.getContext().getSession().get(name);
        
    }
    
    @SuppressWarnings("unchecked")
    public void set(String name, Object value) {
       ActionContext.getContext().getSession().put(name, value);
    }
    
    protected void remove(Object key) {
       ActionContext.getContext().getSession().remove(key);
    }

        //获取对象信息方法
        public Object getSessionInfo() {
        Map session = (Map) ActionContext.getContext().getSession();
        return (Object) session.get("Object");
    }

------解决方案--------------------
这样吧, 我给你个例子
java:
Java code

package com.lil.test_ch05_02.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class RedirectTest extends ActionSupport {
    private String username;
    
    public String getUsername() {
        return username;
    }
    
    public void setUsername(String username) {
        this.username=username;
    }
    
    public String execute() throws Exception {
        Map user=(Map)ActionContext.getContext().getSession();
        user.put("tmp", "zhangsan");
        
        return SUCCESS;
    }
}