SpringBoot-Get

이호영·2022년 1월 29일
0

Spring

목록 보기
2/18

Get: 리소스 취득, read, PathVariable, queryparameter

package com.example.hello.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController //해당 class는 REST API를 처리하는 controller
@RequestMapping("/api")//RequestMapping URI를 지정해주는 Annotation
public class ApiController {
    @GetMapping("/hello") //http://localhost:8080/api/hello
    public String hello(){
        return "hello spring boot";
    }
}
package com.example.hello.controller;

import com.example.hello.DTO.UserRequest;
import org.springframework.boot.autoconfigure.quartz.QuartzTransactionManager;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/get")
public class GetApiController {
@GetMapping(path="hello")//http://localhost:8080/api/get/hello
    public String hello() {
        return "Get";
    } //실행 결과 Get출력

    @RequestMapping(path = "/hi", method = RequestMethod.GET)
    public String hi() {
        return "hi";
    } //구형 방식 method를 지정해 주지않으면 get/post/put 등 모두 실행 되어  method를 지정해줘야함

PathVariable: 변화하는값 즉 다른값들이 입력될수있도록 해줌

1.
//http://localhost:8080/api/get/path-variable/{name}
@GetMapping("path-variable/{name}")  //GetMapping {}와 PathVariable 이름이 같아야함
    public String pathVariable(@PathVariable String name) {
        System.out.println("PathVariable: " + name);
        return name;
    }
2.
@GetMapping("path-variable2/{name}")  //GetMapping {}와 이름을 동일하게 해줄수 없을때 사용
    public String pathvarialbe2(@PathVariable(name = "name") String pathname) {
        System.out.println("PathVariable :" + pathname);
        return pathname;
    }

queryparameter: 쿼리값을 받을때 사용하다.
예시로 설명하자면 초록창에 velog를 검색해보면 https://search.naver.com/search.naver?ie=UTF-8&sm=whl_hty&query=velog
?뒤에 ie=UTF-8&sm=whl_hty&query=velog 살펴보면 &(and연산)이 있는것을 볼수있다.
즉 key=value의 형태인것을 알수있다. 3가지 방법으로 사용가능 하다.

1.
//http://localhost:8080/api/get/query-param?user=steve&email=steve@gmail.com&age=25
    @GetMapping(path="query-param") //뭐가 들어올지 모를때 Map과 Ramda를 사용
    public String queryparam(@RequestParam Map<String, String> queryparam){
        StringBuilder sb= new StringBuilder();
        queryparam.entrySet().forEach(entry ->{
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
            System.out.println("\n");

            sb.append(entry.getKey()+"="+entry.getValue()+"\n");
        } );
        return sb.toString();
    }
2. 주의: 데이터 타입을 명시해주었기 때문에 명시된 데이터타입과 다른 값을 넣으면 오류발생
    @GetMapping("query-param02")
    public String queryparam02( //key가 몇개 되지 않을때
        @RequestParam String name, @RequestParam String email, @RequestParam int age)
    {
        System.out.println(name);
        System.out.println(email);
        System.out.println(age);

        return name+" "+email+" "+age;
    }
3. 현업에서 가장많이 사용한다. 객채를 받아 사용한다.(UserRequest) 즉 인스턴스를 추가하여 사용하기 용이하다.
@GetMapping("query-param03") 
    public String queryparam03(UserRequest userRequest) {

        System.out.println(userRequest.getName());
        System.out.println(userRequest.getEmail());
        System.out.println(userRequest.getAge());
        return userRequest.toString();
    }
}
package com.example.hello.DTO;
----------UserRequest----------------
public class UserRequest {

    private String name;
    private String email;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserRequest{" +
                "name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

0개의 댓글