programing

스프링 MVC에서 JSON payload를 @RequestParam에 POST하는 방법

newnotes 2023. 3. 21. 22:31
반응형

스프링 MVC에서 JSON payload를 @RequestParam에 POST하는 방법

Spring Boot(최신 버전, 1.3.6)사용하고 있는데, 다수의 인수와 JSON 개체를 받아들이는 REST 엔드포인트를 만들고 싶습니다.예를 들어 다음과 같습니다.

curl -X POST http://localhost:8080/endpoint \
-d arg1=hello \
-d arg2=world \
-d json='{"name":"john", "lastNane":"doe"}'

스프링 컨트롤러에서 현재 수행 중인 작업은 다음과 같습니다.

public SomeResponseObject endpoint(
@RequestParam(value="arg1", required=true) String arg1, 
@RequestParam(value="arg2", required=true) String arg2,
@RequestParam(value="json", required=true) Person person) {

  ...
}

json인수가 Person 객체로 일련화되지 않습니다.저는...

400 error: the parameter json is not present.

확실히, 나는 그 일을json컨트롤러 메서드 내의 payload를 String으로 해석합니다만, 그러한 종류의 payload는 Spring MVC를 사용하는 포인트에는 맞지 않습니다.

이 모든 것을 사용할 수중에@RequestBody하지만 JSON 본문 외부에 별도의 주장을 게시할 가능성은 없습니다.

Spring MVC에서 일반 POST 인수와 JSON 개체를 '혼합'하는 방법이 있습니까?

예, post 메서드를 사용하여 param과 body를 모두 전송할 수 있습니다.예: 서버 측:

@RequestMapping(value ="test", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Person updatePerson(@RequestParam("arg1") String arg1,
        @RequestParam("arg2") String arg2,
        @RequestBody Person input) throws IOException {
    System.out.println(arg1);
    System.out.println(arg2);
    input.setName("NewName");
    return input;
}

고객님의 고객:

curl -H "Content-Type:application/json; charset=utf-8"
     -X POST
     'http://localhost:8080/smartface/api/email/test?arg1=ffdfa&arg2=test2'
     -d '{"name":"me","lastName":"me last"}'

즐거운 시간 되세요.

이 작업을 수행하려면Converter부터String자동 배선을 사용하여 파라미터 타입으로 변경ObjectMapper:

import org.springframework.core.convert.converter.Converter;

@Component
public class PersonConverter implements Converter<String, Person> {

    private final ObjectMapper objectMapper;

    public PersonConverter (ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Person convert(String source) {
        try {
            return objectMapper.readValue(source, Person.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

RequestEntity를 사용할 수 있습니다.

public Person getPerson(RequestEntity<Person> requestEntity) {
    return requestEntity.getBody();
}

사용자:

 @Entity
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer userId;
    private String name;
    private String password;
    private String email;


    //getter, setter ...
}

JSON:

{"name":"Sam","email":"sam@gmail.com","password":"1234"}

@RequestBody 를 사용할 수 있습니다.

@PostMapping(path="/add")
public String addNewUser (@RequestBody User user) {
    User u = new User(user.getName(),user.getPassword(),user.getEmail());
    userRepository.save(u);
    return "User saved";
}

언급URL : https://stackoverflow.com/questions/38262055/how-to-post-a-json-payload-to-a-requestparam-in-spring-mvc

반응형