java getSession().setAttribute()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2342207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:42:07  来源:igfitidea点击:

java getSession().setAttribute()

javajakarta-eespring-security

提问by Hamza

I have to make a litle change to an existing project(tomcat and java WebApplication). now, in loginForm, if users type correct login and password, it is Ok, to users wil be shown main page. But when any user types incorrect password, or may be his account is temporarily locked, so to user again wil be shown loginform, user can not know why he cannot log in, by what cause he can not login. (for example "invalid username/password","user account locked",...). now i want to insert the session error message that includes also causes of why user cannot log in. insert(save) to session an attribute named "LoggingError". i am writing as:

我必须对现有项目(tomcat 和 java WebApplication)做一些改动。现在,在 loginForm 中,如果用户输入正确的登录名和密码,就可以了,用户将显示主页。但是当任何用户输入错误的密码,或者可能是他的帐户被临时锁定,所以再次向用户显示登录表单,用户无法知道为什么他无法登录,是什么原因导致他无法登录。(例如“无效的用户名/密码”、“用户帐户被锁定”等)。现在我想插入会话错误消息,其中还包括用户无法登录的原因。插入(保存)到会话名为“LoggingError”的属性。我写成:

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

but when running application, in this line

但是在运行应用程序时,在这一行

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

occurs error in web page:

网页出现错误:

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
...
...

here java code of EeeAuthenticationProvider.java

这里是 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;
  }
}

回答by SOA Nerd

If your request object is a HttpServletRequest object then this should work.

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

If this isn't the problem can you send the exact code snippet (shouldn't need the whole program) and the exact error message?

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

回答by Deepak Singhal

this should work.

这应该有效。

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

回答by Pavel Horal

Is your authentication provider specified as prototypescope bean? Not sure how Struts / WebWork is exactly integrated with Spring, but if your bean is singleton, it can not work.

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

In other words, make sure setServletRequestis called.

换句话说,确保setServletRequest被调用。

And by the way this application must be pretty old, if it has such package names as it has.

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