ActionContext.getContext()。getSession()和Null指针异常

时间:2014-05-26 13:50:32

标签: session struts2

我正在使用struts2,spring,spring security和hibernate开发应用程序。 我需要使用session,我尝试用这段代码定义我的会话:

Map session =  ActionContext.getContext().getSession();//line 1
session.put("objet",objet);// line2

但它返回一个java.lang.NullPointerException(line1) 你对这个问题有什么看法吗? 谢谢!

的LoginAction

public class LoginAction  extends ActionSupport implements SessionAware, Preparable, AuthenticationSuccessHandler {
private UserDetails userDetails;
private User userConnecte;
private Map session;
@Autowired
private UserBO userBO;
// DI via spring
public void setUserBO(UserBO userBO) {
    this.userBO = userBO;
}
/**
 * Getters and setters
 * @return
 */
public User getUserConnecte() {
    return userConnecte;
}

public void setUserConnecte(User userConnecte) {
    this.userConnecte = userConnecte;
}
public User getSession() {
    return session;
}

public void setSession(Map session) {
    this.session = session;
}

public void prepare() throws Exception {
    // TODO Auto-generated method stub

}
public void onAuthenticationSuccess(HttpServletRequest request,
        HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {


        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            this.userDetails =  (UserDetails) auth.getPrincipal();
        }
        this.userConnecte = this.userBO.retournerUserByEmail(this.userDetails.getUsername());
        this.session = ActionContext.getContext().getSession();
        session.put("userConnecte", this.userConnecte);


}

}

2 个答案:

答案 0 :(得分:0)

您可以在struts2过滤器启动操作时使用操作上下文。方法
onAuthenticationSuccess与struts2和动作上下文无关。使用servlet请求对象来获取会话。

HttpSession session = request.getSession(false);

答案 1 :(得分:0)

尝试这个,初始化你的Servlet Action Context,

public void onAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response, Authentication authentication)
    throws IOException, ServletException {

           request=(HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
           String userObject=request.getParameter("userConnecte");
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
           if (!(auth instanceof AnonymousAuthenticationToken)) {
                this.userDetails =  (UserDetails) auth.getPrincipal();
           }
           this.userConnecte = this.userBO.retournerUserByEmail(this.userDetails.getUsername());
           this.session= ActionContext.getContext().getSession();
           if(this.userObject!=null){
           session.put("userConnecte", userObject);
           return "login_successful";
           }else{
           logger.info(" userObject is null."+userObject);
           retrun "re_login_page";
            }
 }