新建BackgroundController类:
package cn.bdqn.mvc.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/background/") public class BackgroundController { @RequestMapping("home") public String home(){ return "background/home"; } }
package cn.bdqn.mvc.controller; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import cn.bdqn.mvc.form.LoginForm; @Controller @RequestMapping("/") public class LoginController { //方法的返回值返回一个对象 @ModelAttribute("form") public LoginForm getForm(){ return new LoginForm(); } //我发送请求要访问login.html页面 @RequestMapping(value="login",method=RequestMethod.GET) public String showLogin(){ return "login"; } //建议不用实体类接受请求,建议单独定义一个表单类 @RequestMapping(value="login",method=RequestMethod.POST) public String doLogin2( @Valid@ModelAttribute("form")LoginForm loginForm,//这样转发回表单页面的时候会自动回填数据 BindingResult result,//服务器端验证用 HttpSession session ){ //是否发生服务器端验证错误,hasErrors()是管所有的错误 if(result.hasErrors()){ return "login"; } if(!loginForm.getLoginName().equals("admin")){ result.rejectValue("loginName","form", "用户名输入错误"); //reject是驳回的意思 }else if (!loginForm.getPassword().equals("123456")) { result.rejectValue("password","form", "密码输入错误"); } //如果添加了错误信息,则转发回登陆表单页面 if(result.hasErrors()){ return "login"; } //将登陆成功的用户名存入session session.setAttribute("loginName", loginForm.getLoginName()); //重定向到后台首页 return "redirect:background/home.html"; } }