【问题标题】:java getSession().setAttribute() [duplicate]java getSession().setAttribute() [重复]
【发布时间】:2011-01-21 11:34:24
【问题描述】:

我必须对现有项目(tomcat 和 java WebApplication)进行一点更改。 现在,在 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;
  }
}

【问题讨论】:

  • 你到底有什么错误?我们需要更多详细信息来帮助您
  • 如果您可以发布您在尝试编译时遇到的错误,那将非常有帮助。
  • 除了这个问题,你通常使用请求范围,而不是会话范围。
  • 我已经编辑了消息,请在“新输入”行之后阅读
  • -1 冒昧地将<blink> 标签放在您的问题中

标签: java jakarta-ee spring-security


【解决方案1】:

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

如果这不是问题,您能否发送确切的代码 sn-p(不需要整个程序)和确切的错误消息?

【讨论】:

  • 我已经编辑了消息,请在“新输入”行之后阅读。
  • @Hamza - 你的问题的第 153 行有什么声明?我可以告诉它在身份验证方法中的某个地方,但不确定在哪里。如果它在 catch 块中,您可以进行堆栈跟踪以查看产生错误的原因。看起来您还没有初始化某个变量,这就是引发空指针异常的原因,但我无法将其修剪为确切的变量。我建议缩小抛出空指针的确切行,并确保您正在初始化所有内容。如果这不起作用,请提供我上面要求的信息。
【解决方案2】:

这应该可以。

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

【讨论】:

【解决方案3】:

您的身份验证提供程序是否指定为 prototype 范围 bean?不确定 Struts / WebWork 是如何与 Spring 完全集成的,但如果你的 bean 是 singleton,它就无法工作。

换句话说,确保调用了setServletRequest

顺便说一下,这个应用程序一定很老了,如果它有这样的包名的话。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多