빡코

Spring 3.0 View 셋팅 실습하기 본문

Java

Spring 3.0 View 셋팅 실습하기

chris.djang 2019. 11. 15. 19:32

SpringWebView 프로젝트 생성해준다. 

패키지의 이름은 com.exe.springwebview

전체 셋팅 구조는 다음과 같다.

 

SpringWebView 의 구조


https://mvnrepository.com/ 에서 maven 태그 복사해 오기

검색창에 itext 검색어 입력하여 다음과 같은 주소에서 태그를 복사하여 pom.xml에 추가해주기

 

 

 

엑셀파일로 내보내는데 필요한 maven 태그이다.

https://mvnrepository.com/artifact/org.apache.poi/poi/3.17

https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl/2.6.12

 

 

파일업로드 관련 maven 태그  

https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload/1.3.3

https://mvnrepository.com/artifact/commons-io/commons-io/2.6

 

 

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.exe</groupId>
	<artifactId>springwebview</artifactId>
	<name>SpringWebView</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</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.15</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>
		<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.7</version>
			<scope>test</scope>
		</dependency>   
		
		
		<!-- itext -->
		<dependency>
    		<groupId>com.lowagie</groupId>
    		<artifactId>itext</artifactId>
    		<version>2.1.7</version>
		</dependency>
		
		<!-- poi(Ms-office 사용가능하게 해준다) -->
		<dependency>
    		<groupId>org.apache.poi</groupId>
    		<artifactId>poi</artifactId>
    		<version>3.17</version>
		</dependency>
		
		<!-- jxl(Excel파일 사용가능하게 해준다) -->
		<dependency>
    		<groupId>net.sourceforge.jexcelapi</groupId>
    		<artifactId>jxl</artifactId>
    		<version>2.6.12</version>
        </dependency>
        
        <!-- 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.6</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.6</source>
                    <target>1.6</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>

 

 

 

다음은 실습화면을 띄위기 위해서, home.jsp을 작성하고 아래의 주소로 웹에 보여준다. 더불어 HomeController.java 클래스도 수정해 준다. 

 

1.home.jsp 

<!-- 실행주소 http://192.168.16.16:8080/springwebview/ -->
<%@ 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</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>

 

   

크롬 웹상에서 보여지는 모습은 다음과 같으며, 차례차례 눌르며 실행하면 된다.

자, 그럼 컨트롤러를 살펴보자. 

package com.exe.springwebview;

import java.io.FileOutputStream;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home() {
		return "home";
	}
	
	@RequestMapping(value = "/pdfView.action")
	public ModelAndView getPdfView() {
		
		ModelAndView mav = new ModelAndView();
		mav.setView(new CustomPdfView());
		mav.addObject("message","PDF FILE");
		return mav;
	}
	
	@RequestMapping(value = "/excelView.action")
	public ModelAndView getExceAndView() {
		
		ModelAndView mav = new ModelAndView();
		
		mav.setView(new CustomExcelView());
		
		return mav;
	}
	
	//파일 업로드
	//파일을 올려주는 역할함
	@RequestMapping(value = "/upload.action",
			method = {RequestMethod.GET,RequestMethod.POST})
	public String upload(MultipartHttpServletRequest request,
			String str) {
		
		//그림 같은 경우: getRealPath("/image"); // 웹페이지에 띄우는 그림들을 넣어주어야 한다!!!!!!!!!!!!!!!!!!!!
		String path = 
				request.getSession()
				.getServletContext()
				.getRealPath("/WEB-INF/files");
		
		//문제는 WEB-INF를 일반인 접근할 수 없다는 것이다. 따라서 스프링에서는 그림이 디스클로징 되지 않는다.
		//그림이 webapp 밑으로 image 폴더를 만들어서 사용자에게 띄어줘야 한다.
		MultipartFile file = request.getFile("upload");
		if(file!=null&&file.getSize()>0) { //파일이 있으면
			
			try {
				
				FileOutputStream fos =
						new FileOutputStream(path +
								"/" + file.getOriginalFilename());
				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);
				}
				is.close();
				fos.close();
			} catch (Exception e) {
				System.out.println(e.toString());
			}
		}
		return "uploadResult";
	}
	
	//파일 다운로드 
	@RequestMapping(value = "/download.action")
	public ModelAndView download() {
		
		ModelAndView mav = new ModelAndView();
		
		mav.setView(new DownloadView());
		
		return mav;
	}
	
}

http://IP주소/springwebview/ 주소에서 연결되는 클래스는 다음과 같다.

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;

public class SimpleCustomView extends AbstractView {

	@Override
	protected void renderMergedOutputModel(
			Map<String, Object> model,  //("message","SimpleCustomView Class") 이 값이 넘어온다
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		
		PrintWriter out = response.getWriter();

		out.print("<html>");
		out.print("<head> View Test");
		out.print("</head>");
		out.print("<body>");
		out.print("<h2>"); //모델로 넘어는 데이터찍기
		out.print(model.get("message"));
		out.print("</h2>");
		out.print("</body>");
		out.print("</html>");
		
		
		
		
	}

}

 

