redirectAttributes的用法以及相关配置

来源:互联网 发布:闹钟软件哪个好 编辑:程序博客网 时间:2024/05/23 11:46

概述:redirectAttributes是spring提供的新特性,具有页面重定向,能够向重定向的页面传递参数的功能。

应用场景:在表单提交后,可以使用此属性重定向到页面中,可以防止表单重复提交带来的不便。

下面就来为大家说说redirectAttributes的几个注意点,希望能够帮到大家:

      1.这是一个使用RedirectAttributes的实例

      //通过这个RedirectAttributes可以将message传递到页面中,这样就很方便优雅的解决了表单重复提交

public String shiroLogin(@RequestParam(value="username",required=false) String name,
@RequestParam(value="password", required=false) String password,
HttpSession session, RedirectAttributes attributes, Locale locale){
Subject currentUser = SecurityUtils.getSubject();

boolean flag = false;

if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(name, password);
            token.setRememberMe(true);
            try {
                currentUser.login(token);
                flag = true;
                
                //把用户的登陆信息放到 Session 域对象中.
                Object user = currentUser.getPrincipals().getPrimaryPrincipal();
                System.out.println("----->" + user);
                session.setAttribute("user", user);
            } catch (UnknownAccountException uae) {
           
            } catch (IncorrectCredentialsException ice) {
            
            } catch (LockedAccountException lae) {
            
            } catch (AuthenticationException ae) {
           
            }
            
            if(!flag){
            attributes.addFlashAttribute("message", messageSource.getMessage("error.user.login", 
    null, locale));
            return "redirect:/index";
            }
        }

return "home/success";
}

2.但是要特别注意的是,仅仅是这样简单的页面重定向是没用的,我们还需要在springmvc.xml中对要跳转的页面做映射(一定要注意,否则跳转是不成功的)

<mvc:view-controller path="/index" view-name="index"/>