0930 Spring CRUD

onnbi·2022년 11월 28일
0

web

목록 보기
7/8
post-thumbnail

spring CRUD

pom.xml 추가 라이브러리

https://mvnrepository.com/ : 메이븐 라이브러리 저장소

  1. Lombok (자동으로 기본 생성자, 전체 초기화 생성자를 만든다)
  2. ojdbc6 (db연결)
  3. Commons Database Connection Pooling (쿼리 조회후 반환)
  4. spring JDBC 5.0.6

spring JDBC사용 위해 2가지 라이브러리 필요 (3, 4번)

servlet-context.xml 객체 생성

  1. dataSource
  2. JDBCTemlate
<!-- DB 접속 정보를 저장하는 객체 생성 -->
<!-- 라이브러리로 땡겨오는 객체에는 annotation 불가 -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
  <beans:property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe"/>
  <beans:property name="username" value="spring"/>
  <beans:property name="password" value="1234"/>	
</beans:bean>

<!-- JDBC Template -->
<beans:bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>

web.xml 인코딩 필터 설정

<!-- 인코딩 필터 설정 -->
	<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>*.do</url-pattern>
	</filter-mapping>

MVC 작성

Controller

한 패키지에 여러 servlet이 생겼던 servlet project와 다르게 spring은 한 컨트롤러에 method를 추가하여 요청을 관리한다

@Controller : 컨트롤러로 지정할 class로 연결할 수 있도록 annotation 추가

@RequestMapping : 메서드와 주소를 연결, 값을 처리할 페이지로 이동하는 String 전달

@Autowired : 스프링이 만든 객체 중 선언된 변수와 일치하는 타입을 찾아서 값을 대입

@Controller
public class BoardController {
	
	@Autowired
	private BoardService service;
  
	@RequestMapping(value="/boardList.do")
	public String boardList(int reqPage, Model model) {
		HashMap<String, Object> pageMap = service.selectBoardList(reqPage);
		model.addAttribute("list", (ArrayList<Board>)pageMap.get("list"));
		model.addAttribute("pageNavi", (String)pageMap.get("pageNavi"));
		model.addAttribute("reqPage", (Integer)pageMap.get("reqPage"));
		model.addAttribute("numPerPage", (Integer)pageMap.get("numPerPage"));
		return "board/boardList";
	}
}
    // redirect : 정해진 이동값을 따르지 않고 작성한 곳으로 보낸다

service

@Service

@Service
public class BoardService {
	@Autowired
	private BoardDao dao;
  
	public int insertBoard(Board b) {
		// board에 인서트가 되지 않으면 file 테이블에서 references를 받을 수 없음
		int result = dao.insertBoard(b);
		System.out.println("dao 수행 후 : "+b.getBoardNo());
		if(result>0) {
			// insert가 성공한 경우 파일 insert
			// 파일이 없는 경우 insert 필요 없음
			if(!b.getFileList().isEmpty()) {
				// 가장 최근에 들어간 boardNo 조회
				int boardNo = dao.selectBoardNo();
				for(FileVO fv : b.getFileList()) {
                  // 방금 insert한 board_no를 참조하기 위해 set
					fv.setBoardNo(boardNo);
					result += dao.insertFile(fv);
				}
			}
		}
		return result;
	}
}
	

dao

@repository

@Repository
public class BoardDao {
	@Autowired
	private SqlSessionTemplate sqlSession;

	public ArrayList<Board> selectBoardList(HashMap<String, Object> map) {
		List list = sqlSession.selectList("board.selectBoardList", map);
		return (ArrayList<Board>)list;
	}
}

첨부파일

pom.xml 추가 라이브러리

파일업로드에 필요한 commons-io / commons-fileupload 라이브러리 추가

		<!-- commons-fileupload -->
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.3.3</version>
		</dependency>

		<!-- commons-io -->
		<dependency>
    		<groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.4</version>
		</dependency>

servlet-context

서버 시작할 때 객체 생성하도록 multipartResolver 생성

<!-- 파일업로드용 객체 생성 (외부라이브러리라서 context불가) -->
	<beans:bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<beans:property name="maxUploadSize" value="10485760"/>
	</beans:bean>

파일명 중복체크 클래스 생성

package common;

import java.io.File;

import org.springframework.stereotype.Component;

@Component
public class FileRename {

	public String fileRename(String path, String filename) {
		// 파일 중복이름 체크 메서드
		// 최종적으로 사용할 파일 path를 돌려주는 클래스
		// 첫번재 매개변수 : upload다음에 올 파일명 받는다
		
		String onlyFilename = filename.substring(0, filename.lastIndexOf("."));
      	// onlyFilename=test
		String extention = filename.substring(filename.lastIndexOf("."));
      	// .txt
		
		// 실제 업로드할 파일 명
		String filepath = null;
		// 파일명이 중복되는 경우 뒤에 붙일 숫자
		int count = 0;
		while(true) {
			if(count==0) {
				// 파일이름체크 첫번째인 경우
				filepath = onlyFilename+extention;
				
			}else {
				filepath = onlyFilename+"_"+count+extention;
			}
			File checkFile = new File(path+filepath);
			if(!checkFile.exists()) {
				// 중복파일명이 아닌 경우 무한 반복문 나가기
				break;
			}
			count++;
		}
		return filepath;
	}
}

jsp-form태그 지정

method = "post" enctype="multipart/form-data"

input = multiple

controller

@RequestMapping(value="/boardWrite.do")
public String boardWrite(Board b, MultipartFile[] boardFile,
                         HttpServletRequest request) {
  ArrayList<FileVO> list = new ArrayList<FileVO>();
  if(!boardFile[0].isEmpty()) {
  String savePath = request.getSession().getServletContext()
  .getRealPath("/resources/upload/board/");
  for(MultipartFile file : boardFile) {
      String filename = file.getOriginalFilename();
      String filepath = fileRename.fileRename(savePath, filename);

      try {
        FileOutputStream fos = new FileOutputStream(new File(savePath+filepath));
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        try {
          byte[] bytes = file.getBytes();
          bos.write(bytes);
          bos.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();     
      }
      FileVO fileVo = new FileVO();
      fileVo.setFilename(filename);
      fileVo.setFilepath(filepath);
      list.add(fileVo);
    }// for문 종료
  }
  b.setFileList(list);
  int result = service.insertBoard(b);
  return "redirect:/boardList.do?reqPage=1";
}

service

public int insertBoard(Board b) {	
	// board에 인서트가 되지 않으면 file 테이블에서 references를 받을 수 없음
	int result = dao.insertBoard(b);
	System.out.println("dao 수행 후 : "+b.getBoardNo());
	if(result>0) {
		// insert가 성공한 경우 파일 insert
		// 파일이 없는 경우 insert 필요 없음
		if(!b.getFileList().isEmpty()) {
			// 가장 최근에 들어간 boardNo 조회
			int boardNo = dao.selectBoardNo();
			for(FileVO fv : b.getFileList()) {
             // 방금 insert한 board_no를 참조하기 위해 set
				fv.setBoardNo(boardNo);
				result += dao.insertFile(fv);
			}
		}
	}
	return result;
}
profile
aelatte coding journal

0개의 댓글