이론


pom.xml에 dependency 하기 -> web.xml에 필터설정하기, servlet설정하기 ->context.xml에 연결할 DB설정하기

->build path에서 톰캣에 ojdbc6.jar 추가하기*****  -> servlet.xml 생성하고 dataSource setting, MyBatis config,mapper setting , MyBatis Template configure, multipartResolver 추가하기 

vo생성하기 -> dao생성하기 ->config.xml생성하기 -> mapper.xml 생성하기-> Controller생성하기 -> jsp생성하기


파일 다운로드 방법(Controller 에서 사용)

파일의 버퍼 설정

다운로드 요청에 대한 HandlerMapping

이미 업로드된 경로에서 파일 다운로드를 할 것이기 때문에 리스트나 뷰에서 해당 파일의 이름을 받아와야 한다.

fileDown.kosta?fileName=파일이름

-> @RequestParam("fileName") String fileName

ServletContext와 파일의 절대경로를 얻어내기위해서

-> HttpSession session, HttpServletRequest request

다운로드란 브라우저와 Stream으로 연결되어서 통신되어야 하기 때문에..

-> HttpServletResponse response

applicationContext 객체를 request로 부터 얻어냄

업로드된 경로 얻음

그 경로로 파일객체를 생성

FileInputStream 스트림으로 읽어옴

요청객체로부터 연결될 브라우저의 마임타입을 얻어냄

만약 마임타입값이 없으면 그냥 디폴트로 스트림으로 연결

지정된 마임타입 세팅

다운로드될 파일의 길이 세팅

다운로드 Type을 설정함

위의 다운로드 타입의 정보를 해더로 설정

브라우저로부터 스트림을 연결

버퍼를 끼워서 빠르게 전달 목적

이제 브라우저로 보내고, 자원 닫으면 끝





실습


pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring0411</groupId>
  <artifactId>spring0411</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <!-- spring-jdbc for MyBatis -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.1</version>
            </dependency>
            <!-- Web MVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.3.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
            </dependency>
            <!-- Aop관련 -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.10</version>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.6</version>
            </dependency>
        </dependencies>
</project>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>spring0411</display-name>
 <!-- Filter -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>EUC-KR</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
   <servlet-name>kosta</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>kosta</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
   
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

kosta-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?xml version="1.0" encoding="UTF-8"?>
 
 
    <context:component-scan base-package="or.kosta.mvc"/>
    <mvc:annotation-driven/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
     
    <!-- dataSource setting -->
    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/myoracle"></property>
    </bean>
    <!-- MyBatis config,mapper setting -->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:or/kosta/config/config.xml"/>
        <property name="mapperLocations" value="classpath*:or/kosta/mapper/*.xml"/>
    </bean>
    <!-- MyBatis Template configure -->
    <bean id="ss" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="factoryBean"/>
    </bean>
     
    <!-- multipartResolver 추가 : 파일 업로드를 하기 위해서 꼭 필요한 객체  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
</beans>

src/or.kosta.config/config.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
<configuration>
    <typeAliases>
        <typeAlias type="or.kosta.vo.TBoardDTO" alias="tvo" />
    </typeAliases>
  
</configuration>

