Spring WEB MVC
1. 프로젝트 생성
2. home.jsp (메인으로 사용할 페이지)
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" pageEncoding="UTF-8"%> <html> <head> <title>Home</title> </head> <body> <br/><br/><br/> <div style="padding-left: 20px;"> <h2>Spring MVC Custom View Demo</h2> <h3>1. <a href="simpleCustomView.action">Simple Custom View</a> </h3> <h3>2. <a href="pdfView.action">PDF View</a> </h3> <h3>3. <a href="excelView.action">Excel View</a> </h3> <h3>4. File Upload</h3> <form action="upload.action" method="post" enctype="multipart/form-data"> <input type="file" name="upload"/><br/> <input type="submit" value="전송"/><br/> </form> <h3>5. <a href="download.action">File Download</a> </h3> </div> </body> </html> |
출력 페이지 (home.jsp)
클래스로 뷰를 만드는 방법
3. HomeController.class
package com.exe.springwebview; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String home() {
return "home"; }
//클래스로 뷰를 만드는 방법 @RequestMapping(value = "/simpleCustomView.action", method = RequestMethod.GET) public ModelAndView customView() {
ModelAndView mav = new ModelAndView(); //jsp 파일 mav.setViewName("simpleCustomView");//폴더없이 views밑에 생성함. jsp로 보냄
//Class mav.setView(new SimpleCustomView());//class로 보냄 mav.addObject("message1","It's SimpleCustomView Class");//class로 보내는 데이터 mav.addObject("message2","Second Data"); return mav; }
} |
4-1. simpleCustomView.jsp (Spring WEB MVC - web View 실습)
<%@ page contentType="text/html; charset=UTF-8"%> <% request.setCharacterEncoding("UTF-8"); String cp = request.getContextPath(); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>SimpleCustomView</title> </head> <body> <h2>SimpleCustomView.jsp 파일 입니다</h2> </body> </html> |
4-2. SimpleCustomView.class 클래스로 뷰를 만드는 방법
package com.exe.springwebview; import java.io.PrintWriter; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.AbstractView; //View의 능력을 부여하기 위하여 추상클래스 상속 public class SimpleCustomView extends AbstractView{ @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
PrintWriter out = response.getWriter(); out.print("<html>"); out.print("<head>class view"); out.print("</head>"); out.print("<body>"); out.print("<h2>"); out.print(model.get("message1")); out.print("<br/>"); out.print(model.get("message2")); out.print("</h2>"); out.print("</body>"); out.print("</html>"); }
} |
5. 출력 페이지
JSP페이지 연결
Class 연결
PDF 전송
PDF를 내보내기 위해서는 규칙이 존재 어크로뱃 사의 규칙을 따라줘야한다.
1. PDF 전송을 위해서는 특정 라이브러리 필요 - IText. MavenRepository 통해 설치
- pom.xml 반영
<!-- com.lowagie/itext --> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> </dependency> |
- 설치 완료여부 반드시 확인하기
2. Controller 작성
package com.exe.springwebview; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String home() {
return "home"; } //클래스로 PDF를 만드는 방법 @RequestMapping(value = "/pdfView.action", method = RequestMethod.GET) public ModelAndView getPdfView() {
ModelAndView mav = new ModelAndView(); mav.setView(new CustomPdfView()); mav.addObject("message","PDF FILE"); return mav; } } |
3. CustomPdfView 클래스 작성
package com.exe.springwebview; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.document.AbstractPdfView; import com.lowagie.text.Chapter; import com.lowagie.text.Document; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfWriter; public class CustomPdfView extends AbstractPdfView { @Override protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { Chapter chapter = new Chapter(new Paragraph("Spring Message"),1);//1번째 행 chapter.add(new Paragraph((String)model.get("message")));//데이터 가져올 수 있음 document.add(chapter);//pdf파일에 추가 } } |
4. 출력 페이지
XML파일 내보내기
1. 필요 라이브러리 - MavenRepository 통해 설치
POI - MS OFFICE를 사용할 수 있는 라이브러리
- pom.xml 반영
<!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> |
jxl - 엑셀을 사용할 수 있게해주는 라이브러리
- pom.xml 반영
<!-- jexcelapi/jxl --> <dependency > <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.12</version> </dependency> |
2. Controller 클래스
package com.exe.springwebview; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String home() {
return "home"; }
//클래스로 EXCEL를 만드는 방법 @RequestMapping(value = "/excelView.action", method = RequestMethod.GET) public ModelAndView getExcelView() {
ModelAndView mav = new ModelAndView(); mav.setView(new CustomExcelView()); mav.addObject("message","EXCEL FILE"); return mav; } } |
3. CustomExcelView 클래스
package com.exe.springwebview; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.document.AbstractJExcelView; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class CustomExcelView extends AbstractJExcelView{ @Override protected void buildExcelDocument(Map<String, Object> model, WritableWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.addHeader("Content-Disposition","attachment;filename=sales.xls");//xls 엑셀의 확장자명
WritableSheet sheet = workbook.createSheet("판매고보서", 0); sheet.addCell(new Label(0,0,"년도"));//jxl.write.Label; 1행 A열 sheet.addCell(new Label(1,0,"판매량"));//1행 B열
//엑셀 작성시 반복문을 활용하면 손쉽게 완성가능
//판매량 임의의 값 for(int i=2001;i<2018;i++) { sheet.addCell(new Label(0,i-2000,String.format("%d", i))); //년도 sheet.addCell(new Label(1,i-2000,String.format("%d",(int)(Math.random()*9000)+10000))); } } } |
4. 출력 페이지
- 생성된 엑셀 파일 확인
파일 업로드
1. 라이브러리 설치
- pom.xml 반영
<!-- commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> |
- pom.xml 반영
<!-- commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> |
2. servlet-context.xml - CommonsMultipartResolver 생성
CommonsMultipartResolver 에 있는 메소드명과 맞춰줘야 하므로 프로퍼티명이 틀리지않도록 유의하자
<?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.exe.springwebview" />
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <beans:property name="maxUploadSize" value="10240000"/> <beans:property name="maxInMemorySize" value="1024000"/> <beans:property name="defaultEncoding" value="UTF-8"/> </beans:bean> </beans:beans> |
3. Controller
package com.exe.springwebview; import java.io.FileOutputStream; import java.io.InputStream; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String home() {
return "home"; }
//파일 업로드 @RequestMapping(value = "/upload.action", method = RequestMethod.POST) public String upload(MultipartHttpServletRequest request, String str) { //request.getSession()은 생략가능 String path = request.getSession().getServletContext().getRealPath("/WEB-INF/files");
MultipartFile file = request.getFile("upload");//파일 읽어오기 if(file!=null && file.getSize()>0) {
try {
FileOutputStream fos = new FileOutputStream(path+"/"+file.getOriginalFilename()); //"/" 은 File.separator InputStream is = file.getInputStream(); byte[] buffer = new byte[512];
while(true) { int data = is.read(buffer,0,buffer.length); if(data==-1) { break; } fos.write(buffer,0,data); //버퍼에 있는 내용을 0~끝까지 파일 아웃풋 스트림에 작성해라 } is.close(); fos.close();
} catch (Exception e) { // TODO: handle exception } } return "uploadResult";
} } |
4. uploadResult.jsp 페이지
<%@ page contentType="text/html; charset=UTF-8"%> <% request.setCharacterEncoding("UTF-8"); String cp = request.getContextPath(); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> alert("파일 업로드 성공!!"); location.href="/springwebview/"; //메인페이지로 다시 돌아감 </script> </head> <body> </body> </html> |
5. 출력 페이지
서버에 파일 저장 경로 확인
파일 다운로드 기능 구현
1. Controller
package com.exe.springwebview; import java.io.FileOutputStream; import java.io.InputStream; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String home() {
return "home"; } //파일 다운로드 @RequestMapping(value = "/download.action", method = RequestMethod.POST) public ModelAndView download() {
ModelAndView mav = new ModelAndView(); mav.setView(new DownloadView()); return mav;
} } |
2. DownloadView 클래스
package com.exe.springwebview; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.AbstractView; public class DownloadView extends AbstractView{ @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { //다운로드 처리 //1.브라우저에게 처리할수없는 컨텐츠로 알려줘서 다운로드 처리하도록 작성 //response.setContentType("application/octet-stream"); response.setContentType("application/unknown");
//2.다운로드 처리할때 필요한 정보를 제공 response.addHeader("Content-Disposition","Attachment;FileName=\"_AjaxBasic.pdf\""); //업로드시킨 파일 중 하나를 기입
//3.파일 응답 스트림에 기록 String file = request.getSession().getServletContext().getRealPath("WEB-INF/files/_AjaxBasic.pdf");//파일경로
//스트림 객체 생성 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
while(true) { int data = bis.read();//읽어오기
if(data!=-1) { bos.write(data);//작성하기 }else { break; } } bis.close(); bos.close(); } } |
출력 페이지
'Dev > Spring' 카테고리의 다른 글
[Spring] EHCache (0) | 2020.05.06 |
---|---|
[Spring] Annotation 간략 정리 (0) | 2019.12.11 |
Spring3.0 - MVC web & MyBatis (0) | 2019.04.18 |
Spring3.0 - MVC web & JDBC 게시판만들기 (0) | 2019.04.18 |
Spring3.0 - AOP (0) | 2019.04.17 |