Springmvc获取前端传递参数的方法---注解

1. @RequestParam

使用@RequestParam注解将【请求参数】(即查询参数或表单数据)绑定到控制器中的方法参数。

@Controller
@RequestMapping("/books")
public class EditBookForm {

    @GetMapping("/setbook")
    public String setupForm(@RequestParam("bookId") int bookId, Model model) { 
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "bookForm";
    }
}

默认情况下,使用此注解的方法参数 (如上例中的bookId) 是必需的,但我们可以通过将@RequestParam注解的【required标志设置】为 false来指定方法参数是可选的。

前端传入的参数全是都是String类型,目标方法如果接受参数的类型不是String,框架会自动转换为匹配的类型,不需要我们另外处理。

2.  @RequestHeader

使用@RequestHeader注解将请求的首部信息绑定到控制器中的方法参数中:

请求header如下:

Host localhost:8080 
Accept text/html,application/xhtml+xml,application/xml;q=0.9 
Accept-Language fr,en-gb;q=0.7,en;q=0.3 
Accept-Encoding gzip,deflate 
Accept-Charset ISO -8859-1,utf-8;q=0.7,*;q=0.7 
Keep-Alive 300

获取Accept-EncodingKeep-Alive标头的值:

@GetMapping("/demo")
public void handle(
        @RequestHeader("Accept-Encoding") String encoding, 
        @RequestHeader("Keep-Alive") long keepAlive) { 
    //...
}

3. @PathVariable

使用@PathVariable注解捕获的 URI 变量:

@GetMapping("/users/{userID}/books/{bookId}")
public User findPet(@PathVariable Long userID, @PathVariable Long bookId) {
    // ...
}

4. @CookieValue

使用@CookieValue注解将请求中的 cookie 的值绑定到控制器中的方法参数。

假设我们的请求中带有如下cookie:

JSESSIONID=997T4AC178CA32B49039CA727BADD8

获取 cookie 值:

@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) { 
    //...
}

5. @ModelAttribute

使用@ModelAttribute注解在方法参数上来访问【模型中的属性】,或者在不存在的情况下对其进行实例化。模型的属性会覆盖来自 HTTP Servlet 请求参数的值,其名称与字段名称匹配,这称为数据绑定.

@RequestMapping("/register")
public String register(@ModelAttribute("user") User user) {
    ...
}

@ModelAttribute 和 @RequestMapping 注解同时应用在方法上时,有以下作用:

  1. 方法的【返回值】会存入到 Model 对象中,key为 ModelAttribute 的 value 属性值。
  2. 方法的返回值不再是方法的访问路径,访问路径会变为 @RequestMapping 的 value 值,例如:@RequestMapping(value = "/index") 跳转的页面是 index.jsp 页面。
    @Controller
    public class ModelAttributeController {
        // @ModelAttribute和@RequestMapping同时放在方法上
        @RequestMapping(value = "/index")
        @ModelAttribute("name")
        public String model(@RequestParam(required = false) String name) {
            return name;
        }
    }

6. @RequestAttribute

使用@RequestAttribute注解来访问先前创建的存在与请求中的属性(例如,由 ServletFilter 或HandlerInterceptor)创建或在请求转发中添加的数据:

@GetMapping("/")
public String handle(@RequestAttribute Client client) { 
    // ...
}

7. @SessionAttributes

@SessionAttributes注解应用到Controller上面,可以将Model中的属性同步到session当中:

@Controller
@RequestMapping("/Demo.do")
@SessionAttributes(value={"attr1","attr2"})
public class Demo {
    
    @RequestMapping(params="method=index")
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView("index.jsp");
        mav.addObject("attr1", "attr1Value");
        mav.addObject("attr2", "attr2Value");
        return mav;
    }
    
    @RequestMapping(params="method=index2")
    public ModelAndView index2(@ModelAttribute("attr1")String attr1, @ModelAttribute("attr2")String attr2) {
        ModelAndView mav = new ModelAndView("success.jsp");
        return mav;
    }
}

注解使用的案例:

@RequestMapping("insertUser")
    public String insertUser(
            @RequestParam(value = "age",required = false) Integer age,
            @RequestHeader(value = "Content-Type",required = false) String contentType,
            @RequestHeader(required = false) String name,
            @CookieValue(value = "company",required = false) String company,
            @SessionAttribute(value = "username",required = false) String onlineUser,
            @RequestAttribute(required = false) Integer count,
            @ModelAttribute("date") Date date,
            @SessionAttribute(value = "date",required = false) Date sessionDate
    ) {
        System.out.println("sessionDate = " + sessionDate);
        System.out.println("date = " + date);
        System.out.println("count = " + count);
        System.out.println("onlineUser = " + onlineUser);
        System.out.println("age = " + age);
        System.out.println("contentType = " + contentType);
        System.out.println("name = " + name);
        System.out.println("company = " + company);
        return "user";
    }

5. 数组的传递

将方法的参数指定为数组:

@GetMapping("/array")
public String testArray(@RequestParam("array") String[] array) throws Exception {
    System.out.println(Arrays.toString(array));
    return "array";
}

发送如下请求,可以是多个名称相同的key,也可以是一个key,但是值以逗号分割的参数:

http://localhost:8080/app/hellomvc?array=1,2,3,4
http://localhost:8080/app/hellomvc?array=1&array=3

 

5. 复杂参数的传递 

 如下表单提交页面:

 

<form action="user/queryParam" method="post">
    排序字段:<br>
    <input type="text" name="sortField">
    <hr>
    数组:<br>
    <input type="text" name="ids[0]"> <br>
    <input type="text" name="ids[1]">
    <hr>
    user对象:<br>
    <input type="text" name="user.username" placeholder="姓名"><br>
    <input type="text" name="user.password" placeholder="密码">
    <hr>
    list集合<br>
    第一个元素:<br>
    <input type="text" name="userList[0].username" placeholder="姓名"><br>
    <input type="text" name="userList[0].password" placeholder="密码"><br>
    第二个元素: <br>
    <input type="text" name="userList[1].username" placeholder="姓名"><br>
    <input type="text" name="userList[1].password" placeholder="密码">
    <hr>
    map集合<br>
    第一个元素:<br>
    <input type="text" name="userMap['user1'].username" placeholder="姓名"><br>
    <input type="text" name="userMap['user1'].password" placeholder="密码"><br>
    第二个元素:<br>
    <input type="text" name="userMap['user2'].username" placeholder="姓名"><br>
    <input type="text" name="userMap['user2'].password" placeholder="密码"><br>
    <input type="submit" value="提交">
</form>

 需要搞一个实体类用来接收这个表单的参数:

@Data
public class QueryVo {
    private String sortField;
    private User user;
    private Long[] ids;
    private List<User> userList;
    private Map<String, User> userMap;
}

编写接口进行测试,我们发现表单的数据已经尽数传递了进来:

@PostMapping("queryParam")
public String queryParam(QueryVo queryVo) {
    System.out.println(queryVo);
    return "user";
}

结束! 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值