본문 바로가기
카테고리 없음

Java & SpringBoot로 시작하는 웹 프로그래밍 : 자바 인강 [7주차]

by 소윤:) 2022. 8. 2.
반응형
Spring Boot

Spring 1.0 는 자바 엔터프라이즈 어플리케이션 개발의 최고의 자리를 유지

스프링 프레임워크의 구성은 20여가지로 구성되어 있으며 필요한 모듈만 선택하여 사용 가능

스프링에서는 일반적인 Java객체를 new로 생성하여 개발자가 관리하는 것이 아닌 Spring Container에 모두 맡김(제어의 역전)

 

  • Spring Boot Annotations
Annotation 의미
@SpringBootApplication Spring boot application 으로 설정
@Controller View를 제공하는 controller로 설정
@RestController REST API를 제공하는 controller로 설정
@RequestController URL 주소를 맵핑
@GetMapping Http GetMathod URL 주소 맵핑
@PostMapping Http PostMathod URL 주소 맵핑
@PutMapping Http PutMathod URL 주소 맵핑
@DeleteMapping Http DeleteMathod URL 주소 맵핑
@RequestParam URL Query Parameter 맵핑
@RequestBody Http Body를 Parsing 맵핑
@Valid POJO Java class의 검증
@Configration 1개 이상의 bean을 등록할 때 설정
@Component 1개의 Class 단위로 등록할 때 사용
@Bean 1개의 외부 library로부터 생성한 객채를 등록시 사용
@Autowired DI를 위한 곳에 사용
@Qualifier @Autowired 사용시 bean이 2개 이상일 때 명시적 사용
@Resource @Autowired + @Qualifier 의 개념으로 이해
@Aspect AOP 적용시 사용
@Before AOP 메소드 이전 호출 지정
@After AOP 메소드 호출 이후 지정 예외 발생 포함
@Around AOP 이전/이후 모두 포함 예외 발생 포함
@AfterReturning AOP 메소드의 호출이 정상일 때 실행
@AfterThrowing AOP시 해당 메소드가 예외 발생시 지정

 

  •  Spring Boot Exception 처리
@ControllerAdvice Global 예외 처리 및 특정 package/Controller 예외처리
@ExceptionHandler 특정 Controller의 예외처리

 

  • POST API 실습
package com.example.post.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

public class PostRequestDto {
    private String account;
    private String email;
    private String address;
    private String password;
    @JsonProperty("phone_number")
    private String phoneNumber;
    @JsonProperty("OTP")
    private String OTP;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getEmail() {
        return email;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumver(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    @Override
    public String toString() {
        return "PostRequestDto{" +
                "account='" + account + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                ", password='" + password + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", OTP='" + OTP + '\'' +
                '}';
    }
}
package com.example.post.controller;

import com.example.post.dto.PostRequestDto;
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 java.util.Map;

@RestController
@RequestMapping("/api")
public class PostApiController {
    @PostMapping("/post")
    public void post(@RequestBody PostRequestDto requestData){
            System.out.println(requestData);
    }
}

<Talend API Test>

  • PUT API 실습
package com.example.put;

import com.example.put.dto.PostRequestDto;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class PutApiController {
    @PutMapping("/put/{userId}")
    public PostRequestDto put(@RequestBody PostRequestDto requestDto, @PathVariable Long userId){
        System.out.println(userId);
        return requestDto;
    }
}
package com.example.put;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PutApplication {

    public static void main(String[] args) {
        SpringApplication.run(PutApplication.class, args);
    }
}
package com.example.put.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

public class CarDto {
    private String name;
    @JsonProperty("car_number")
    private String carNumber;

    public String getName() {
        return name;
    }

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

    public String getCarNumber() {
        return carNumber;
    }

    public void setCarNumber(String carNumber) {
        this.carNumber = carNumber;
    }

    @Override
    public String toString() {
        return "CarDto{" +
                "name='" + name + '\'' +
                ", carNumber='" + carNumber + '\'' +
                '}';
    }
}

 

<Talend API Test>

  • DELETE API 실습
package com.example.delete.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class DeleteApiController {
    @DeleteMapping("/delete/{userId}")
    public void delete(@PathVariable String userId, @RequestParam String account){
        System.out.println(userId);
        System.out.println(account);
    }
}
package com.example.delete;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DeleteApplication {

    public static void main(String[] args) {
        SpringApplication.run(DeleteApplication.class, args);
    }
}

 

  • Response API 실습
package com.example.response;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ResponseApplication {

    public static void main(String[] args) {
        SpringApplication.run(ResponseApplication.class, args);
    }
}
package com.example.response.controller;

import com.example.response.dto.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ApiController {
    //TEXT
    @GetMapping("/text")
    public String text(@RequestParam String account){
        return account;
    }
    //JSON
    @PostMapping("/json")
    public User json(@RequestBody User user){
        return user;
    }
    //ResponseEntity
    @PutMapping("/put")
    public ResponseEntity<User> put(@RequestBody User user){
       return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }
}
package com.example.response.controller;

import com.example.response.dto.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PageController {
    @RequestMapping("/main")
    public String main(){
        return "main.html";
    }

    //ResponseEntity
    @ResponseBody
    @GetMapping("/user")
    public User user(){
        var user=new User();
        user.setName("steve");
        user.setAddress("pastcampus");
        return user;
    }
}

 

  • 모범사례 - Object Mapping
package com.example.objectmapper;

import com.fasterxml.jackson.annotation.JsonProperty;

public class User {
    private String name;
    private int age;

    @JsonProperty("phone_number")
    private String phonenumber;

    public User(){
        this.name=null;
        this.age=0;
        this.phonenumber=null;
    }
    public User(String name, int age, String phonenumber){
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getPhonenumber() {
        return phonenumber;
    }

    public User defaultUser(){
        return new User("default", 0, "010-1111-2222");
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", phonenumber='" + phonenumber + '\'' +
                '}';
    }
}
package com.example.objectmapper;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ObjectMapperApplication {

    public static void main(String[] args) {
        SpringApplication.run(ObjectMapperApplication.class, args);
    }
}
package com.example.objectmapper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class ObjectMapperApplicationTests {

    @Test
    void contextLoads() throws JsonProcessingException {
        System.out.println("-------------------");

        //Text JSON -> Object
        //Object -> Text JSON

        //Controller req json(text) -> object
        //response object -> json(text)

        var objectMapper = new ObjectMapper();

        //object -> text
        var user = new User("steve", 10,"010-1111-2222");
        var text = objectMapper.writeValueAsString(user);
        System.out.println(text);

        //text -> object
        var objectUser=objectMapper.readValue(text, User.class);
        System.out.println(objectUser);
    }
}

<Talend API Test>

 

반응형