아래는 simpleCustomView.jsp 코딩이다. 이 화면이 웹상에 실제로 보여지게 된다.

<%@ page contentType="text/html; charset=UTF-8"%>
<%
	request.setCharacterEncoding("UTF-8");
	String cp= request.getContextPath();
	
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>SimpleCustomView.jsp 입니다</h1>

</body>
</html>

실제화면

 

 

2. PDF view를 살펴보겠다. 

homeContllorer.java 내의 해당 코딩 

	
	@RequestMapping(value = "/pdfView.action")
	public ModelAndView getPdfView() {
		
		ModelAndView mav = new ModelAndView();
		mav.setView(new CustomPdfView());
		mav.addObject("message","PDF FILE");
		return mav;
	}
	

 

CustomPdfView.java 클래스의 코딩 

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 {
		
		//pdf를 만드는 가장 기본적인 코딩
		//실행주소: http://192.168.16.16:8080/springwebview/pdfView.action
		Chapter chapter = new Chapter(new Paragraph("Spring Message"),1);
		chapter.
		add(new Paragraph((String)model.get("message")));
		
		document.add(chapter);
		
	}
	
	
}

 

실제 웹상에 띄워지는 모습

 

3. 엑셀 view

homeContllorer.java 내의 해당 코딩 

	@RequestMapping(value = "/excelView.action")
	public ModelAndView getExceAndView() {
		
		ModelAndView mav = new ModelAndView();
		
		mav.setView(new CustomExcelView());
		
		return mav;
	}
	

CustomExcelView.java 클래스 코딩

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");
		WritableSheet sheet = workbook.createSheet("판매보고서",0); //0번째(첫번째) sheet에다가 판매보고서 만들기
		
		//0,0에다가 년도를 쓰겠다!!
		sheet.addCell(new Label(0,0,"년도")); //** import되는 경로? 주의하기!!
		sheet.addCell(new Label(1,0,"판매량"));
		
		for(int i=2001;i<=2019;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()*90000)+100000))); //랜덤으로 임의의 숫자를 만들냄
		}
		
	}
	
}

 

Exel View실행결과 

Exel View실행결과 

 

4. 파일 업로드(homeContllorer.java 내의 해당 코딩 )

@RequestMapping(value = "/upload.action",
			method = {RequestMethod.GET,RequestMethod.POST})
	public String upload(MultipartHttpServletRequest request,
			String str) {
		
		//그림 같은 경우: getRealPath("/image"); // 웹페이지에 띄우는 그림들을 넣어주어야 한다!!!!!!!!!!!!!!!!!!!!
		String path = 
				request.getSession()
				.getServletContext()
				.getRealPath("/WEB-INF/files");
		
		//문제는 WEB-INF를 일반인 접근할 수 없다는 것이다. 따라서 스프링에서는 그림이 디스클로징 되지 않는다.
		//그림이 webapp 밑으로 image 폴더를 만들어서 사용자에게 띄어줘야 한다.
		MultipartFile file = request.getFile("upload");
		if(file!=null&&file.getSize()>0) { //파일이 있으면
			
			try {
				
				FileOutputStream fos =
						new FileOutputStream(path +
								"/" + file.getOriginalFilename());
				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);
				}
				is.close();
				fos.close();
			} catch (Exception e) {
				System.out.println(e.toString());
			}
		}
		return "uploadResult";
	}

uploadResult.jsp 

<%@ page contentType="text/html; charset=UTF-8"%>
<%
	request.setCharacterEncoding("UTF-8");
	String cp= request.getContextPath();
	
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript">
	
	alert("파일 업로드 성공!!");
	
	location.href="/springwebview/"; //다시 메인으로 돌아가게요

</script>

</head>
<body>

</body>
</html>

 

실행결과 화면 

 

 

 

 

내 PC에 저장된 모습 

경로:D:\sts-bundle\work\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringWebView\WEB-INF

 

5.파일 다운로드(homeContllorer.java 내의 해당 코딩)

 

	//파일 다운로드 
	@RequestMapping(value = "/download.action")
	public ModelAndView download() {
		
		ModelAndView mav = new ModelAndView();
		
		mav.setView(new DownloadView());
		
		return mav;
	}
	

 

DownloadView.java 클래스의 모습

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 {

		response.setContentType("application/octet-stream");

		response.addHeader("Content-Disposition", "attachment;filename=\"a.jpg\"");

		String file = request.getSession().getServletContext().getRealPath("WEB-INF/files/a.jpg");

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

	}

}

 

실행된 모습

<스프링 끝>

'Java' 카테고리의 다른 글

Spring 3.0 + Mybatis 셋팅 && 실습  (0) 2019.11.15
Spring 3.0 + jdbc 셋팅 && 실습  (0) 2019.11.15
스프링 3.0 + 웹 개발  (0) 2019.11.14
스프링 3.0 + APO 셋팅 및 실습  (0) 2019.11.14
스프링 3.0 + MyBatis 셋팅  (0) 2019.11.14