개발에 AtoZ까지

[Spring Boot] 전송방식에 따른 Parameter 받는 방법 본문

백엔드/Spring

[Spring Boot] 전송방식에 따른 Parameter 받는 방법

AtoZ 개발자 2021. 4. 30. 00:14
반응형

◆목표

동기식 방식일 때 parameter 받는 방법
비동기식 방식일 때 parameter 받는 방법

1. 동기식방식일때 parameter 받는 방법

     1) @RequestParam를 활용한 방식

         => @RequestParam과 일반 자료형을 활용해서 url에 입력된 Parameter 명과 매개변수의 변수명을 동일하게 하여 값을 받는 방법

 

<controller>

@Controller
@RequestMapping("/test/example")
public class TestController {

	@GetMapping("/test1")
	public void exam1(@RequestParam String name, @RequestParam String address, Model model) {
		model.addAttribute("name",name);		//URL에 있는 name 값
		model.addAttribute("address",address);	//URL에 있는 address 값
	}
}

<jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파라미터 받는 방법 Test</title>
</head>
<body>
	<h2 style="text-align:center;margin-top:100px;">name: ${name}</h2>
	<h2 style="text-align:center;margin-top:100px;">address: ${address}</h2>
</body>
</html>

<url 및 결과 화면>

  2) @RequestParam과 Map을 활용한 방식

         => @RequestParam과 Map을 활용해서 url에 입력된 Parameter를 일괄적으로 MAP 컬렉션이 담아서 받는 방법

 

<controller>

@Controller
@RequestMapping("/test/example")
public class TestController {

	@GetMapping("/test2")
	public void exam2(@RequestParam Map<String, Object> map, Model model) {
		model.addAttribute("map",map);		//URL에 있는 Parameter값들을 MAP 구조에 넣음
	}
}

<jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파라미터 받는 방법 Test</title>
</head>
<body>
	<h2 style="text-align:left;margin-top:100px;margin-left:50px;">name: ${map.name}</h2>
	<h2 style="text-align:left;margin-top:100px;margin-left:50px;">address: ${map.address}</h2>
</body>
</html>

<url 및 결과 화면>

3)  Class를 활용한 방식

         => Class을 활용해서 url에 입력된 Parameter를  Class 변수에 담는 방법

         => 단 해당 방식은 Class에 Getter와 Setter를 선언해주어야 정상 동작한다.

              (URL 파라미터를 받을 때는 getter, jsp에 출력할 때는 setter)

 

<controller>

@Controller
@RequestMapping("/test/example")
public class TestController {

	@GetMapping("/test3")
	public void exam3(TestVO testVO, Model model) {
    	//URL에 있는 Parameter값들을 class에 담기, 단 getter와 Setter가 있어야함
		model.addAttribute("testVO",testVO);		
	}
}

<jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파라미터 받는 방법 Test</title>
</head>
<body>
	<h2 style="text-align:left;margin-top:100px;margin-left:50px;">name: ${testVO.name}</h2>
	<h2 style="text-align:left;margin-top:100px;margin-left:50px;">address: ${testVO.address}</h2>
</body>
</html>

<url 및 결과 화면>

4)  PathValiable를 활용한 방식

         => url의 패턴을 정형화시켜서 parameter를 받는 방식

         => PathValiable은 해당 controller 실행 후 이동할 페이지를 Return 값으로 전달해줘야 한다.

              (ex, test/example/test4/홍길동/서울 이라는 페이지는 없기 때문이다.)

 

<controller>

@Controller
@RequestMapping("/test/example")
public class TestController {

	@GetMapping("/test4/{name}/{address}")
	public String exam4(@PathVariable String name, @PathVariable String address, Model model) {
		model.addAttribute("name",name);		
		model.addAttribute("address",address);
		return "test/example/test4";
	}
}

<jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파라미터 받는 방법 Test</title>
</head>
<body>
	<h2 style="text-align:left;margin-top:100px;margin-left:50px;">name: ${name}</h2>
	<h2 style="text-align:left;margin-top:100px;margin-left:50px;">address: ${address}</h2>
</body>
</html>

<url 및 결과 화면>

2. 비동기식방식일때 parameter 받는 방법

     1) MAP를 활용한 방식

         => @requestBody로 json 객체를 자바객체로 전달받고

         => @responseBody로 자바객체를 json객체로 변환

 

 

<controller>

@Controller
@RequestMapping("/test/example")
public class TestController {

	@GetMapping("/test6/form")
	public void form() {
	}

	/*
	 * 	web에서 받은 data는 java에서 사용 시 : web -> (javaObject로 변환 ) - > java에서 활용
		java에서 web으로 data 보낼 시  : java -> ( json Object로 변환) ->  web
	 */
	
	@PostMapping("/test6/saveData")
	@ResponseBody		//java 객체를 HTTP 요청의 body 내용으로 매핑하는 역할. VO 객체를 JSON으로 바꿔서 HTTP body에 담는 스프링 어노테이션
	public Map<String, Object> exam6(@RequestBody Map<String, Object> map, Model model) { //header에  실려서 오는 json 문자열을 읽기 위해 사용
		Map<String, Object> result = map;
		result.put("result", true);
		return result;
	}
}

<jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파라미터 받는 방법 Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
	let json = {
			name:'홍길동',
			age:14,
			address:'대한민국'
	}
	$.ajax({
		url:'/test/example/test6/saveData',
		type:'post',
		data:JSON.stringify(json), //json 문자열로 변환
		contentType:'application/json', // header에 json타입이라고 명시
		dataType:'json', //서버에서받을 데이터 형식을 json으로 지정
		success:function(data){
			console.log(data);
		}
		
	})
})


</script>

</body>
</html>

<url 및 결과 화면>

반응형
Comments