基本类型、包装类型的数据绑定以及坑

本文探讨了SpringMVC中基本类型与包装类型的参数绑定机制,包括int与Integer类型的处理差异,以及如何通过@RequestParam注解配置来避免常见的绑定错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基本类型、包装类型的数据绑定以及坑

例如,age

可以是基本类型:int、也可以是包装类型:Integer


情景一:age为int类型时

错误:参数不是int类型时,springmvc报错400



错误:不传参数,springmvc报错500












情景二:age为包装类型。例如Integer

当然我们实际开发过程中,也可以通过

@RequestParam()
@RequestParam()注解对是否进行配置



下面给出我的实例代码:

package com.wsq.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wsq on 2017/12/17下午9:31.
 * 本章主要介绍基本类型、包装类型的数据绑定以及坑
 */

@Controller
public class TestController {

    //TODO http://localhost:8080/baseType.do?xage=10
    @RequestMapping(value = "baseType.do", method = RequestMethod.GET)
    @ResponseBody
    public String baseType(@RequestParam("xage") int age){
        return "age: " + age;
    }



    //TODO http://localhost:8080/baseType2.do?age=10
    @RequestMapping(value = "baseType2.do", method = RequestMethod.GET)
    @ResponseBody
    public String baseType2(Integer age){
        return "age: " + age;
    }


    //TODO http://localhost:8080/array.do?name=Tom&name=Lucy&name=Jim
    @RequestMapping(value = "array.do", method = RequestMethod.GET)
    @ResponseBody
    public String baseType2(String[] name){
        StringBuilder sbf = new StringBuilder();
        for (String item : name) {
            sbf.append(item).append(" ");
        }
        return sbf.toString();
    }



}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值