zoukankan      html  css  js  c++  java
  • SpringMVC 模拟登陆

    新建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";
    	}
    }
    
  • 相关阅读:
    Leetcode: Increasing Triplet Subsequence
    Snapchat面经(师兄的)
    M面经prepare: Shuffle a deck
    M面经Prepare: Find integer Average of 2 integers.
    M面经Prepare: Positive-Negative partitioning preserving order
    M面经Prepare: Delete Words Starting With One Character
    Lintcode: Subtree
    Leetcode: Reconstruct Itinerary
    Groupon面经:Find paths in a binary tree summing to a target value
    一些小感悟(2014.04版)
  • 原文地址:https://www.cnblogs.com/Angelinas/p/5638155.html
Copyright © 2011-2022 走看看