Spring 3일차

MOZZI KIM·2022년 12월 8일
0

Spring

목록 보기
3/8
post-thumbnail

1. 아래를 프로그래밍 하시오

http://localhost:8282/board/grade/{kor}/{eng}/{math}

grade.jsp 에 평균과 총점이 나오도록 하시오.
단) lombok 이 쓰고, command 객체로 처리 할것.

@GetMapping("/grade/{kor}/{math}/{eng}")
	public String grade(@PathVariable int kor, 
    					@PathVariable int math, 
                        @PathVariable int eng, Model model) {
		System.out.println("grade()...");
		
		Grade grade = new Grade();
		grade.setKor(kor);
		grade.setEng(eng);
		grade.setMath(math);
        
		return "grade";
	}
    
  -----------------------------------------------------------------------------
  package adu.global.ex.vo;

/*import lombok.AllArgsConstructor;*/
import lombok.Data;

@Data
public class Grade {
	private int kor;
	private int math;
	private int eng;
	
	public int total() {
		return kor + math + eng;
	}
	
	public double avg() {
		return kor+math+eng/3.0;
	}
}


<%@ page language="java" contentType="text/html; charset=EUC-KR"
  pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	국어 : ${kor}<br>
	수학 : ${math}<br>
	영어 : ${eng}<br>
	총점 : ${grade.total()} <br>
	평균 : ${grade.avg()}
</body>
</html>
  

2.FOREIGN KEY 와 PRIMARY KEY 에 대하여 설명하시오.



3.아래 @애너테이션에 대하여 설명하시오.

- @Controller
- @RequestMapping
- @GetMapping
- @PathVariable
- @RequestParam

📌 @Controller

Spring에게 해당 Class가 Controller의 역할을 한다고 명시하기 위해 사용하는 Annotation입니다.

@Controller                   // 이 Class는 Controller 역할을 합니다
@RequestMapping("/user")      // 이 Class는 /user로 들어오는 요청을 모두 처리합니다.
public class UserController {
    @RequestMapping(method = RequestMethod.GET)
    public String getUser(Model model) {
        //  GET method, /user 요청을 처리
    }
}

📌 @RequestMapping

@RequestMapping(value=”“)와 같은 형태로 작성하며, 요청 들어온 URI의 요청과 Annotation value 값이 일치하면 해당 클래스나 메소드가 실행됩니다. Controller 객체 안의 메서드와 클래스에 적용 가능하며, 아래와 같이 사용합니다.

Class 단위에 사용하면 하위 메소드에 모두 적용됩니다.
메소드에 적용되면 해당 메소드에서 지정한 방식으로 URI를 처리합니다.

@Controller                   // 이 Class는 Controller 역할을 합니다
@RequestMapping("/user")      // 이 Class는 /user로 들어오는 요청을 모두 처리합니다.
public class UserController {
    @RequestMapping(method = RequestMethod.GET)
    public String getUser(Model model) {
        //  GET method, /user 요청을 처리
    }
    @RequestMapping(method = RequestMethod.POST)
    public String addUser(Model model) {
        //  POST method, /user 요청을 처리
    }
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String addUser(Model model) {
        //  GET method, /user/info 요청을 처리
    }
}

📌 @RequestParam

URL에 전달되는 파라미터를 메소드의 인자와 매칭시켜, 파라미터를 받아서 처리할 수 있는 Annotation으로 아래와 같이 사용합니다. Json 형식의 Body를 MessageConverter를 통해 Java 객체로 변환시킵니다.

@Controller                   // 이 Class는 Controller 역할을 합니다
@RequestMapping("/user")      // 이 Class는 /user로 들어오는 요청을 모두 처리합니다.
public class UserController {
    @RequestMapping(method = RequestMethod.GET)
    public String getUser(@RequestParam String nickname, @RequestParam(name="old") String age {
        // GET method, /user 요청을 처리
        // https://naver.com?nickname=dog&old=10
        String sub = nickname + "_" + age;
        ...
    }
}

📌 @GetMapping

GET 요청 방식의 API를 만들때, @RequestMapping(method = RequestMethod.GET ...) 방식도 있지만, @GetMapping을 이용하는 방법도 있다.

@RestController
@RequestMapping("api")
public class GetController {

  ...

  // GET Method 통신
  // 경로는 api/getParam과 매핑됨
  @GetMapping("/getParam")
  public String getParameter() {
    return "Hello Spring";
  }

}

단순히 @GetMapping 을 사용하면 @RequestMapping(method = RequestMethod.GET ...) 과 동일한 효과를 볼 수 있다.

📌 @PathVariable 이란?

REST API에서 URI에 변수가 들어가는걸 실무에서 많이 볼 수 있다.
예를 들면, 아래 URI에서 1234와 4062464가 @PathVariable로 처리해줄 수 있는 부분이다.
http://localhost:8080/api/user/⭐1234
https://music.bugs.co.kr/album/⭐4062464

사용법
Controller에서 아래와 같이 작성하면 간단하게 사용 가능하다.

@GetMapping(PostMapping, PutMapping 등 다 상관없음){변수명}
메소드 정의에서 위에 쓴 변수명을 그대로 @PathVariable("변수명") 
(Optional) Parameter명은 아무거나 상관없음(아래에서 String name도 OK, String employName도 OK)

@RestController
public class MemberController { 
    // 기본
    @GetMapping("/member/{name}")
    public String findByName(@PathVariable("name") String name ) {
        return "Name: " + name;
    }
    
    // 여러 개
    @GetMapping("/member/{id}/{name}")
	public String findByNameAndId(@PathVariable("id") String id, 
    							  @PathVariable("name") String name) {
    	return "ID: " + id + ", name: " + name;
    }
    
}

4. Command 객체에 대하여 설명하시오.

profile
코린이

0개의 댓글