Spring MVC 传递值的方式

Spring MVC 作为控制层的框架,负责前后端传值的重要职责。

本文代码参:http://git.oschina.net/iridiumcao/iridiumonline/tree/master/hellospringmvc_trans_value

前端 -> 后端

页面提交一个 form,然后,Controller 就得到值了。

传递单个参数

form:

<form action="/hello/world/1" method="post">
    Value: <input type="text" name="hello"/>
    <input type="submit" value="Submit"/>
</form>

这里的的 method 用 get or post 都无所谓的。

controller method:

(在本文存放在 git 库中的实际代码中, RequestMapping 的 value 因为在 Controller 上已经有一部分了,就只剩下数字。)

@RequestMapping("/hello/world/1")
public String helloWorld1(String hello) {
     System.out.println(hello);
     return "hello";
}

注意这里的参数,名称是 hello,与页面 form 里的名称是对应的,可是,参数多了怎么办?理论上,可以依次列出,但是,太难看。

or

@RequestMapping("/hello/world/2")
public String helloWorld2(HttpServletRequest request){
    String result = request.getParameter("hello");
    System.out.println(result);
    return "hello";
}

这里用到了 HttpServletRequest, 好像很屌的样子。

访问地址:http://localhost:8080/hello/world/1 or http://localhost:8080/hello/world/2

随便输入个什么值,在后台就会打印出来。

传递多个参数

form:

<form action="/hello/world/3" method="post">
    Color: <input type="text" name="color"/><br/>
    weight: <input type="text" name="weight"/><br/>
    <input type="submit" value="Submit"/>
</form>

entity: 将表单内容封装成实体

public class Cup {
    private String color;
    private int weight;
    // getters and setters
}

controller:

@RequestMapping("/hello/world/3")
    public String helloworld3(Cup cup){
    System.out.println(cup.getColor());
    System.out.println(cup.getWeight());
    return "hello3";
}

没想到,这样还居然能找到!Spring MVC 的自动匹配功能太强大了!

如果不使用 Cup 封装类,还可以这么写 controller:

@RequestMapping("/hello/world/4")
public String helloworld3(String color, Integer weight){
    System.out.println(color);
    System.out.println(weight);
    return "hello3";
}

这里需要注意的是,数字类型的必须使封装类型,比如上面的参数 weight, 如果定义成 int weight,访问/hello/world/4就会报500错误。

URL: http://localhost:8080/hello/world/3

后端 -> 前端

普通方式

后台封装一个 model,传给前台用 el 表示就可以了。

controller:

@RequestMapping("/hello/world/5")
public ModelAndView helloworld5(){
    Cup cup = new Cup();
    cup.setColor("red");
    cup.setWeight(123);
    Map<String, Cup> cupMap = new HashMap();
    cupMap.put("c", cup);
    return new ModelAndView("hello5", cupMap);
}

这个 controller 还可以用下面两种方式替换:

@RequestMapping("/hello/world/6")
public ModelAndView helloworld6(Map cupMap){
Cup cup = new Cup();
cup.setColor("red");
cup.setWeight(123);
cupMap.put("c", cup);
return new ModelAndView("hello5", cupMap);
}

or

@RequestMapping("/hello/world/7")
public String helloworld7(Map cupMap){
Cup cup = new Cup();
cup.setColor("red");
cup.setWeight(123);
cupMap.put("c", cup);
return "hello5";
}

or

@RequestMapping("/hello/world/8") public String helloworld8(Model model){ Cup cup = new Cup(); cup.setColor("red"); cup.setWeight(123); model.addAttribute("c", cup); return "hello5"; }

page:

${c.color}, ${c.weight}

这里的 c 名称和前面 controller 中定义的一致。

URL: http://localhost:8080/hello/world/5

Ajax 方式

TODO