정리노트

[스프링]MVC

망고고래 2024. 1. 18. 17:10

Ch05 컨트롤러

5.1 컨트롤러 개요

5.2 컨트롤러 정의

5.3 @RequestMapping을 이용한 요청 매핑 경로 설정

5.4 요청 처리 메서드와 모델 유형

 

 

5.1 컨트롤러 개요

5.1.1 컨트롤러

웹 브라우저에서 들어온 사용자 요청을 구현된 메서드에서 처리하고 그 결과를 뷰에 전달하는 스프링의 빈 객체

웹 요청을 전달받아 그 내용을 해석한 후 요청을 처리할 수 있는 메서드 호출

 

5.1.2 컨트롤러 구현 과정

(1) 컨트롤러 정의

@Controller

 

(2)요청 매핑 경로 설정

@RequestMapping(value="/books", method=RequestMethod.GET)

 

(3)요청 처리 메서드 구현

	public String requestMethod(Model model) {
		model.addAttribute("data", "Model 예제");
		model.addAttribute("data2", "웹 요청 URL: /home/exam05");
		return "webpage05";
	}

 

(4) 뷰[&모델] 반환

return "webpage05";

 

package com.springmvc.chap05;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
public class Example05Controller {

	@GetMapping("/exam05")
	public String requestMethod(Model model) {
		model.addAttribute("data", "Model 예제");
		model.addAttribute("data2", "웹 요청 URL: /home/exam05");
		return "webpage05";
	}
	
}

 

 

5.2 컨트롤러 정의

5.2.1 @Controller를 이용한 컨트롤러 정의

org.springframework.stereotype.Controller 임포트

 

5.2.2 <context:component-scan> 요소로 컨트롤러 등록

servlet-context.xml 파일에 입력

  <context:component-scan base-package="패키지명" />

해당 패키지 안의 @(컨트롤러 및 의존 관계에 있는 자바 클래스)을 빈 객체로 자동 등록한다.

 

<context:component-scan>을 사용하지 않으면 다음과 같이 수동으로 등록해야 한다.

<beans:bean class="com.springmvc.controller.HomeController"/>
   <beans:bean id="bookRepository Impl" class="com.springmvc.repository.BookRepositoryImpl"/>
   <beans:bean id="bookServiceImpl" class="com.springmvc.service.BookServiceImpl">
   			주입
   		<beans:property name="bookRepository" ref="bookRepositoryImpl"/>
   </beans:bean>   
   <beans:bean class="com.springmvc.controller.BookController">
   		<beans:property name="bookService" ref="bookServiceImpl"/>
   </beans:bean>

그리고 @Autowired도 인식되지 않기 때문에 프로퍼티의 Setter() 메서드도 모두 작성해야 한다.

    public void setBookRepository(BookRepository bookRepository){
		this.bookRepository = bookRepository;
	}

 

5.3 @RequestMapping을 이용한 요청 매핑 경로 설정

①클래스 수준: 클래스 위에 작성

②메서드 수준: 메서드 위에 작성

package com.springmvc.chap05;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
public class Example05Controller {

	@GetMapping("/exam05")
	public String requestMethod(Model model) {
		model.addAttribute("data", "Model 예제");
		model.addAttribute("data2", "웹 요청 URL: /home/exam05");
		return "webpage05";
	}
	
}

url에 '/home/exam05' 입력시 requestMethod()와 매핑됨

method=RequestMethod.GET 생략시 GET방식 적용

 

@Controller
@RequestMapping("/books")
public class BookController {
	@Autowired
	private BookService bookService;
	
	@RequestMapping
	public String requestBookList(Model model) {
		List<Book> list = bookService.getAllBookList();
		model.addAttribute("bookList", list);
		return "books";
	}

@RequestMapping 뒤에 주소가 없으면 클래스 수준에서 설정된 주소와 매핑됨

 

5.4 요청 처리 메서드와 모델 유형

응답 데이터를 저장하는 모델 유형

모델(&뷰) 클래스 설명
Model 데이터(또는 객체) 정보를 저장
ModelMap 데이터(또는 객체) 정보를 저장
ModelAndView 모델 정보 및 뷰 정보를 저장

 

(1)Model 인터페이스

package com.springmvc.chap05;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
public class Example05Controller {

	@GetMapping("/exam05")
	public String requestMethod(Model model) {
		model.addAttribute("data", "Model 예제");
		model.addAttribute("data2", "웹 요청 URL: /home/exam05");
		return "webpage05";
	}
	
}

 

(2)ModelMap 클래스

Model과 동일

 

(3)ModelAndView 클래스

package com.springmvc.chap05;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/home")
public class Example07Controller {
	
