728x90
728x90

11. 파일처리.pptx
7.48MB

 

파일업로드는 insert와 delete, 추가만 있다.
fileUploadEx 라는 이름의 스프링 레거시 프로젝트를 만든다.

 

 

C 루트에 upload/temp 폴더를 만든다.

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.lje</groupId>
	<artifactId>aopexam</artifactId>
	<name>aopExam</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.1.9.RELEASE</org.springframework-version>
		<org.aspectj-version>1.9.4</org.aspectj-version>
		<org.slf4j-version>1.7.25</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> 
			<version>2.5</version> <scope>provided</scope> </dependency> -->
		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<!-- 스프링프레임워크 랑 똑같은 버전으로 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.1.9.RELEASE</version>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.8</version>
			<scope>provided</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.9.4</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.9.4</version>
		</dependency>

		<!-- 추가한 것 -->
		<!-- https://mvnrepository.com/artifact/com.googlecode.log4jdbc/log4jdbc -->
		<dependency>
			<groupId>com.googlecode.log4jdbc</groupId>
			<artifactId>log4jdbc</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.5.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>2.0.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.1.9.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>5.1.9.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.7.0</version>
		</dependency>


	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<additionalProjectnatures>
						<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
					</additionalProjectnatures>
					<additionalBuildcommands>
						<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
					</additionalBuildcommands>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>true</downloadJavadocs>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<compilerArgument>-Xlint:all</compilerArgument>
					<showWarnings>true</showWarnings>
					<showDeprecation>true</showDeprecation>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.2.1</version>
				<configuration>
					<mainClass>org.test.int1.Main</mainClass>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

 

