SpringMVC @RequestBody请求参数在postman中的请求

SpringMVC @RequestBody请求参数在postman中的请求

代码

package com.toltech.springboot.controller;

import com.toltech.springboot.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by Wgs on 2017/9/3.
 */
@RestController
@RequestMapping("/")
public class HelloController {
    @PostMapping("hello")
    public String show(@RequestBody User user) {
        System.out.println(user);
      return "hello";
    }
}

PostMan

例子

响应格式

package com.spring_boot.dto;

/**
 * Created by wanggs on 2017/9/20.
 */
public class JSONResult {
    public static final String SUCCESS = "success";
    public static final String ERROR = "error";

    private String state;
    private String message;
    private Object data;
    public JSONResult(Object data) {
        this(SUCCESS,data);
    }

    public JSONResult(String message) {
        this(ERROR,message);
    }

    public JSONResult(String state, String message) {
        this.state = state;
        this.message = message;
    }

    public JSONResult(String state, Object data) {
        this.state = state;
        this.data = data;
    }

    // getXxx setXxx
}

```
#### 控制器
```
package com.spring_boot.controller;

import com.spring_boot.dto.JSONResult;
import com.spring_boot.param.UserParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by wanggs on 2017/9/20.
 */
@RestController
@RequestMapping("/")
public class ParamController {
    @PostMapping("/param")
    public JSONResult param(@RequestBody UserParam user){
        System.out.println(user);
        JSONResult x = getJsonResult(user);
        if (x != null) return x;
        return new JSONResult(JSONResult.SUCCESS,"success");
    }
    private JSONResult getJsonResult(@RequestBody UserParam user) {
        if(user == null){
            return new JSONResult(JSONResult.ERROR,"参数为空");
        }
        if(StringUtils.isBlank(user.getName())){
            return new JSONResult(JSONResult.ERROR,"用户名不能为空");
        }
      if(user.getAge() == null){
            return new JSONResult(JSONResult.ERROR,"年龄不能为空");
        }
        if(!user.getName().equals("tom")){
            return new JSONResult(JSONResult.ERROR,"用户名不存在");
        }
        if(!checked(user.getAge())){
            return new JSONResult(JSONResult.ERROR,"年龄不合法");
        }
        return null;
    }

    private boolean checked(Integer age) {
        return age > 0 ? true:false;
    }
}

```
### 测试
```
package test.com.toltech.service.impl;

import com.alibaba.fastjson.JSON;
import com.toltech.pojo.UserParam;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * Created by wanggs on 2017/9/18.
 */
public class UserServiceImplTest {
    private static Logger logger = LoggerFactory.getLogger(UserServiceImplTest.class);
    public static void main(String[] args) throws IOException {
        UserParam userParam = new UserParam(null,"toms");
        String json = JSON.toJSONString(userParam);
        System.out.println(json);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),json);
        Request request = new Request.Builder()
                .url("http://localhost/param")
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = new OkHttpClient().newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String resultJson = response.body().string();
        System.out.println(resultJson);
       Map<String,Object> map = JSON.parseObject(resultJson);
        String message = (String) map.get("message");
        String state = (String) map.get("state");
        System.out.println("state: "+state+"message: "+message);
      if(!state.equals("success")){
            logger.info("请求失败:{}",message);
        }else {
            logger.info("请求成功:{}",message);
        }
        response.close();
    }
    /**
     * {"name":"toms"}
     {"state":"error","message":"年龄不能为空","data":null}
     state: errormessage: 年龄不能为空
     */
}
```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容