`

springMVC 前后台传值与接收值

 
阅读更多

 

@Controller
@RequestMapping("/user")
@SessionAttributes("loginUser")
public class UserController {

    @RequestMapping(value={"/","/hello"})
    public String hello(int id,Map<String,Object> map) {
        map.put("hellokey", "world"); 
        return "hello";  // hello.jsp页面取值 用 $("hellokey") 就可以取到值 world
    }

   @RequestMapping(value="/say")
    public String say(@RequestParam int id,Model model) {
         model.addAttribute("hello", "value");
        //使用Object的类型作为key,String-->string
        model.addAttribute("ok");
        return "hello";// hello.jsp页面取值 用 $("String") 就可以取到值 world
    }

    @RequestMapping("/req")
    public String req(HttpServletRequest req) {
        System.out.println(req.getParameter("username"));
        return "hello";
    }

    @RequestMapping({"/users","/"})
    public String list(Model model) {
        model.addAttribute("users",users);//map
        return "user/list";
    }

    @RequestMapping(value="/{username}/update",method=RequestMethod.POST)
    public String update(@PathVariable String username,@Valid User user,BindingResult br,Model model) {
        if(br.hasErrors()) {
            return "user/update";  // 会找到user文件夹下的update.jsp页面
        }
        users.put(username, user);
        return "redirect:/user/users";  //相当于跳转另外一个链接
    }

 

}

总结:@PathVariable 当 @RequestMapping(value="/{username}/update",method=RequestMethod.POST)

           时使用,rest风格

            

            @RequestParam  接收一个简单类型的参数 当@RequestMapping(value="/say")时使用,普通风格

         

             @Valid  接收一个对象类型的参数,例如@Valid User user    对应前台页面如下:

<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<sf:form method="post" modelAttribute="user">
UserName:<sf:input path="username"/><sf:errors path="username"/><br/>
Password:<sf:password path="password"/><sf:errors path="password"/><br/>
Nickname:<sf:input path="nickname"/><sf:errors path="nickname"/><br/>
Email: <sf:input path="email"/><sf:errors path="email"/><br/>
<input type="submit"/>
</sf:form>

</body>

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics