수업(국비지원)/Spring

[Spring] (MVC 2) 상품 상세 보기(detail), 상품 등록(create)

byeolsub 2023. 4. 20. 23:53
  • 상품 상세 보기

 📌 detail.jsp 생성

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%-- /springmvc1/src/main/webapp/WEB-INF/view/item/detail.jsp --%>  
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 상세보기</title>
</head>
<body>
<h2>상품 상세 보기</h2>
<table>
<tr><td><img src="../img/${item.pictureUrl}"></td>
<td><table>
<tr><td>상품명</td><td>${item.name}</td></tr>
<tr><td>가격</td><td>${item.price}</td></tr>
<tr><td>상품설명</td><td>${item.description}</td></tr>
<tr><td colspan="2">
<form action="../cart/cartAdd">
<input type="hidden" name="id" value="${item.id}">
<table><tr><td><select name="quantity">
<c:forEach begin="1" end="10" var="i"><option>${i}</option></c:forEach>
</select></td>
<td><input type="submit" value="장바구니">
<input type="button" value="상품목록" onclick="location.href='list'">
</td></tr></table>
</form></td></tr>
</table></td></tr>
</table>
</body>
</html>

 

 

📌 itemController.java 내용 추가

package controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import logic.Item;
import logic.ShopService;

/*
 * @Controller : 객체화 대상이 되는 클래스
 *    - Controller 기능 : url의 요청시 호출되는 클래스 
 */

@Controller //@Component(객체를 만들어주는) + Controller 기능
@RequestMapping("item") // <http://localhost:8088/springmvc1/item> 호출이 들어오면 실행
public class ItemController {
	@Autowired //ShopService 객체를 주입.
	private ShopService service;
	
//http://localhost:8088/springmvc1/item/list 요청시 호출되는 메서드
	@RequestMapping("list")
	public ModelAndView list() {
		//1. ModelAndView : 데이터값 + 뷰 정보를 저장하고 있는 객체
		ModelAndView mav = new ModelAndView();
		//itemList : db의 item 테이블의 모든 데이터를 Item 객체들로 저장하고 있는 객체
		List<Item> itemList = service.itemList();
		mav.addObject("itemList",itemList); //데이터 저장.
		//뷰의 이름은 기본적으로 요청 url의 정보로 설정된다 : "item/list" 설정
		return mav;
	}
	//http://localhost:8088/springmvc1/item/detail?id=1
	@RequestMapping("detail")
	public ModelAndView detail(Integer id) {
		//request.getParameter("id") = id 매개변수명 == 파라미터 이름
		ModelAndView mav = new ModelAndView();
		Item item = service.getItem(id);
		mav.addObject("item",item);
		return mav;
	}
}

 

 

📌 ShopService.java 내용 추가

package logic;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dao.ItemDao;

/*
 *  @Component : 해당 클래스를 객체화
 *     - Service 기능 : Controller 와 Model사이의 중간 역할의 클래스
 */

@Service //@Component + Service 기능
public class ShopService {
	@Autowired //현재 내 컨테이너(객체)들 중에 itemDao 객체를 주입.
	private ItemDao itemDao;

	public List<Item> itemList() { 
		return itemDao.list();
	}

	public Item getItem(Integer id) {
		return itemDao.getItem(id);
	}
}

 

 

📌 ItemDao.java 내용 추가

package dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import logic.Item;

/*
 *  @Component : 해당 클래스를 객체화
 *   - model 기능 : db와 연결된 클래스
 */

@Repository //@Component(객체를 만들어주는) + model 기능
public class ItemDao {
	private NamedParameterJdbcTemplate template;
	private Map<String,Object> param = new HashMap<>();
	private RowMapper<Item> mapper = new BeanPropertyRowMapper<>(Item.class);
	
	@Autowired // 현재 컨테이너(객체)중 DataSource 객체를 주입.
	//DataSource : 데이터 베이스에 연결되어져 있는 객체.(...DriverManagerDataSource 객체 주입) 
	public void setDataSource(DataSource dataSource) {
		template = new NamedParameterJdbcTemplate(dataSource);
	}

	public List<Item> list() { 
		//mapper : db의 컬럼명과 mapper에 지정된 Item 클래스의 프로퍼티를 비교하여 Item 클래스에 객체로 저장
		return template.query("select * from item order by id", param, mapper);
	}

