java getSession().setAttribute()

java getSession().setAttribute(),java,jakarta-ee,spring-security,Java,Jakarta Ee,Spring Security,我必须对现有的项目(tomcat和JavaWebApplication)稍作修改。 现在,在loginForm中,如果用户键入正确的登录名和密码,就可以了, 将在主页上显示给用户。但是当任何用户输入错误的密码时, 或者可能是他的帐户被暂时锁定,因此再次向用户显示loginform, 用户不知道为什么他不能登录,原因是什么,他不能登录。 (例如“无效用户名/密码”、“用户帐户已锁定”、…)。 现在我想插入会话错误消息,其中还包括用户无法登录的原因。 在会话中插入(保存)名为“LoggingErro

我必须对现有的项目(tomcat和JavaWebApplication)稍作修改。 现在,在loginForm中,如果用户键入正确的登录名和密码,就可以了, 将在主页上显示给用户。但是当任何用户输入错误的密码时, 或者可能是他的帐户被暂时锁定,因此再次向用户显示loginform, 用户不知道为什么他不能登录,原因是什么,他不能登录。 (例如“无效用户名/密码”、“用户帐户已锁定”、…)。 现在我想插入会话错误消息,其中还包括用户无法登录的原因。 在会话中插入(保存)名为“LoggingError”的属性。 我写的是:

request.getSession().setAttribute("LoggingError", message);
但在运行应用程序时,在这一行中

request.getSession().setAttribute("LoggingError", message);
网页中出现错误:

type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
    com.se.eee.security.EeeAuthenticationProvider.authenticate(EeeAuthenticationProvider.java:153)
    net.sf.acegisecurity.providers.ProviderManager.doAuthentication(ProviderManager.java:159)
    net.sf.acegisecurity.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:49)
    net.sf.ace
...
...
这里是EeeAuthenticationProvider.java的java代码

package com.se.eee.security;