src/or.kosta.mapper/tboardMap.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  <mapper namespace="tboardMap">
    <insert id="add" parameterType="tvo">
    insert into tvo values(tvo_seq.nextVal,#{title},#{writer},#{content},#{pwd},#{mfile})
    </insert>
    <select id="list" resultType="tvo">
    select num,title,writer,mfile from tvo order by 1 desc
    </select>
    <select id="detail" parameterType="int" resultType="tvo">
    select num,title,writer,content,mfile,pwd from tvo where num=#{num}
    </select>
    <update id="up" parameterType="tvo">
    update tvo set title=#{title},writer=#{writer},content=#{content},mfile=#{mfile},pwd=#{pwd} where num=#{num}
    </update>
    <delete id="del" parameterType="int">
        delete from tvo where num=#{num}
    </delete>
  </mapper>

src/or.kosta.mvc.controller/DefaultController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package or.kosta.mvc.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class DefaultController {
 
    //기본 페이지 설정
    @RequestMapping(value= {"/index","/"})
    public String defaultPage() {
        System.out.println("test");
        return "index";
    }
    @RequestMapping(value="/myindex")
    public String myDefaultView() {
        return "index";
    }
}

src/or.kosta.mvc.controller/TboardController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package or.kosta.mvc.controller;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
 
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
 
import or.kosta.mvc.dao.TvoDao;
import or.kosta.vo.TBoardDTO;
 
@Controller
public class TBoardController {
    @Autowired
    private TvoDao tvoDao;
 
    @RequestMapping(value = "/form")
    public String form() {
        return "form";
    }
 
    @RequestMapping(value = "/tBoardProcess", method = RequestMethod.POST)
    public ModelAndView save(TBoardDTO tvo, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String r_path = session.getServletContext().getRealPath("/");
        System.out.println(r_path);
        String img_path = "resources\\img\\";
        System.out.println(img_path);
        StringBuffer path = new StringBuffer();
        path.append(r_path).append(img_path);
        String oriFn = tvo.getMfile1().getOriginalFilename();
        path.append(oriFn);
        System.out.println(path);
        // 파일 업로드
        File f = new File(path.toString());
        try {
            tvo.getMfile1().transferTo(f);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        tvo.setMfile(oriFn);
        tvoDao.add(tvo);
        ModelAndView mav = new ModelAndView("redirect:/list");
        return mav;
    }
 
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("list");
        List<TBoardDTO> listvo = tvoDao.getList();
        mav.addObject("list", listvo);
        return mav;
    }
 
    // 파일의 버퍼 설정
    private static final int BUFFER_SIZE = 4096;
 
    // 다운로드 요청에 대한 HandlerMapping
    // 이미 업로드된 경로에서 파일 다운로드를 할 것이기 때문에
    // 리스트나 뷰에서 해당 파일의 이름을 받아와야 한다.
    // fileDown.kosta?fileName=파일이름
    // -> @RequestParam("fileName") String fileName
    // ServletContext와 파일의 절대경로를 얻어내기위해서
    // -> HttpSession session, HttpServletRequest request
    // 다운로드란 브라우저와 Stream으로 연결되어서 통신되어야 하기 때문에..
    // -> HttpServletResponse response
    @RequestMapping(value = "/fileDown")
    public void fileDown(@RequestParam("fileName") String fileName, HttpSession session, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        // applicationContext 객체를 request로 부터 얻어냄
        ServletContext context = request.getServletContext();
        // 업로드된 경로 얻음
        String img_path = "resource\\img\\";
        String path = session.getServletContext().getRealPath("resources/img/") + fileName;
        System.out.println("FileDown:" + path);
        // 그 경로로 파일객체를 생성
        File downloadFile = new File(path);
        // FileInputStream 스트림으로 읽어옴
        FileInputStream fi = new FileInputStream(downloadFile);
        // 요청객체로부터 연결될 브라우저의 마임타입을 얻어냄
        String mimeType = context.getMimeType(path);
        // 만약 마임타입값이 없으면 그냥 디폴트로 스트림으로 연결
        if (mimeType == null) {
            // text/html, text/json, text/image
            mimeType = "application/octet-stream";
        }
        // 지정된 마임타입 세팅
        response.setContentType(mimeType);
        // 다운로드될 파일의 길이 세팅
        response.setContentLength((int) downloadFile.length());
        // 다운로드 Type을 설정함
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        // 위의 다운로드 타입의 정보를 해더로 설정
        response.setHeader(headerKey, headerValue);
        // 브라우저로부터 스트림을 연결
        OutputStream outStream = response.getOutputStream();
        // 버퍼를 끼워서 빠르게 전달 목적
        byte[] buffer = new byte[BUFFER_SIZE];
        // 이제 브라우저로 보내고, 자원 닫으면 끝
        int bytesRead = -1;
        while ((bytesRead = fi.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }
        fi.close();
        outStream.close();
 
    }
 
    @RequestMapping(value = "/detail")
    public String detail(int num, Model m) {
        TBoardDTO vo = tvoDao.getDetail(num);
        m.addAttribute("vo", vo);
        return "detail";
    }
 
    @RequestMapping(value = "/update")
    public String updateForm(int num, Model m) {
        TBoardDTO vo = tvoDao.getDetail(num);
        m.addAttribute("vo", vo);
        return "updateForm";
    }
 
    @RequestMapping(value = "/updateProcess", method = RequestMethod.POST)
    public ModelAndView updateProcess(TBoardDTO tvo, HttpServletRequest request) {
        if (tvo.getMfile1().isEmpty() == false) {
            HttpSession session = request.getSession();
            String r_path = session.getServletContext().getRealPath("/");
            System.out.println(r_path);
            String img_path = "resources\\img\\";
            System.out.println(img_path);
            StringBuffer path = new StringBuffer();
            path.append(r_path).append(img_path);
            String oriFn = tvo.getMfile1().getOriginalFilename();
            path.append(oriFn);
            System.out.println(path);
            // 파일 업로드
            File f = new File(path.toString());
            try {
                tvo.getMfile1().transferTo(f);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
            tvo.setMfile(oriFn);
        }else {
            tvo.setMfile(tvo.getMfile());
        }
        tvoDao.update(tvo);
        ModelAndView mav = new ModelAndView("redirect:/list");
        return mav;
    }
    @RequestMapping(value = "/delete")
    public String delete(int num) {
        tvoDao.delete(num);
        return "redirect:/list";
    }
}

src/or.kosta.mvc.dao/TvoDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package or.kosta.mvc.dao;
 
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import or.kosta.vo.TBoardDTO;
//
@Repository
public class TvoDao {
    @Autowired
    private SqlSessionTemplate ss;
     
    public void add(TBoardDTO tvo) {
        ss.insert("tboardMap.add",tvo);
    }
    public List<TBoardDTO> getList(){
        return ss.selectList("tboardMap.list");
    }
    public TBoardDTO getDetail(int num) {
        return ss.selectOne("tboardMap.detail",num);
    }
    public void update(TBoardDTO tvo) {
        ss.update("tboardMap.up", tvo);
    }
    public void delete(int num) {
        ss.delete("tboardMap.del",num);
    }
     
}

src/or.kosta.vo/TBoardDTO.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package or.kosta.vo;
 
import org.springframework.web.multipart.MultipartFile;
 
public class TBoardDTO {
    private int num;
    private String title,writer,content,pwd,mfile;
    private MultipartFile mfile1;
     
    public String getMfile() {
        return mfile;
    }
 
    public void setMfile(String mfile) {
        this.mfile = mfile;
    }
 
    public MultipartFile getMfile1() {
        return mfile1;
    }
 
    public void setMfile1(MultipartFile mfile1) {
        this.mfile1 = mfile1;
    }
 
    public int getNum() {
        return num;
    }
 
    public void setNum(int num) {
        this.num = num;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
    public String getWriter() {
        return writer;
    }
 
    public void setWriter(String writer) {
        this.writer = writer;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
     
     
}

JSP코드 블로그에 버튼,파일등록창 같이떠서 제외


'학원수업 > Spring' 카테고리의 다른 글

학원 24일차 복습(4/16)  (0) 2018.04.16
학원 23일차 복습(4/13)  (0) 2018.04.13
학원 22일차 복습(4/12)  (0) 2018.04.12
학원 20일차 복습(4/10)  (0) 2018.04.10
학원 19일차 복습(4/9)  (0) 2018.04.09

+ Recent posts