	public Item getItem(Integer id) {
		param.clear();
		param.put("id", id);
		return template.queryForObject("select * from item where id=:id", param, mapper);
	}
}

 


  • 상품 등록

 📌 create.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="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>    
<%-- /springmvc1/src/main/webapp/WEB-INF/view/item/create.jsp 
   1. 유효성 검증
   2. 파일 업로드
--%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 등록</title>
</head>
<body><form:form modelAttribute="item" action="register" enctype="multipart/form-data">
<h2>상품 등록</h2>
<table>
<tr><td>상품명</td>
<td><form:input path="name" maxlength="20"/></td>
<td><font color="red"><form:errors path="name"/></font></td></tr>
<tr><td>상품가격</td>
<td><form:input path="price" maxlength="20"/></td>
<td><font color="red"><form:errors path="price"/></font></td></tr>
<tr><td>상품이미지</td>
<td colspan="2"><input type="file" name="picture"></td></tr>
<tr><td>상품설명</td>
<td><form:textarea path="description" cols="20" rows="5"/></td>
<td><font color="red"><form:errors path="description"/></font></td>
</tr>
<tr><td colspan="3"><input type="submit" value="상품등록">&nbsp;
<input type="button" value="상품목록" onclick="location.href='list'">
</td></tr>
</table></form:form>
</body>
</html>

  • 상품 등록 - 유효성 검증

📌 ItemController.java 내용 추가

package controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import logic.Item;
import logic.ShopService;

/*
 * @Controller : 객체화 대상이 되는 클래스
 *    - Controller 기능 : url의 요청시 호출되는 클래스 
 */

@Controller //@Component(객체를 만들어주는) + Controller 기능
@RequestMapping("item") // <http://localhost:8088/springmvc1/item> 호출이 들어오면 실행
public class ItemController {
	@Autowired //ShopService 객체를 주입.
	private ShopService service;
	
//http://localhost:8088/springmvc1/item/list 요청시 호출되는 메서드
	@RequestMapping("list")
	public ModelAndView list() {
		//1. ModelAndView : 데이터값 + 뷰 정보를 저장하고 있는 객체
		ModelAndView mav = new ModelAndView();
		//itemList : db의 item 테이블의 모든 데이터를 Item 객체들로 저장하고 있는 객체
		List<Item> itemList = service.itemList();
		mav.addObject("itemList",itemList); //데이터 저장.
		//뷰의 이름은 기본적으로 요청 url의 정보로 설정된다 : "item/list" 설정
		return mav;
	}
	//http://localhost:8088/springmvc1/item/detail?id=1
	@RequestMapping("detail")
	public ModelAndView detail(Integer id) {
		//request.getParameter("id") = id 매개변수명 == 파라미터 이름
		ModelAndView mav = new ModelAndView();
		Item item = service.getItem(id);
		mav.addObject("item",item);
		return mav;
	}
	@RequestMapping("create")
	public ModelAndView create() {
		ModelAndView mav = new ModelAndView();
		mav.addObject(new Item());
		return mav;
	}
@RequestMapping("register")
/*
	     @Valid : 유효성 검사.(입력값 검증)
	      item : item 객체의 프로퍼티와 요청파라미터의 이름이 같은 것을 item 객체에 저장.
	             입력된 파라미터의 값들을 저장하고 있는 객체.
	 */
	public ModelAndView register(@Valid Item item, BindingResult bresult,HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("item/create");
		if(bresult.hasErrors()) {
			mav.getModel().putAll(bresult.getModel());
		return mav;
	}
		mav.setViewName("redirect:list");
		return mav;
	}
}

 

 

📌 springmvc1.pom.xml 내용 추가

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>kr.kic</groupId>
  <artifactId>springmvc1</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springmvc1 Maven Webapp</name>
  <url>http://maven.apache.org</url>

<!--spring 버전 설정 -->
  <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <spring.version>4.3.30.RELEASE</spring.version>
     <spring.version1>5.2.19.RELEASE</spring.version1>
  </properties>

<!-- maven의 기본 원격 저장소 : https://mvnrepository.com/ -->
<!-- maven 환경에서 사용되는 원격 저장소 추가로 설정 -->
  <repositories>
     <repository>
       <id>oracle</id>
       <name>ORACLE JDBC Repository</name>
       <url>http://maven.jahia.org/maven2</url>
     </repository>
  </repositories>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- 웹 환경을 만들수 있도록 하는 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- db 연결 해주는  -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- 오라클 관련 설정 -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc5</artifactId>
    <version>11.2.0.2.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<!-- 유효성 검사 설정 -->
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

