티스토리 뷰
요청 처리 메서드와 모델 유형
Model 인터페이스를 이용한 메서드 작성
응답 데이터를 저장하는 모델 유형
모델(&뷰) 클래스(객체) | 설명 |
Model | 데이터(or 객체) 정보를 저장하는 데 사용합니다. |
ModelMap | 데이터(or 객체) 정보를 저장하는 데 사용합니다. |
ModelAndView | 모델 정보 및 뷰 정보를 저장하는 데 사용합니다. |
Example05Controller.java
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";
}
}
WEB-INF/views/webpage05.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>${data}
<p>${data2}
</body>
</html>
ModelMap 클래스를 이용한 메서드 작성
ModelAndView 클래스를 사용한 메서드 작성
Exmaple07Controller.java
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("webpage07");
return mav;
}
}
WEB-INF/views/webpage07.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>${data}
<p>${data2}
</body>
</html>
BookController.java (ModelAndView로 수정.)
package com.springmvc.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.domain.Book;
import com.springmvc.service.BookService;
@Controller
@RequestMapping("books") //추가
public class BookController {
//autowired 자동으로 변수에 대입을 해준다. 라고 생각
@Autowired
private BookService bookService;
//매핑에서 value값을 찾아서 반환해준다.
@GetMapping //수정
public String requestBookList(Model model)
{
List<Book> list = bookService.getAllBookList();
model.addAttribute("bookList", list);
return "books";
}
@GetMapping("/all") //수정
public ModelAndView requestAllBooks()
{
List<Book> list = bookService.getAllBookList();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("bookList", list);
modelAndView.setViewName("books");
return modelAndView;
}
}
요청 처리 메서드의 파라미터 유형
경로 변수와 @PathVariable
경로 변수
@PathVariable을 이용한 경로 변수 처리
Example01Controller.java
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 "wabpage071";
}
}
webpage071.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>${data}
</body>
</html>
Example02Controller.java
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 reqeustMethod(@PathVariable String category,
@PathVariable String publisher, Model model)
{
System.out.println("도서 분야 : "+ category);
System.out.println("출판사 : " + publisher);
model.addAttribute("data" , "도서 분야 : " + category + "<br>" + "출판사 : "+ publisher);
return "webpage06";
}
}
webpage06.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>${data }
</body>
</html>
도서 분야와 일치하는 도서 목록 출력하기.
BookRepository.java 추가. (interface)
package com.springmvc.repository;
import java.util.List;
import com.springmvc.domain.Book;
public interface BookRepository {
List<Book> getAllBookList();
List<Book> getBookListByCategory(String category);
}
BookRepositoryImpl.java 위에 추가한 것 구현
@Override
public List<Book> getBookListByCategory(String category) {
// TODO Auto-generated method stub
List<Book> booksByCategory = new ArrayList<Book>();
for(int i = 0; i< listOfBooks.size(); i++)
{
Book book = listOfBooks.get(i);
if(category.equalsIgnoreCase(book.getCategory()))
{
booksByCategory.add(book);
}
}
return booksByCategory;
}
BookService.java(interface) 추가.
package com.springmvc.service;
import java.util.List;
import com.springmvc.domain.Book;
public interface BookService {
List<Book> getAllBookList();
List<Book> getBookListByCategory(String category);
}
BookServiceImpl.java 위에 추가한 것 구현.
@Override
public List<Book> getBookListByCategory(String category) {
// TODO Auto-generated method stub
List<Book> booksByCategory = bookRepository.getBookListByCategory(category);
return booksByCategory;
}
BookController.java 에 @PathVariable 추가.
@GetMapping("/{category}")
public String requestBookByCategory(@PathVariable("category") String bookCategory, Model model)
{
List<Book> booksByCategory = bookService.getBookListByCategory(bookCategory);
model.addAttribute("bookList", booksByCategory);
return "books";
}
매트릭스 변수와 @MatrixVariable
매트릭스 변수
@MatrixVariable을 이용한 매트릭스 변수 처리
servlet-context.xml
annotation-driven 태그 내용 추가.
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven enable-matrix-variables="true"/>
Example04Controller.java
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.RequestMapping;
@Controller
@RequestMapping("/home")
public class Example04Controller {
@GetMapping("/exam04/{bookId}/category/{category}")
public String reqeustMethod(@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";
}
}
webpage06.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>${data}
</body>
</html>
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven enable-matrix-variables="true"/>
Set<Book> getBookListByFilter(Map<String, List<String>> filter);
@Override
public Set<Book> getBookListByFilter(Map<String, List<String>> filter) {
// TODO Auto-generated method stub
Set<Book> booksByPublisher = new HashSet<Book>();
Set<Book> booksByCategory = new HashSet<Book>();
Set<String> booksByFilter = filter.keySet();
if(booksByFilter.contains("publisher"))
{
for(int j = 0; j<filter.get("publisher").size(); j++)
{
String publisherName = filter.get("publisher").get(j);
for(int i = 0; i<listOfBooks.size(); i++)
{
Book book = listOfBooks.get(i);
if(publisherName.equalsIgnoreCase(book.getPublisher()))
{
booksByPublisher.add(book);
}
}
}
}
if(booksByFilter.contains("category"))
{
for(int i = 0; i<filter.get("category").size(); i++)
{
String category = filter.get("category").get(i);
List<Book> list = getBookListByCategory(category);
booksByCategory.addAll(list);
}
}
booksByCategory.retainAll(booksByPublisher);
return booksByCategory;
BookService.java [interface]
Set<Book> getBookListByFilter(Map<String, List<String>> filter);
BookServiceImple.java
public Set<Book> getBookListByFilter(Map<String, List<String>> filter) {
// TODO Auto-generated method stub
Set<Book> booksByFilter = bookRepository.getBookListByFilter(filter);
return booksByFilter;
}
BookController.java
@GetMapping("/filter/{bookFilter}")
public String requestBooksByFilter(@MatrixVariable(pathVar="bookFilter")
Map<String, List<String>> bookFilter, Model model)
{
Set<Book> booksByFilter = bookService.getBookListByFilter(bookFilter);
model.addAttribute("bookList", booksByFilter);
return "books";
}
요청 파라미터와 @RequestParam
요청 파라미터
@RequestParam을 이용한 요청 파라미터 처리
@RequestParam을 이용해 도서 ID와 일치하는 도서의 상세 정보 출력.
BookRepository.java
Book getBookById(String bookId);
BookRepositoryImpl.java
@Override
public Book getBookById(String bookId) {
// TODO Auto-generated method stub
Book bookInfo = null;
for(int i = 0; i<listOfBooks.size(); i++)
{
Book book = listOfBooks.get(i);
if(book != null && book.getBookId() != null && book.getBookId().equals(bookId))
{
bookInfo = book;
break;
}
}
if(bookInfo == null)
throw new IllegalArgumentException("도서 ID가 " + bookId + "인 해당 도서를 찾을 수 "
+ "없습니다.");
return bookInfo;
}
BookService.java
Book getBookById(String bookId);
BookServiceImple.java
@Override
public Book getBookById(String bookId) {
// TODO Auto-generated method stub
Book bookById = bookRepository.getBookById(bookId);
return bookById;
}
BookController.jsp
@GetMapping("/book")
public String requestBookById(@RequestParam("id") String booKId, Model model)
{
System.out.println("Book.jsp 도서 정보 도착");
Book bookById = bookService.getBookById(booKId);
model.addAttribute("book", bookById);
return "book";
}
Book.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/bootstrap.min.css"/>" rel="stylesheet">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<nav class="navbar navbar-expand navbar-dark bg-dark">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="./home">Home</a>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">도서 정보</h1>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12">
<h3>${book.name}</h3>
<p>${book.description}</p>
<br>
<p><b>도서코드 : </b><span class="badge badge-info">${book.bookId}</span>
<p><b>저자</b> : ${book.author}
<p><b>출판사</b> : ${book.publisher}
<p><b>출판일</b> : ${book.releaseDate}
<p><b>분류</b> : ${book.category}
<p><b>재고수</b> : ${book.unitsInStock}
<h4>${book.unitPrice}원</h4>
<br>
<p><a href="#" class="btn btn-primary">도서주문 »</a>
<a href="<c:url value="/books"/>" class="btn btn-secondary">도서 목록 »</a>
</div>
</div>
<hr>
<footer>
<p>© BookMarket</p>
</footer>
</div>
</body>
</html>
'정리 노트 > Spring' 카테고리의 다른 글
Spring Chapter8 [16-1] (0) | 2024.01.22 |
---|---|
Spring Chapter7 [15-5] (0) | 2024.01.19 |
Spring Chapter4~Chapter5 [15-3] (0) | 2024.01.17 |
Spring Chapter3 [15-2] (0) | 2024.01.16 |
Spring Chapter1~Chapter2 & 개발 환경 설정[15-1] (0) | 2024.01.15 |