수업 문제(국비 지원)/JSP

[JSP] 2022.10.26 (삭제 부분 완료하기)

byeolsub 2023. 4. 29. 22:18

 📌 delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%-- /springmvc1/src/main/webapp/WEB-INF/view/item/delete.jsp --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상품 삭제 전 확인</title>
<%-- 상품 삭제 완성하기 --%>
</head>
<body>
	<h2>상품 삭제 전 확인</h2>
	<table>
		<tr><td><img src="../img/${item.pictureUrl}"></td></tr>
		<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><form sction="delete" method="post">
							**<input type="hidden" name="id" value="${param.id}">** 
							<input type="submit" value="상품삭제"> 
							<input type="button" value="상품목록" onclick="location.href='list'">
						</form></td></tr>
			</table></td>
	</table>
</body>
</html>

📌 ItemController.java 내용 추가

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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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;
	}
//http://localhost:8088/springmvc1/item/update?id=1
	/*
	 *  RequestMapping : get, post 방식이든 싱행
	 *  GetMapping : get 방식 호출 시 실행
	 *  PostMapping : post 방식 호출 시 실행
	 *  @GetMapping("update") : item/update 요청 정보가 get 방식 호출
	 */

	//{"update","delete"} : get 방식 요청중 update,delete 요청시 호출되는 메서드가 같음
	// update 요청 시 : update.jsp
	// delete 요청 시 : delete.jsp
	@GetMapping({"update","delete"})
	public ModelAndView updateForm(Integer id) {
		ModelAndView mav = new ModelAndView();
		//item : id에 해당하는 데이터를 db에서 읽어서 저장
		Item item = service.getItem(id);
		mav.addObject("item",item);
		return mav;
	}
	/*
	 * 1. 입력값 유효성 검증
	 * 2. db에 내용 수정. 파일 업로드.
	 * 3. update 완료시 list 재요청 하기
	 */
	
	@PostMapping("update")
	public ModelAndView update(@Valid Item item, BindingResult bresult, HttpServletRequest request) { 
	    ModelAndView mav = new ModelAndView();
	    if(bresult.hasErrors()) { //입력값에서 오류가 발생한 경우.
		mav.getModel().putAll(bresult.getModel()); //bresult.getModel() : item 객체를 그대로 전달
	    return mav;
        } 
	    service.itemUpdate(item,request);
	    mav.setViewName("redirect:list");
	    return mav;
	}

**//id에 해당하는 상품을 db에서 삭제**
	**@RequestMapping("delete")
	public ModelAndView delete (Integer id) {
		ModelAndView mav = new ModelAndView();
		service.itemDelete(id);**
		**mav.setViewName("redirect:list");**
		**return mav;**
	**}

/* 이렇게도 사용 가능하다!
	@RequestMapping("delete")
	public String delete (Integer id) { //뷰만 리턴(데이터는 보내지 않음.)
		service.itemDelete(id);
		return "redirect:list";
	}
*/**
}

📌 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();
		}
	}

	public void itemUpdate(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()); //파일의 이름을 db에 등록하기 위해 설정
		}
		itemDao.update(item);
	}

	**public void itemDelete(Integer id) {
		 itemDao.delete(id);
	}**
	
}

📌 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);
	}

	public void update(Item item) {
		//item 객체의 값을 프로퍼티를 이용하여 파라미터로 사용함.
		SqlParameterSource param = new BeanPropertySqlParameterSource(item); //지역변수
		String sql = "update item set name=:name, price=:price," 
		   + " description=:description, pictureUrl=:pictureUrl"
		   + " where id=:id";
		template.update(sql,param); //db에 수정
	}

	**public void delete(Integer id) {
		param.clear();
		param.put("id", id);
		template.update("delete from item where id=:id", param);
	}**
}

 

  • 삭제부분 완료하기