<dependency>    
<groupId>org.hibernate</groupId>    
<artifactId>hibernate-validator</artifactId>    
<version>6.1.0.Final</version>
</dependency>

  </dependencies>
  <build>
    <finalName>springmvc1</finalName>
<!-- pom.xml의 첫번째 줄에 plugin 관련 오류 발생 시 추가 -->
<plugins>
  <plugin>
   <artifactId>maven-war-plugin</artifactId>
   <version>3.2.2</version>
  </plugin>
</plugins>
  </build>
</project>

 

 

📌 Item.java 내용 추가

package logic;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;

import org.springframework.web.multipart.MultipartFile;

public class Item {
	private int id;
	@NotEmpty(message="상품명을 입력하세요.")
	private String name;
	@Min(value=10,message="10원 이상 가능합니다.")
	@Max(value=100000,message="10만원 이하만 가능합니다.")
	private int price;
	@NotEmpty(message="상품설명을 입력하세요.")
	private String description;
	private String pictureUrl;
  //name=picture 태그기 선택한 파일의 내용 저장
	//<input type="file" name="picture">
	private MultipartFile picture;
	
	//setter.getter, toString
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getPictureUrl() {
		return pictureUrl;
	}
	public void setPictureUrl(String pictureUrl) {
		this.pictureUrl = pictureUrl;
	}
	public MultipartFile getPicture() {
		return picture;
	}
	public void setPicture(MultipartFile picture) {
		this.picture = picture;
	}
	
	@Override
	public String toString() {
		return "item [id=" + id + ", name=" + name + ", price=" + price + ", description=" + description
				+ ", pictureUrl=" + pictureUrl + ", picture=" + picture + "]";
	}
}

 


  • 상품 등록 - 파일 업로드

📌 springmvc1.pom.xml 내용 추가

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>kr.kic</groupId>
  <artifactId>springmvc1</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springmvc1 Maven Webapp</name>
  <url>http://maven.apache.org</url>

<!--spring 버전 설정 -->
  <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <spring.version>4.3.30.RELEASE</spring.version>
     <spring.version1>5.2.19.RELEASE</spring.version1>
  </properties>

<!-- maven의 기본 원격 저장소 : https://mvnrepository.com/ -->
<!-- maven 환경에서 사용되는 원격 저장소 추가로 설정 -->
  <repositories>
     <repository>
       <id>oracle</id>
       <name>ORACLE JDBC Repository</name>
       <url>http://maven.jahia.org/maven2</url>
     </repository>
  </repositories>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- 웹 환경을 만들수 있도록 하는 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- db 연결 해주는  -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- 오라클 관련 설정 -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc5</artifactId>
    <version>11.2.0.2.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<!-- 유효성 검사 설정 -->
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.0.Final</version>
</dependency>

<!-- 파일 업로드 설정 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>    
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>    
<dependency>
    <groupId>commons-digester</groupId>
    <artifactId>commons-digester</artifactId>
    <version>2.1</version>
</dependency>

  </dependencies>
  <build>
    <finalName>springmvc1</finalName>
<!-- pom.xml의 첫번째 줄에 plugin 관련 오류 발생 시 추가 -->
<plugins>
  <plugin>
   <artifactId>maven-war-plugin</artifactId>
   <version>3.2.2</version>
  </plugin>
</plugins>
  </build>
</project>

 

 

📌 spring-mvc.xml 내용 추가

<?xml version="1.0" encoding="UTF-8" ?>
<!-- /src/main/resources/spring-mvc.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:websocket="http://www.springframework.org/schema/websocket"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- css,js,html 웹에서 제공되는 파일의 기본 기능 제외  -->
<mvc:default-servlet-handler /> 

<!-- controller,logic,dao 패키지를 먼저 scan해서 @Component 를 가진 클래스의 객체 생성 -->
<context:component-scan base-package="controller,logic,dao" />

<!-- web 환경에서 객체 주입을 위한 설정 : @Autowired,@Controller... 기능 사용  -->
<mvc:annotation-driven />

