我正在用Struts2、Spring、Spring安全和Hibernate开发一个应用程序。
我需要使用会话,我尝试用以下代码定义会话:
Map session = ActionContext.getContext().getSession();//line 1
session.put("objet",objet);// line2但是它返回一个java.lang.NullPointerException (line1),您对这个问题有什么想法吗?
LoginAction.java
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);
}
}发布于 2014-05-26 14:26:19
当struts2筛选器启动操作时,可以使用操作上下文。该方法
onAuthenticationSuccess与struts2和操作上下文无关。使用servlet请求对象获取会话。
HttpSession session = request.getSession(false);发布于 2014-05-27 05:09:07
试试这个,初始化Servlet上下文,
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";
}
}https://stackoverflow.com/questions/23871707
复制相似问题