zoukankan      html  css  js  c++  java
  • SpringMVC(五):@RequestMapping下使用@RequestParam绑定请求参数值

    在处理方法入参使用@RequestParam可以把请求参数传递给请求方法,@RequestParam包含的属性值:

    --- value :参数名称

    --- required :是否必须,默认为true,表示请求参数中必须包含对应的参数,否则抛出异常。

    --- defaultValue:当请求参数缺少或者有请求参数但值为空时,值采用该设置值。

    示例:

    1)在HelloWord.java中添加testRequestParam方法:

    package com.dx.springlearn.handlers;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    @RequestMapping("class_requestmapping")
    public class HelloWord {
        private static String SUCCESS = "success";
    
        @RequestMapping("/testRequestParam")
        public String testRequestParam(@RequestParam(value = "username") String username,
                @RequestParam(value = "address") String address,
                @RequestParam(value = "age", required = false, defaultValue = "0") int age) {
            System.out.println("testRequestParam, username: " + username + ",address: " + address + ",age: " + age);
            return SUCCESS;
        }
    }

    2)在index.jsp中插入链接html:

        <a
            href="class_requestmapping/testRequestParam?username=abc&address=def&age=26">testRequestParam</a>
        <br>

    3)测试。

    当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def&age=26

    打印信息为:testRequestParam, username: abc,address: def,age: 26

    当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def&age=

    抛出异常:

    Jan 04, 2018 8:02:53 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleTypeMismatch
    警告: Failed to bind request element: org.springframework.beans.TypeMismatchException: 
    Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException:
    For input string: ""

    解决方案,把age定义类型修改为Integer

    当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def

    打印信息为:testRequestParam, username: abc,address: def,age: 0

    当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc

    抛出异常:

    HTTP Status 400 - Required String parameter 'address' is not present
  • 相关阅读:
    【题解】Red-Blue Graph Codeforces 1288F 上下界费用流
    【题解】The Magician HDU 6565 大模拟
    HAOI2018游记
    【题解】【THUSC 2016】成绩单 LOJ 2292 区间dp
    【题解】【雅礼集训 2017 Day5】远行 LOJ 6038 LCT
    【题解】Catering World Finals 2015 上下界费用流
    《无问西东...》
    为了世界的和平~一起上caioj~~~!
    新征程~起航!
    bzoj4240: 有趣的家庭菜园(树状数组+贪心思想)
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/8195592.html
Copyright © 2011-2022 走看看