2012-11-09 80 views
3

我创建了一个简单的会话在Spring 3.1作用域bean。它应该给我方便地访问公司的当前登录用户。不保留在Spring会话bean数据

@Component 
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) 
public class SessionData { 

    private Company company; 

    public Company getCompany() { 
     return company; 
    } 

    public void setCompany(Company company) { 
     this.company = company; 
    } 
} 

我在我的自定义身份验证提供程序的authenticate()方法中使用公司填充此bean。

@Component(value = "authenticationProvider") 
public class ProduxAuthenticationProvider implements AuthenticationProvider { 

    private SessionData sessionData; 
    private CompanyService companyService; 

    @Autowired 
    public ProduxAuthenticationProvider(SessionData sessionData, CompanyService companyService) { 
     this.sessionData = sessionData; 
     this.companyService = companyService; 
    } 

    @Override 
    public Authentication authenticate(Authentication authentication) throws AuthenticationException { 

     // Authentication logic (token creation) removed for readability.... 

     Company company = companyService.findByUserProfile(profile); 

     // Set company on session bean 
     sessionData.setCompany(company); 

     return token; 
    } 
} 

然后我试图访问ManagementHomeController中的公司字段,它在验证成功完成后运行。

@Controller 
@RequestMapping(value = "/manage/home") 
public class ManagementHomeController { 

    private CourseService userService; 
    private CompanyService companyService; 
    private SessionData sessionData; 

    @Autowired 
    public ManagementHomeController(CourseService userService, CompanyService companyService, SessionData sessionData) { 
     this.userService = userService; 
     this.companyService = companyService; 
     this.sessionData = sessionData; 
    } 

    @RequestMapping(method = RequestMethod.GET) 
    public String get(Model model) { 
     model.addAttribute("mainContent", "content/managementHome"); 

     // sessionData.company is null here! Object id is same as in ProduxAuthenticationProvider 

     return "main"; 
    } 
} 

不知何故,在ManagementHomeController中SessionData的公司字段为空,但它是同一个对象。我可以看到,由于sessionData的对象ID是ProduxAuthenticationProvider和ManagementHomeController相同。

任何想法,为什么SessionData一路上失去它的公司?

+0

你能否证实谁调用ProduxAuthenticationProvider,它是通过任何机会的过滤器来注册RequestContextListener? –

+0

你好六必居,是的,它可能是一个弹簧过滤器。我在web.xml中声明了org.springframework.web.filter.DelegatingFilterProxy以使安全工作。 – Julius

回答

2

不完全确定这是否可行,但从我的理解,因为您正在将会话scoped bean注入到Spring调用程序servlet被调用之前调用的过滤器中,因此作用域代理正常工作需要某些请求属性没有被正确设置。

的修复将是这个逻辑移动到任何一个春天拦截或在web.xml

+0

那答案是启发我,谢谢! –