spring mvc 传值一

前面完成了环境的搭建及controller与view的映射。接下来学习下spring mvc中值的传递。如何将值传递给controller。

1、创建一个controller,使用注解@RequestParam为创建的controller传递参数,例如:

//使用(@RequestParam("username")传递参数

@RequestMapping(value={"/","/welcom"})
 public String welcome(@RequestParam("username") String username){
  System.out.println("welcome");
  System.out.println("接收传入的参数username "+username);
  return "welcome";
 }

 2、发布项目,在地址栏中输入:http://localhost:8080/springmvc01/welcom?username=hello%20world



 

3、控制台输出如下内容:



 以上方式传值,操作起来非常的简单。但是:如果我们在地址栏中不传值,即输入:

http://localhost:8080/springmvc01/welcom,就会发生400的错误。如下图:



 那么,为什么会出现这种情况呢?(其实spring是支持目前比较流行的REST风格的框架的)当我们使用了@RequestParam时,spring就是认为参数是请求地址的一部分,所以会出现400的错误。

其实我们可以将@RequestParam去掉,Spring会自动使用username为我们做对应的处理。此时,不传值,就不会出现400的错误,而username的址为null。

猜你喜欢

转载自appleblue.iteye.com/blog/1852242