본문 바로가기

Spring

post, get 방식

GET 방식

@RestController
@RequestMapping("/api") //http://localhost:8888/api
public class GetController {    //rest 자원요청하면서 api역할
    //url호출할 수 있는 기능
    //http://localhost:8888/api/getmethod
    @RequestMapping(method = RequestMethod.GET, path="/getmethod")      //언옵테이션
    public String getMethod(){                                              //위아래 붙여서 실행해야함
        return "getMethod()호출!";
    }
//http://localhost:8888/api/getparameter1?userid=apple&userpw=1234  //userid userpw와 파람안 변수와 같아야함
//되돌려주고싶을때 사용하는 메소드
@RequestMapping(method = RequestMethod.GET,path="getparameter1")
public String getParameter1(@RequestParam String userid, @RequestParam String userpw){
    System.out.println("userid:" + userid);
    System.out.println("userpw:" + userpw);
    return "getParameter1()호출!";        //json -> javascript patch로
}
// http://localhost:8888/api/getparameter2?userid=apple&userpw=1234
@GetMapping("/getparameter2")               //위@RequestMapping(method = RequestMethod.GET,path="getparameter1")와 동일
public String getParameter2(@RequestParam String userid,@RequestParam(name="userpw") String password){
    System.out.println("userid:" + userid);
    System.out.println("userpw:" + password);
    return "getParameter2()호출!";
}
// http://localhost:8888/api/getmultiparameter2?userid=apple&userpw=1234&name=김사과&gender=여자&email=apple@apple.com&age=20
@GetMapping("/getmultiparameter2")
public Member getMultiParameter2(Member member){
    System.out.println(member);     //tostring 찍힘
    return member;          //json으로 리턴
	}
}

POST 방식

package com.koreait.day2.controller;

import com.koreait.day2.model.Member;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api") // http://localhost:8888/api
public class PostController {
    // http://localhost:8888/api/postmethod //get방식이라서 출력이 안됨
    // post방법으로 호출 x  post는 주소 나타나지 않음-> form 이용 or postman
    @RequestMapping(method = RequestMethod.POST,path = "/postmethod")
    public String postMethod(){
        return "postMethod() 호출!";

    }
    // http://localhost:8888/api/postparameter
    @RequestMapping(method = RequestMethod.POST, path = "/postparameter")
    public String postParameter(@RequestParam String userid, @RequestParam String userpw){
        System.out.println("userid: "+ userid);
        System.out.println("userpw: "+ userpw);
        return "postParameter() 호출!";
    }
    // http://localhost:8888/api/postmultiparameter
    @PostMapping("postmultiparameter")
    public Member postMultiParameter(@RequestBody Member member){   //200번 성공, 400번대 페이지를 찾을 수 없음, 500번 서버에러
        System.out.println(member); //tostring작동
        return member; //json이 나옴
        //content type 헤더에 써있는 정보값
        //객체로 보낼 때? --> spring 객체를 전달할 때 json으로감, post로 보낼때 json으로 받음
    }
}

'Spring' 카테고리의 다른 글

MyBatis  (0) 2023.03.25
Spring -03  (0) 2023.02.23
MVC 패턴  (0) 2023.02.23
Mapping  (0) 2023.01.09
Spring  (0) 2023.01.09