如何在spring mvc中管理会话?

时间:2015-06-10 05:45:43

标签: java spring session spring-mvc

我是春天的新人。有一个名为userController的控制器。在此控制器中,有一个名为signIn的方法。在此方法中,用户输入了正确的用户ID和密码,然后页面重定向到具有会话值的同一视图。然后用户可以查看他的个人资料详情为此,我在userController中创建了一个方法调用account。在这种方法中,我无法获得先前设置的会话值。我怎么能得到它?这是我实现的两种方法。 这是signIn方法

@RequestMapping(value = "/sign_in", method = RequestMethod.POST)
public String signIn(@RequestHeader(value = "Accept") String headerAccept,@ModelAttribute User requestParamUser,RedirectAttributes redirectAttrs,HttpSession session) {
    JSONObject obj = new JSONObject();
    try {
        // Check request parameters are null
        if ((requestParamUser.getUserId() == null)|| (requestParamUser.getPassword() == null)) {
            obj.put("loginError", CommonConfig.REQUEST_PARAMETERS_ARE_NULL);
            redirectAttrs.addFlashAttribute("state", obj);
            redirectAttrs.addFlashAttribute("user",requestParamUser);
            return "redirect:/";
        }

        User user = userDAO.findByUserIdAndPassword(requestParamUser.getUserId(),requestParamUser.getPassword());

        // Check provide userId and password is correct
        if (user == null) {
            obj.put("loginError", CommonConfig.USER_NOT_FOUND);
            redirectAttrs.addFlashAttribute("state", obj);
            redirectAttrs.addFlashAttribute("user",requestParamUser);
            return "redirect:/";
        }

        obj.put("loginSuccess", CommonConfig.LOGIN_SUCCESS);
        redirectAttrs.addFlashAttribute("state", obj);
        session.setAttribute("userId",user.getUserId());
        session.setAttribute("userName",user.getFirstName());
        return "redirect:/";

    } catch (Exception e) {
        System.out.println(CommonConfig.DB_ERROR + " : "+ e.getMessage().toString());
        obj.put("loginError", CommonConfig.DB_ERROR);
        redirectAttrs.addFlashAttribute("state", obj);
        redirectAttrs.addFlashAttribute("user",requestParamUser);
        return "redirect:/";
    }
}

这是account方法。

@RequestMapping(value="/ac")
    public String account(@RequestHeader(value = "Accept") String headerAccept,RedirectAttributes redirectAttrs, HttpServletRequest request){

        String userId = (String) request.getSession(false).getAttribute("userId");
        redirectAttrs.addFlashAttribute("abc",userId);
        return "account";   
    }

在这种方法中,我尝试将session测试为redirectAttrs。该值将显示在account视图中。问题在于这种方法。我无法使userId会话正确无误。

1 个答案:

答案 0 :(得分:2)

首先,您应该添加spring security libs,然后执行以下操作:

创建实现此UserDetailsS​​ervice的新类,如下所示:

public class UserDetailsS​​erviceImpl实现UserDetailsS​​ervice并实现loadUserByUsername

@Override
    public UserDetails loadUserByUsername(String userInfo)
            throws UsernameNotFoundException {
        // use userInfo to check user Info then return object from UserDetails class
    String[] tokens=userInfo.split("@0@");
    Collection<GrantedAuthority> authorities= new ArrayList<GrantedAuthority>();
    // here you pass the Role so you can use later in your application
    authorities.add(new SimpleGrantedAuthority ("ROLE_"+tokens[2]));
    UserDetails userDetails = new User(tokens[0],tokens[1], authorities);
    return userDetails;
}

现在在spring配置文件中添加这些行以定义身份验证管理器:

<bean id="daoAuthenticationProvider"
   class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <property name="userDetailsService" ref="userDetailsService"/>
 </bean>
   <bean id="userDetailsService" class="yourPackage.UserDetailsServiceImpl"/>

   <bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">

        <property name="providers">
            <list>
                <ref bean="daoAuthenticationProvider" />

            </list>
        </property>
    </bean>
    <bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder"/>

    <sec:authentication-manager >
        <sec:authentication-provider user-service-ref="userDetailsService">

        </sec:authentication-provider>
    </sec:authentication-manager>

在这里定义身份验证管理器,然后您可以在登录控制器中使用,如下所示:

Authentication authRequest = new UsernamePasswordAuthenticationToken(username+"@0@"+password+"@0@"+response.getOperatorInfo().getRole_name(), password);

                    Authentication result=null;
                    try {
                        result = authenticationManager.authenticate(authRequest);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    SecurityContextHolder.getContext().setAuthentication(result);

最后在其他Controller中你可以像这样使用userInfo:

SecurityContextHolder.getContext().getAuthentication().getName()