<!-- "viewResolver" 뷰결정자 : jsp 페이지의 위치 지정  -->
<bean id="viewResolver"
     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass">
     <value>org.springframework.web.servlet.view.JstlView</value>
  </property>
  
<!-- item/list : WEB-INF/view/item/list.jsp : 뷰 지정 -->
  <property name="prefix"><value>/WEB-INF/view/</value></property>
  <property name="suffix"><value>.jsp</value></property>
</bean>   

<!-- 파일 업로드 설정  
   요청시 enctype="multipart/form-data" 형식인 경우 작동.
   
   p:maxUploadSize="104854600" : 100M 최대 업로드 가능한 크기 설정.
   p:maxInMemorySize="10485460" : 10M까지는 메모리에 파일의 내용을 저장.  
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
 p:maxUploadSize="104854600" p:maxInMemorySize="10485460"></bean>

<!-- 예외처리 -->
<bean id="exceptionHandler" 
     class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  <property name="exceptionMappings">
    <value></value>
  </property>
</bean>
</beans>

 

 

📌 web.xml 내용 추가

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>springmvc1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
<!-- spring 설정 -->  
  <servlet>
    <servlet-name>shop</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring-mvc.xml
      classpath:spring-db.xml
    </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>shop</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>
<!-- filter : servlet 프로그램 이전에 구동 -->
<filter>
   <filter-name>CharacterEncoding</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>CharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>

 

 

📌 ItemController.java 내용 추가

@Valid : 유효성 검사.(입력값 검증)
   - item : item 객체의 프로퍼티와 요청파라미터의 이름이 같은 것을 item 객체에 저장.
            입력된 파라미터의 값들을 저장하고 있는 객체.
   - bresult : item 객체에 유효성 검증의 결과 저장 객체.
package controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import logic.Item;
import logic.ShopService;

/*
 * @Controller : 객체화 대상이 되는 클래스
 *    - Controller 기능 : url의 요청시 호출되는 클래스 
 */

@Controller //@Component(객체를 만들어주는) + Controller 기능
@RequestMapping("item") // <http://localhost:8088/springmvc1/item> 호출이 들어오면 실행
public class ItemController {
	@Autowired //ShopService 객체를 주입.
	private ShopService service;
	
//http://localhost:8088/springmvc1/item/list 요청시 호출되는 메서드
	@RequestMapping("list")
	public ModelAndView list() {
		//1. ModelAndView : 데이터값 + 뷰 정보를 저장하고 있는 객체
		ModelAndView mav = new ModelAndView();
		//itemList : db의 item 테이블의 모든 데이터를 Item 객체들로 저장하고 있는 객체
		List<Item> itemList = service.itemList();
		mav.addObject("itemList",itemList); //데이터 저장.
		//뷰의 이름은 기본적으로 요청 url의 정보로 설정된다 : "item/list" 설정
		return mav;
	}
	//http://localhost:8088/springmvc1/item/detail?id=1
	@RequestMapping("detail")
	public ModelAndView detail(Integer id) {
		//request.getParameter("id") = id 매개변수명 == 파라미터 이름
		ModelAndView mav = new ModelAndView();
		//item :  id에 해당하는 db의 레코드 정보를 한개 저장하는 객체
		Item item = service.getItem(id);
		mav.addObject("item",item);
		return mav;
	}
	//http://localhost:8088/springmvc1/item/create
	@RequestMapping("create")
	public ModelAndView create() {
		ModelAndView mav = new ModelAndView();
		mav.addObject(new Item());
		return mav;
	}
	/*
       @Valid : 유효성 검사.(입력값 검증)
        - item : item 객체의 프로퍼티와 요청파라미터의 이름이 같은 것을 item 객체에 저장.
                 입력된 파라미터의 값들을 저장하고 있는 객체.
        - bresult : item 객체에 유효성 검증의 결과 저장 객체.
     -        
    */
	@RequestMapping("register")
	public ModelAndView register(@Valid Item item, BindingResult bresult,HttpServletRequest request) {
		//"item/create" : 뷰의 이름을 설정.
		ModelAndView mav = new ModelAndView("item/create");
		if(bresult.hasErrors()) { //유효성 검증에 오류가 있는지 ?
			mav.getModel().putAll(bresult.getModel()); //bresult.getModel() : item 객체를 그대로 전달
		return mav;
	} 
    //item : 요청 파라미터, 업로드된 파일의 내용 저장 객체
		//request : 요청 객체. (위치를 가져 오고자)
		service.itemCreate(item,request);
		mav.setViewName("redirect:list");
		return mav;
	}
}

 

 

 