web.xml (한글처리)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
	id = "WebApp_ID">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<multipart-config>
			<location>C:\\upload\\temp</location>
			<max-file-size>20971520</max-file-size> <!-- 한파일: 1mb * 20 -->
			<max-request-size>41943040</max-request-size> <!-- 한번에 여러개올리는데 전체가 40mb -->
			<file-size-threshold>20971520</file-size-threshold> <!-- 넘으면 temp에 넣고 업로드에 들어가지 않는다 : 20mb -->
		</multipart-config>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- spring character encoding filter -->
	<filter>
           <filter-name>encoding</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>encoding</filter-name>
           <url-pattern>/*</url-pattern>
     </filter-mapping>

</web-app>

 

 

servlet-context.xml

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

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.lje.fileupload_ex" />
	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></beans:bean>
	
	
</beans:beans>

 

 

 

FileUploadController.java

package com.lje.fileupload_ex.controller;

import java.io.File;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import com.lje.fileupload_ex.domain.BoardVO;

import lombok.extern.java.Log;

@Controller
@Log
public class FileUploadController {
	String uploadFolder = "c:\\upload";
	
	@GetMapping("/upload")
	public void uploadForm() {
		log.info("upload form");
	}
	
	@PostMapping("/upload")
	public String upload(MultipartFile[] uploadFile, Model model) { //multiparfile : 여러개파일한번에
		for(MultipartFile multipartFile : uploadFile ) {
			log.info("=============================");
			log.info("upload file name:"+multipartFile.getOriginalFilename());
			log.info("upload file name:"+multipartFile.getSize());
			
			File saveFile = new File(uploadFolder, multipartFile.getOriginalFilename()); //uploadFolder 주소 밑에 경로 생성
			try {
				multipartFile.transferTo(saveFile); //파일을 이동해서 복사 (업로드됨)
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return "redirect:list";
	}
	
	@GetMapping("/list")
	public String list(Model model) {
		return "list";
	}
	
	@GetMapping("/upload2")
	public void uploadForm2() {
		log.info("upload form");
	}
	
	@PostMapping("/upload2")
	public String upload2(MultipartFile[] uploadFile, 
			@ModelAttribute("board") BoardVO board) { //multiparfile : 여러개파일한번에
		log.info("board:"+board);
		
		for(MultipartFile multipartFile : uploadFile ) {
			log.info("=============================");
			log.info("upload file name:"+multipartFile.getOriginalFilename());
			log.info("upload file name:"+multipartFile.getSize());
			
			File saveFile = new File(uploadFolder, multipartFile.getOriginalFilename()); //uploadFolder 주소 밑에 경로 생성
			try {
				multipartFile.transferTo(saveFile); //파일을 이동해서 복사 (업로드됨)
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return "redirect:list";
	}
	
}

 

 

 

list.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>list page</title>
</head>
<body>
<h1>
	list page  
</h1>

<P> This page is list page </P>
</body>
</html>

 

 

upload.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>
	<form action="upload" method="post" enctype="multipart/form-data">
		<input type="file" name="uploadFile" multiple><br><br>
		<button>Submit</button>
	</form>
</body>
</html>

 

 

upload2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 하기</title>
</head>
<body>
	<form action="upload2" method="post" enctype="multipart/form-data">
		<table>
			<tr><td>제목</td><td><input type="text" name="title"></td></tr>
			<tr><td>내용</td><td><textarea rows="5" cols="50" name="content"></textarea></td></tr>
			<tr><td>작성자</td><td><input type="text" name="writer"></td></tr>
			<tr><td>파일</td><td><input type="file" name="uploadFile"></td></tr>
			<tr><td colspan="2"><input type="submit" value="저장"></td></tr>
		</table>
	</form>
</body>
</html>

 

 

 

BoardVO.java

package com.lje.fileupload_ex.domain;

import java.util.List;

import lombok.Data;

@Data
public class BoardVO {
	private int bno;
	private String title;
	private String content;
	private String writer;
	private List<SaveFile> fileList;
	// 게시글과 해당하는 파일
}

 

 

테이블 만들기

create table file_board(
bno number primary key,
title varchar2(100) not null,
content VARCHAR2(1000) not null,
writer VARCHAR2(50) not null);

create SEQUENCE seq_file_board;

CREATE TABLE save_file(
fno number PRIMARY KEY,
file_name VARCHAR2(200) not null,
bno number REFERENCES file_board(bno));

CREATE SEQUENCE seq_save_file;


Save_file 제약조건 > 왜래키 > 삭제 시 설정 조정한다.
널 설정, 종속삭제 두 가지가 있는데 종속삭제는 bno를 지웠을 때 같이 지워진다.

 

SaveFile.java

package com.lje.fileupload_ex.domain;

import lombok.Data;

@Data
public class SaveFile {
	private int fno;
	private int bno;
	private String filename;
}

 

 

root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name="driverClassName" value="net.sf.log4jdbc.DriverSpy" />
			<property name="url" value="jdbc:log4jdvc:oracle:thin:@192.168.0.78:1521:XE" />
				
			<property name="username" value="mvc" />
			<property name="password" value="1234" />
		</bean>
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
			<property name="dataSource" ref="dataSource" /> 
		</bean>
		
		<mybatis-spring:scan base-package="com.lje.fileupload_ex.mapper" />
		<context:component-scan base-package="com.lje.fileupload_ex" />
		
</beans>

 

 

 

mapper

 

BoardMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lje.fileupload_ex.mapper.BoardMapper">
	<insert id = "register">
		insert into file_board (bno, title, content, writer)
		values(seq_file_board.nextval, ${title}, #{content}, #{writer})
	</insert>
	<select id="get" resultType="com.lje.fileupload_ex.domain.BoardVO">
		select * from file_board where bno=#{bno}
	</select>
	<select id="getList" resultType="com.lje.fileupload_ex.domain.BoardVO">
		select * from file_board;
	</select>
	<update id = "update">
		update file_board set title=#{title}, content=#{content}
		where bno = #{bno}
	</update>
	<delete id = "delete">
		delete from file_board where bno = #{bno}
	</delete>
</mapper>

 

 

FileMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lje.fileupload_ex.mapper.BoardMapper">
	<select id="get" resultType="com.lje.fileupload_ex.domain.SaveFile">
		select * from save_file where fno=#{fno}
	</select>
	<select id="getList" resultType="com.lje.fileupload_ex.domain.SaveFile">
		select * from save_file where bno=#{bno}
	</select>
	<insert id="register">
		insert into save_file(fno, filename, bno)
		values(seq_save_file.nextval, #{filename}, #{bno})
	</insert>
	<delete id="delete">
		delete from save_file where fno = #{fno}
	</delete>
	<delete id="deleteList">
		delete from save_file where bno = #{bno}
	</delete>
</mapper>

 

 

 

FileMapper.java (interface)

package com.lje.fileupload_ex.mapper;

import java.util.List;

import com.lje.fileupload_ex.domain.SaveFile;

public interface FileMapper {
	public void register(SaveFile saveFile);
	public void delete(int fno);
	public SaveFile get(int fno);
	public List<SaveFile> getList(int bno);
	public void deleteList(int fno);
}

 

 

BoardMapper.java (interface)

package com.lje.fileupload_ex.mapper;

import java.util.List;

import com.lje.fileupload_ex.domain.BoardVO;


public interface BoardMapper {
	public void register(BoardVO vo);
	public void update(BoardVO vo);
	public void delete(int bno);
	public BoardVO get(int bno);
	public List<BoardVO> getList();
}

 

 

 

Service


BoardService.java (interface)

package com.lje.fileupload_ex.service;

import java.util.List;

import com.lje.fileupload_ex.domain.BoardVO;
import com.lje.fileupload_ex.domain.SaveFile;

public interface BoardService {
	public void register(BoardVO vo, List<SaveFile> fileList);
	public void modify(BoardVO vo);
	public void remove(int bno);
	public BoardVO read(int bno);
	public List<BoardVO> getList();
	public void removeFile(int fno);
	public void registerFile(List<SaveFile> fileList);
}

 

 

 

BoardServiceImpl.java

package com.lje.fileupload_ex.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lje.fileupload_ex.domain.BoardVO;
import com.lje.fileupload_ex.domain.SaveFile;
import com.lje.fileupload_ex.mapper.BoardMapper;
import com.lje.fileupload_ex.mapper.FileMapper;

import lombok.AllArgsConstructor;
import lombok.extern.java.Log;

@Service
@Log
@AllArgsConstructor
public class BoardServiceImpl implements BoardService {
	private BoardMapper bMapper;
	private FileMapper fMapper;
	
	@Transactional //트랜잭션 두개 이상의 함수
	@Override
	//파일이 입력되거나 실패되면 전체 롤백됨.
	public void register(BoardVO vo, List<SaveFile> fileList) {
		log.info("Service.register..."+vo);
		bMapper.register(vo);
		registerFile(fileList); 
//		for(int i=0; i<fileList.size(); i++) {
//			fMapper.register(fileList.get(i));
//			log.info("Save file:"+fileList.get(i));
//		}
	}
	@Override
	public void modify(BoardVO vo) {
		bMapper.update(vo);
	}
	@Transactional
	@Override
	public void remove(int bno) { //파일은 게시글과 함께 지워진다.
		fMapper.delete(bno);
		bMapper.delete(bno);
	}
	@Override
	public BoardVO read(int bno) {  //데이터 가져오는거라 트랜젝션 ㄴㄴ
		List<SaveFile> fileList=fMapper.getList(bno);
		BoardVO vo=bMapper.get(bno);
		vo.setFileList(fileList);
		return vo;
	}
	@Override
	public List<BoardVO> getList() {
		return bMapper.getList();
	}
	@Override
	public void removeFile(int fno) {
		fMapper.delete(fno);
	}
	@Override
	public void registerFile(List<SaveFile> fileList) {
		for(int i=0; i<fileList.size(); i++) {
			fMapper.register(fileList.get(i));
			log.info("Save file:"+fileList.get(i));
		}
		
	}	
}
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v