欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot接收参数from 表单,json等

程序员文章站 2022-04-29 17:20:12
...

1.新建项目

  1. 建立项目如下:

springboot接收参数from 表单,json等
2. pom 依赖如下

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

3.vo 中User 类

import lombok.Data;

@Data
public class User {
    private String username;
    private String id;
}

二:Controller接收form 表单

1.form 表单转对象,转map,与字符串方式接收

@Controller
@Slf4j
public class FormController {
    @RequestMapping("/formToObj")
    @ResponseBody
    /**
     * form 转java 类
     */
    public String formToObj(User user){

        log.info(JSON.toJSONString(user));
        return JSON.toJSONString(user);
    }
    @RequestMapping("/formToMap")
    @ResponseBody
    /**
     * form 转Map<String,String>
     */
    public String formToMap(@RequestParam Map<String,String> user){

        log.info(JSON.toJSONString(user));
        return JSON.toJSONString(user);
    }
    @RequestMapping("/formString")
    @ResponseBody
    /**
     * form 用String 接收
     * defaultValue 设置默认值
     */
    public String formString(@RequestParam(value = "username",defaultValue = "ambity") String username){

        log.info(username);
        return username;
    }
}

三 Controller 接收json

@RestController
@Slf4j
public class JsonController {
    @RequestMapping(value = "/jsonToObj" ,consumes={MediaType.APPLICATION_JSON_VALUE},produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    /**
     * form 转java 类
     */
    public String formToObj(@RequestBody User user){

        log.info(JSON.toJSONString(user));
        return JSON.toJSONString(user);
    }
    @RequestMapping("/jsonToMap")
    @ResponseBody
    /**
     * form 转java 类
     */
    public String jsonToMap(@RequestBody Map<String,String> user){

        log.info(JSON.toJSONString(user));
        return JSON.toJSONString(user);
    }
}