📌 ShopService.java 내용 추가

package logic;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import dao.ItemDao;

/*
 *  @Component : 해당 클래스를 객체화
 *     - Service 기능 : Controller 와 Model사이의 중간 역할의 클래스
 */

@Service //@Component + Service 기능
public class ShopService {
	@Autowired //현재 내 컨테이너(객체)들 중에 itemDao 객체를 주입.
	private ItemDao itemDao;

	public List<Item> itemList() { 
		return itemDao.list();
	}

	public Item getItem(Integer id) {
		return itemDao.getItem(id);
	}
  //db에 내용 저장. 파일 업로드.
  //item : 저장 정보. 입력된 파라미터 값 + 업로드 된 파일의 내용	
	public void itemCreate(@Valid Item item, HttpServletRequest request) {
		//item.getPicture() : 업로드 된 파일의 내용
		if(item.getPicture() != null && !item.getPicture().isEmpty()) { //업로드 된 파일이 있는 경우
			String uploadPath = request.getServletContext().getRealPath("/") + "img/"; //업로드 위치
			uploadFileCreate(item.getPicture(), uploadPath); //업로드 구현 완료
			item.setPictureUrl(item.getPicture().getOriginalFilename()); //파일의 이름
		}
    //maxid : item테이블 중 최대 id 값
		int maxid = itemDao.maxId(); 
		item.setId(maxid+1);
		itemDao.insert(item);
	}

	private void uploadFileCreate(MultipartFile file, String uploadPath) {
		//uploadPath : 파일이 업로드 되는 폴더
		String orgFile = file.getOriginalFilename(); //업로드 된 파일의 이름
		File fpath = new File(uploadPath);
		if(!fpath.exists()) fpath.mkdirs(); //업로드 폴더를 생성(없으면)
		try { 
			//파일의 내용 => uploadPath + orgFile 로 파일 저장
			file.transferTo(new File(uploadPath + orgFile)); //파일업로드
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

 

📌 ItemDao.java 내용 추가

package dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import logic.Item;

/*
 *  @Component : 해당 클래스를 객체화
 *   - model 기능 : db와 연결된 클래스
 */

@Repository //@Component(객체를 만들어주는) + model 기능
public class ItemDao {
	private NamedParameterJdbcTemplate template;
	private Map<String,Object> param = new HashMap<>();
	private RowMapper<Item> mapper = new BeanPropertyRowMapper<>(Item.class);
	
	@Autowired // 현재 컨테이너(객체)중 DataSource 객체를 주입.
	//DataSource : 데이터 베이스에 연결되어져 있는 객체.(...DriverManagerDataSource 객체 주입) 
	public void setDataSource(DataSource dataSource) {
		//spring-jdbc 모듈
		template = new NamedParameterJdbcTemplate(dataSource);
	}

	public List<Item> list() { 
		//mapper : db의 컬럼명과 mapper에 지정된 Item 클래스의 프로퍼티를 비교하여 Item 클래스에 객체로 저장
		//query() : select 구문의 결과가 여러개의 레코드 가능
		return template.query("select * from item order by id", param, mapper); 
	}

	public Item getItem(Integer id) {
		param.clear();
		param.put("id", id);
		//queryForObject() : select 구문의 결과가 한개만 가능. 결과가 여러개인 경우는 오류 발생
		return template.queryForObject("select * from item where id=:id", param, mapper); 
	}

	//item 테이블의 id 값 중 최대값 리턴
	public int maxId() {
		//Integer.class : 리턴값의 자료형 설정
		return template.queryForObject("select nvl(max(id),0) from item", param, Integer.class);
	}
	
	//db에 등록 해주는 
	public void insert(@Valid Item item) {	
		//BeanPropertySqlParameterSource(item) : item 객체의 get프로퍼티를 이용해서 파라미터로 사용
		SqlParameterSource param = new BeanPropertySqlParameterSource(item); //지역변수
		//:id : item.getId() 메서드 호출
		//:name : item.getName() 메서드 호출
    String sql = "insert into item" + " (id, name, price, description, pictureUrl)"
		     + " values (:id, :name, :price, :description, :pictureUrl)";
		template.update(sql,param);
	}
}