	@GetMapping("/exam07")
	public ModelAndView requestMethod(ModelMap model) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("data", "ModelAndView 예제");
		mav.addObject("data2", "웹 요청 URL: /home/exam07");
		mav.setViewName("webpage05");
		return mav;
	}
}

addAttribute()가 아니라 addObject이고,

바로 String값을 리턴하는 것이 아니라 ModelAndView 객체를 생성해두고 setViewName으로 값을 설정한 후 객체를 리턴한다.

 

 

 

Ch06 요청 처리 메서드의 파라미터 유형

6.1 경로 변수와 @PathVariable

6.2 매트릭스 변수와 @MatrixVariable

6.3 요청 파라미터와 @RequestParam

 

 

6.1 경로 변수와 @PathVariable

6.1.1 경로 변수의 개요

URL 파라미터 작성 방법

①/cars?color=red

②/cars/red

 

URL 예시: http://.../cars/red

@GetMapping("/cars/{color}")			//파라미터 color와 매치
public String requestMethod(@PathVariable String color, ...)
{
    ...
    return "cars";
}

 

 

 

6.1.2 @PathVariable을 이용한 경로 변수 처리

//경로 변수 이름 그대로 사용
@RequestMapping("경로 변수")
public String 메서드명(@PathVariable 경로 변수, ...){
	...
}

//경로 변수 이름 재정의
@RequestMapping("경로 변수")
public String 메서드명(@PathVariable(경로 변수) 매개변수, ...){
	...
}

 

 

예시

package com.springmvc.chap06;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
public class Example01Controller {

	@GetMapping("/exam01/{bookId}")
	public String requestmethod(@PathVariable String bookId, Model model) {
		System.out.println("도서 ID: "+bookId);
		model.addAttribute("data", "도서 Id: "+bookId);
		return "webpage06";
	}
}

'/exam01/' 뒤에 입력하는 부분이 bookId의 value로 들어가서 사용된다.

 

@PathVariable 복수 사용

package com.springmvc.chap06;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
public class Example02Controller {
	
	@GetMapping("/exam02/{category}/publisher/{publisher}")
	public String requestMethod(@PathVariable String category, @PathVariable String publisher, Model model) {
		System.out.println("도서 분야: "+category);
		System.out.println("출판사: "+publisher);
		model.addAttribute("data", "도서 분야: "+category+"<br>"+"출판사: "+publisher);
		return "webpage06";
	}
}

 

 

파라미터를 거치지 않고 @PathVariable로 바로 이동하기 때문에 인코딩을 위해서는 web.xml에 필터를 작성해야 한다.

	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 

 

 

6.2 매트릭스 변수와 @MatrixVariable

다중 파라미터 값을 전달받음

@RequestMapping의 경로 변수에 '매트릭스 변수 = 값' 형태

color=red, green, blue 또는 color=red;color=green;color=blue

 

package com.springmvc.chap06;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
public class Example03Controller {
	
	@GetMapping("/exam03/{bookId}")
	public String requestMethod(@PathVariable String bookId, @MatrixVariable String category, Model model) {
		System.out.println("도서 ID: "+bookId);
		System.out.println("도서 분야: "+category);
		model.addAttribute("data", "도서 ID: "+bookId+"<br>"+"도서 분야: "+category);
		
		return "webpage06";
	}
}

url: ..../home/exam03/ISBN1234;category=IT전문서

 

 

매트릭스 변수의 매핑: value, pathVar 속성 사용

package com.springmvc.chap06;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/home")
public class Example04Controller {

	@GetMapping("/exam04/{bookId}/category/{category}")
	public String requestMethod(@MatrixVariable(value="publisher", pathVar="bookId") String q1, @MatrixVariable(value="publisher", pathVar="category") String q2, Model model) {
		System.out.println("출판사1: "+q1);
		System.out.println("출판사2: "+q2);
		model.addAttribute("data", "출판사1: "+q1+"<br>"+"출판사2: "+q2);
		
		return "webpage06";
	}
}

url: ..../home/exam04/ISBN1234;publisher=길벗/category/IT전문서;publisher=이지톡

 

 

 

6.3 요청 파라미터와 @RequestParam

요청 URL이 http://.../cars?color=red일 경우

요청 파라미터 이름: color

값: red

@GetMapping("/cars")
public String requestMethod(@RequestParam String color, ...)
{
	...
    return "cars";
}

 

 

 

 

 

'정리노트' 카테고리의 다른 글

[스프링] 시큐리티  (0) 2024.01.22
[스프링] 폼 태그  (0) 2024.01.19
[Spring] MVC 실습①  (0) 2024.01.17
[스프링] 스프링 MVC 분석  (0) 2024.01.16
[스프링] 스프링 MVC  (0) 2024.01.15