重定向传值

登录页面
* 重定向的时候向页面携带数据 要求如下
1.在目标controller方法使用RedirectAttributes类型的参数
2.要求不能直接重定向到页面,必须经过springmvc的映射

比如传错误信息
先在springmvc配置文件中配置一个解析器
<!--为了controller能携带数据 ,经过springmvc的映射 重定向到页面 -->
    <mvc:view-controller path="/login" view-name="login"></mvc:view-controller>

举例子 一个登陆页面controller层

参数中应用了 RedirectAttributes 参数 进行传值

//验证码 源码里面还存了一份在session域中, 用来和用户输入的验证码做对比 ,判断是否输入正确。 接收从页面传过来的值和用户名,密码
    //这个键 是工具类里面存到域中的那个键 ,根据这键取session域中的验证码值
    @RequestMapping(value = "/login", method = RequestMethod.POST)
public  String  login(Employee employee, String code, HttpSession session, RedirectAttributes attributes){
        String validateCode = (String)session.getAttribute("validateCode");
        session.removeAttribute("validateCode");
        if(!validateCode.equalsIgnoreCase(code)){
            attributes.addFlashAttribute("errorMsg","验证码错误");
            return "redirect:/login";
        }
        //如果验证码正确,验证用户名和密
        Employee emp = employeeService.login(employee);
        if(emp != null){
            session.setAttribute("loginUser",emp);
            return "redirect:/index.jsp";
        }else{
            attributes.addFlashAttribute("error","用户名或密码错误");
            return "redirect:/login";
        }
    }

然后是登录页面

<TABLE id=table2 cellSpacing=1 cellPadding=0 width="100%"
                                       border=0>
                                    <TBODY>
                                    <TR>
                                        <span style="color:red">${error}</span>
                                        <TD align=middle width=81><FONT color=#ffffff>用户名:</FONT></TD>
                                        <TD><INPUT class=regtxt title=请填写用户名 maxLength=16
                                                   size=16 value=username name=username></TD>
                                    </TR>
                                    <TR>
                                        <TD align=middle width=81><FONT color=#ffffff>密&nbsp;
                                            码:</FONT></TD>
                                        <TD><INPUT class=regtxt title=请填写密码 type=password
                                                   maxLength=16 size=16 name=password id=pass></TD>
                                    </TR>
                                    <TR>
                                        <TD align=middle width=81><FONT color=#ffffff >验证码:</FONT></TD>
                                        <TD><INPUT  title=请填写验证码 maxLength=50 size=12  name=code  value="${errorMsg}">
                                            <span><img id="validateCode" src="${pageContext.request.contextPath}/code/getCode?time="+(new Date().getTime()) ></span></TD>
                                    </TR>
                                    </TBODY>
                                </TABLE>


猜你喜欢

转载自www.cnblogs.com/ych961107/p/11978785.html
今日推荐