码迷,mamicode.com
首页 > 编程语言 > 详细

springMvc参数传递的方法

时间:2016-08-18 23:26:24      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

  1. package cn.edu.hj.controller;  
  2. import java.util.Map;  
  3. import javax.servlet.http.HttpServletRequest;  
  4. import org.springframework.stereotype.Controller;  
  5. import org.springframework.ui.Model;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestParam;  
  8.   
  9. @Controller  
  10. //@RequestMapping(value = "/hello")//表示要访问这个action的时候都要加上这个/hello路径  
  11. public class HelloController {  
  12.       
  13. /* 接收参数getParameter()的时候: 
  14.  * 如果地址栏/springmvc/hello.htm上面没有传递参数,那么当id为int型的时候会报错,当id为Integer的时候值为null 
  15.  * 当地址栏为/springmvc/hello.htm?id=10的时候,action中有三种接收方式 
  16.  * 1、String hello(@RequestParam(value = "userid") int id),这样会把地址栏参数名为userid的值赋给参数id,如果用地址栏上的参数名为id,则接收不到 
  17.  * 2、String hello(@RequestParam int id),这种情况下默认会把id作为参数名来进行接收赋值 
  18.  * 3、String hello(int id),这种情况下也会默认把id作为参数名来进行接收赋值 
  19.  * 注:如果参数前面加上@RequestParam注解,如果地址栏上面没有加上该注解的参数,例如:id,那么会报404错误,找不到该路径 
  20.  */  
  21.     @RequestMapping(value = "/hello.htm")  
  22.     public String hello(int id){//getParameter()的方式  
  23.         System.out.println("hello action:"+id);  
  24. //      return "hello";  
  25.         return "redirect:/index.jsp";//不能重定向web-info里面的文件,而且需要写上绝对路径  
  26.     }  
  27.       
  28.     //返回页面参数的第一种方式,在形参中放入一个map  
  29.     @RequestMapping(value = "/hello1.htm")  
  30.     public String hello(int id,Map<String,Object> map){  
  31.         System.out.println("hello1 action:"+id);  
  32.         map.put("name", "huangjie");  
  33.         return "hello";  
  34.     }  
  35.       
  36.     //返回页面参数的第二种方式,在形参中放入一个Model  
  37.     @RequestMapping(value = "/hello2.htm")  
  38.     public String hello2(int id,Model model){  
  39.         System.out.println("hello2 action:"+id);  
  40.         model.addAttribute("name", "huangjie");  
  41.         //这个只有值没有键的情况下,使用Object的类型作为key,String-->string  
  42.         model.addAttribute("ok");  
  43.         return "hello";  
  44.     }  
  45.   
  46.     //得到request,response,session等,只要在方法形参中声明参数即可  
  47.     @RequestMapping(value = "/hello3.htm")  
  48.     public String hello3(HttpServletRequest request){  
  49.         String id = request.getParameter("id");  
  50.         System.out.println("hello3 action:"+id);  
  51.         return "hello";  
  52.     }  

springMvc参数传递的方法

标签:

原文地址:http://www.cnblogs.com/zhaoxinshanwei/p/5785607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!