import net.sf.acegisecurity.*;
import net.sf.acegisecurity.providers.AuthenticationProvider;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.providers.dao.User;
import net.sf.acegisecurity.providers.dao.UsernameNotFoundException;
import net.sf.acegisecurity.providers.dao.event.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import com.se.eee.bus.*;
import com.se.eee.bus.SecurityManager;
import com.se.spring.datasource.core.MakeConnectionException;
import com.se.spring.ext.CurrentRequestContext;
import com.opensymphony.webwork.interceptor.SessionAware;
import com.opensymphony.webwork.interceptor.ServletRequestAware;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class EeeAuthenticationProvider implements AuthenticationProvider, SessionAware, ServletRequestAware {
  private static Log log = LogFactory.getLog(EeeAuthenticationProvider.class);
  private JDBCProperties jdbcProp;
  private ApplicationContext context;
  private SecurityManager securityManager;
  private HttpServletRequest request;

  public void setServletRequest(HttpServletRequest req) {
          this.request = req;
  }
  public void setSession(Map session) {
        //To change body of implemented methods use File | Settings | File Templates.
  }

  public void setSecurityManager(SecurityManager securityManager) {
    this.securityManager = securityManager;
  }

  public void setApplicationContext(ApplicationContext applicationContext)
      throws BeansException {
    this.context = applicationContext;
  }

  public void setJdbcProp(JDBCProperties jdbcProp) {
        this.jdbcProp = jdbcProp;
  }

  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // Determine username
    // log.warn((authentication.isAuthenticated()?"Already Authenticated. Skip it!":"")+"authenticate: "+authentication);
  if(authentication.isAuthenticated()) {
      //log.warn("Already Authenticated. Skip it!");
    return authentication;
  }
  String username = "NONE_PROVIDED";

  if (authentication.getPrincipal() != null) {
    username = authentication.getPrincipal().toString();
  }

  if (authentication.getPrincipal() instanceof UserDetails) {
    username = ((UserDetails) authentication.getPrincipal()).getUsername();
  }

  UserDetails user = null;
  com.se.eee.bus.User principal=null;

  try
    {
      JDBCProperties props = jdbcProp.deserialize();
      String input_passwords= authentication.getCredentials().toString();
      String[] psd = input_passwords.split(":");
      Filial fil = props.getFilial(psd[1]);

      String sgn = input_passwords;
      int i= sgn.indexOf(":", 1);
      sgn = sgn.substring(i+1,sgn.length());
      i= sgn.indexOf(":", 1);
      sgn = sgn.substring(i+1,sgn.length());

      if(fil==null)username=null;
      securityManager.makeConnect(username, psd[0], fil);
      user=new User(username, "skipped",true,true,true,true, new  GrantedAuthority[]{new GrantedAuthorityImpl("ROLE_USER")});
      //set connection for DataSource
      ContextDataBean dataBean=(ContextDataBean)CurrentRequestContext.get();
      dataBean.setUserKey(username+fil.id);

      principal=securityManager.getUserByLogin(username.toUpperCase());
      if(principal == null) throw new UsernameNotFoundException("Couldn't login.");

      principal.setLogin(username);
      principal.setPassword("******");
      //principal.setBranch(fil.id);

      if (principal.getBanktype().equals("055"))
      {
        if ( sgn!=null && sgn.length() != 0)
        {
            securityManager.insUserKey(principal.getBranch(), principal.getId(), sgn);
            com.se.eee.bus.Document docum = new com.se.eee.bus.Document();
            docum.setBranch(principal.getBranch());
            docum.setEmpId(principal.getId());
            docum.setErrCode("991");
            docum = securityManager.getAnswerUserKey(docum);
            if (!docum.getErrCode().equals("000")) throw new UsernameNotFoundException("Key code error. User: "+principal.getLogin());
        }
        else
        {
            throw new UsernameNotFoundException("error while inserting test key code. please touch i-key or check loginform.ftl. user: "+principal.getLogin());
        }
      }
    }
  catch (MakeConnectionException mex)
    {
      log.error(mex.getMessage());
      if (this.context != null) {
        context.publishEvent(new AuthenticationFailureUsernameOrPasswordEvent(authentication, new User("".equals(username)? "EMPTY_STRING_PROVIDED" : username, "*****", false, false, false, false, new GrantedAuthority[0])));
      }
      throw new BadCredentialsException("Couldn't login connection problem.");
    }
  catch(Exception ex)
  {
    Throwable cause=ex.getCause();
    String message=null;
    if(cause!=null)message = cause.getMessage();
    else message = ex.toString();
    log.error(message);

// здес я пытаюс написать в session
 request.getSession().setAttribute("LoggingError", message);
// но код не компилируется

    throw new UsernameNotFoundException("Couldn't login.");
  }
  return createSuccessAuthentication(principal, authentication, user);

  }
  protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
      UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
      result.setDetails((authentication.getDetails() != null) ? authentication.getDetails() : null);
      result.setAuthenticated(true);
      return result;
  }

  public boolean supports(Class aClass) {
    if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass)) return true;
    return false;
  }
}

如果您的请求对象是HttpServletRequest对象,那么这应该可以工作

request.getSession(true).setAttribute("LoggingError", message); 
如果这不是问题,您可以发送准确的代码片段(不需要整个程序)和准确的错误消息吗?

这应该可以

request.getSession(true).setAttribute("LoggingError", message); 

您的身份验证提供程序是否指定为
prototype
scopebean?不确定Struts/WebWork是如何与Spring集成的,但是如果您的bean是单例的,它就不能工作

换句话说,确保调用了
setServletRequest


顺便说一句,如果这个应用程序有这样的包名,那么它一定很旧。

您到底有什么错误?我们需要更多详细信息来帮助您如果您可以发布尝试编译时遇到的错误,这将非常有帮助。除此之外,您通常使用此请求范围,而不是会话范围。我已编辑了消息,请在第行“更新输入”后阅读-1为了冒昧地在你的问题中添加
标签,我已经编辑了信息,请在第153行“更新输入”后阅读。@Hamza-你的问题中第153行是什么陈述?我知道它在authenticate方法中的某个地方,但不确定在哪里。如果它在catch块中,您可以执行堆栈跟踪以查看是什么导致了错误。看起来您还没有初始化某个变量,这就是引发空指针异常的原因,但我无法将其精简到确切的变量。我建议缩小抛出空指针的确切行,并确保您正在初始化所有内容。如果不起作用,请提供我上面要求的信息。原始呼叫不应返回
null
-