1.이미지 전달
(1)정적인 이미지 전송
-서블릿/JSP 페이지에서 MIME타입 지정
image/gif
image/jpeg -압축률이 뛰어나다.
-ServletOutputStream으로 전달
바이너리 데이터 전송
HttpServletResponse의 getOutputStream()
(2)정적인 이미지전송 예제
//logo.jsp
<%@ page contentType="image/gif"%> <%@ page import="java.io.*" %><%
byte [] buffer = new byte[1024];
ServletOutputStream o = response.getOutputStream();
try {
String file = application.getRealPath("image/logo.gif");
BufferedInputStream in = new
BufferedInputStream(new FileInputStream(file));
int n = 0;
while((n=in.read(buffer, 0, 1024)) != -1) {
o.write(buffer, 0, n);
}
o.close();
in.close();
} catch(Exception e) { }
%>
//image.html
<html><head><title>이미지 파일</title></head>
<body>
<h3 align=center>학교 소개</h3>
<p>
학교 설명...
<p>
학교 로고 : <p> <img src=logo.jsp>
</body>
</html>
(3)동적인 이미지 전달
-주식시세와 같이 DB에서 데이터를 읽어들여 동적으로 데이터 전달(이미지 생성)
-서블릿에서 gif,jpeg 파일 포맷으로 변경
-gif :GifEncoding클래스 사용
-jpeg : com.sun.image.codec.jpeg 패키지의 JPEGImageEncoder 클래스
GifEncoder클래스
-GifEncoder(ImageProducer prod , OutputStream out);
ecode(),setDimensions(int width,int height)
JPEGImageEncoder클래스
createJPEGEncoder(OutputStream out)
encode(BufferedImage bi)
라이브러리 다운
Acme package를 다운 받자.
톰캣베이스폴더의 common/lib 내에 복사한다.
자바베이스폴더의 jre/lib/ext내에 복사한다.
이클립스는 재가동한다.
(4)동적인 이미지 전달 예제
//helloImage.java
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.servlet.*;
import javax.servlet.http.*;
import Acme.JPM.Encoders.GifEncoder;
public class HelloImage extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
ServletOutputStream out = res.getOutputStream();
res.setContentType("image/gif");
Graphics2D g = null;
try {
BufferedImage img = new
BufferedImage(400, 60, BufferedImage.TYPE_INT_RGB);
g = img.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, 400, 60);
g.setColor(Color.black);
g.setFont(new Font("Serif", Font.BOLD, 48));
g.drawString("Hello 안녕", 10, 50); //동적으로 이미지를 생성한다.
GifEncoder encoder = new GifEncoder(img, out);
encoder.encode(); //이미지 전송
} catch(Exception e) {
e.printStackTrace();
} finally {
if(g != null)
g.dispose();
}
}
}
2.차트생성
(1)개요
동적인 차트 생성
JFreeChar사용
http://www.jfreechart.org 에서 다운 받자
JFreeChar차트 사용
-데이터 생성
DataSet로 데이터 관리
-차트 생성
chartFactory클래스의 createXxxChar()메소드
-커스터마이징
Plot클래스를 이용하여 원하는 형태로 커스터마이징가능하다.
-차트보여주기
(2)예제
-파이차트예제
//PieChartTest.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jfree.chart.*;
import org.jfree.data.general.*;
public class PieChartTest extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
DefaultPieDataset ds = new DefaultPieDataset();
ds.setValue("홍길동", new Double(40.0));
ds.setValue("홍길숙", new Double(25.0));
ds.setValue("기타", new Double(15.0));
JFreeChart chart = ChartFactory.createPieChart(
"득점 분포", ds, true, true, false);
ServletOutputStream out = res.getOutputStream();
ChartUtilities.writeChartAsPNG(out, chart, 400, 400);//png포맷으로 그려준다.
}
}
-데이터베이스의 자료를 근거로 차트그리기
//XYChart.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.jfree.chart.*;
import org.jfree.data.xy.*;
import org.jfree.chart.plot.PlotOrientation;
public class XYChartTest extends HttpServlet {
String url;
String id = "root", passwd = "mysql";
public void init() {
try {
url = "jdbc:mysql://localhost:3306/stock";
String option="?useUnicode=true&characterEncoding=euckr";
url = url + option;
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
try {
Connection con = DriverManager.getConnection(url, id, passwd);
Statement st = con.createStatement();
String sql = "select value from lge";
ResultSet rs = st.executeQuery(sql);
XYSeries vs = new XYSeries("주가동향");
int x = 1;
while(rs.next()) {
vs.add(x, rs.getInt(1));
x += 1;
}
XYSeriesCollection ds = new XYSeriesCollection(vs);
JFreeChart chart = ChartFactory.createXYLineChart(
"주가동향", "날짜", "가격", ds,
PlotOrientation.VERTICAL, true, true, true);
ServletOutputStream out = res.getOutputStream();
ChartUtilities.writeChartAsPNG(out, chart, 400, 400);
} catch (Exception e) { }
}
}
3.기타 데이터의 MIME,
MP3 :response.setContentType("audio/x-mpeg")
리얼오디오:response.setContentType("audio/vnd.rn-realaudio")
리얼미디어:response.setContentType("audio/vnd.rn-realmedia")
4.응용프로그램 데이터 전송
(1)개요
Excel 실행
application/vnd.ms-excel;charset-KSC5601
Excel 저장
respons.setHeader("Content-Disposition","attachment;filename=data.xls");
Word 실행
application/msword;charset=KSC5601
(2)예제
//웹브라우저에서 엑셀실행시키기
<%@ page contentType="application/vnd.ms-excel;charset=KSC5601" %>
<html><head><title>엑셀 데이터</title></head>
<body>
<table>
<tr><td colspan=3 align=center><b>월급 명세서</b></td>
<tr bgcolor=gray>
<th>이름</th><th>월급(단위:만원)</th><th>주소</th></tr>
<tr><td>김개똥</td><td>500</td><td>목포시 부흥동</td></tr>
<tr><td>홍길동</td><td>350</td><td>광주시</td></tr>
<tr><td>허준</td><td>400</td><td>서울시</td></tr>
</table>
</body></html>
//엑셀을 다운 받도록하는 경우sava.jsp
<%@ page contentType="application/vnd.ms-excel;charset=KSC5601" %>
<%
response.setHeader("Content-Disposition",
"attachment;filename=data.xls");
%>
<html><head><title>엑셀 데이터</title></head>
<body>
<table>
<tr><td colspan=3 align=center><b>월급 명세서</b></td>
<tr bgcolor=gray>
<th>이름</th><th>월급(단위:만원)</th><th>주소</th></tr>
<tr><td>김개똥</td><td>500</td><td>목포시 부흥동</td></tr>
<tr><td>홍길동</td><td>350</td><td>광주시</td></tr>
<tr><td>허준</td><td>400</td><td>서울시</td></tr>
</table>
</body></html>
//웹브라우저 내에서 워드실행하기
<%@ page contentType="application/msword;charset=KSC5601" %>
<html><head><title>MS 워드</title></head>
<body>
<h3 align=center>워드 테스트</h3>
<u>안녕하세요</u>
<img src=logo.jsp>
</body>
</html>
5.파일 읽기 응용프로그램
(1)개요
웹 응용 프로그램의 파일을 읽고 변경가능도록 구현해보자
(2)예제
//dir.jsp
<%@ page contentType="text/html;charset=KSC5601" %>
<%@ page import="java.io.*, java.util.Date" %>
<%
String dir = request.getParameter("dir");
if(dir == null) dir = ".";
String path = application.getRealPath(dir);
File dirFile = new File(path);
File [] fileList = dirFile.listFiles();
%>
<html><head><title><%=path%></title></head>
<body>
<h3 align=center><%= path %> 파일 목록</h3>
<table width="100%">
<% for(int i = 0; i < fileList.length; i++) {
String name = fileList[i].getName();
%>
<tr><td>
<% if(fileList[i].isDirectory()) { %>
<img src=image/dir.gif>
<a href=dir.jsp?dir=<%=dir%>/<%=name%>><%=name%></a>
<% } else { %>
<img src=image/file.gif>
<a href=/servlet/FRead?dir=<%=dir%>&file=<%=name%>>
<%=name%></a>
<% } %> </td>
<td> <%= fileList[i].length() %> </td>
<td> <%
Date t = new Date(fileList[i].lastModified());
out.println(t.toLocaleString());
}
%> </table>
</body>
</html>
//FRead.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FRead extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("KSC5601");
String dir = req.getParameter("dir");
String file = req.getParameter("file");
if(file == null || dir == null) return;
String realDir = getServletContext().getRealPath(dir);
File f = new File(realDir + "/" + file);
if(f.isDirectory()) return;
if(file.endsWith("html") || file.endsWith("txt") ||
file.endsWith("xml") || file.endsWith("jsp")) {
res.setContentType("text/html;charset=KSC5601");
PrintWriter out = res.getWriter();
sendText(dir, file, realDir, out);
} else {
if(file.endsWith("gif"))
res.setContentType("image/gif");
else if(file.endsWith("jpg"))
res.setContentType("image/jpeg");
else {
res.setContentType("application/octet"); //파일을 다운받도록 하는 형태
res.setHeader("Content-Disposition",
"attachment;filename=" + file);
}
ServletOutputStream out = res.getOutputStream();
sendBinary(realDir, file, out);//파일전송
return;
}
}
protected void sendText(String dir, String file, String realDir,
PrintWriter out) throws IOException {
String path = realDir + "/" + file;
File dataFile = new File(path);
out.println("<html><head><title>"+file+"</title></head>");
out.println("<body>");
out.println("<h3 align=center>"+dir + "/" + file +"</h3>");
out.print("<form method=post ");
out.println(" action=/fwrite.jsp>");
out.println("<textarea cols=75 rows=25 name=contents>");
BufferedReader in = new BufferedReader(new FileReader(dataFile));
String line = null;
while((line = in.readLine()) != null) {
line = replace(line, "&", "&"); //특수문자입력방법
line = replace(line, "<", "<");
line = replace(line, ">", ">");
out.println(line);
}
out.println("</textarea><br><br>");
out.println("<input type=hidden name=dir value=\""+dir+"\">");
out.println("<input type=hidden name=file value=\""+file+"\">");
out.println("<center><input type=submit value=\"저 장\">");
out.println("<input type=reset value=\"취 소\"></center>");
out.println("</form></BODY></HTML>");
in.close();
out.close();
}
protected void sendBinary(String realDir, String file, //파일전송
OutputStream out) throws IOException {
String path = realDir + "/" + file;
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(path));
byte buf[] = new byte[1024];
int n=-1;
while((n = in.read(buf, 0, 1024)) != -1) {
out.write(buf, 0, n);
out.flush();
}
in.close();
out.close();
}
private String replace(String s, String from, String to) { //글자변환
int index = s.indexOf(from);
StringBuffer buf = new StringBuffer();
if(index < 0) return s;
buf.append(s.substring(0, index));
buf.append(to);
if(index + from.length() < s.length())
buf.append(replace(s.substring(index +
from.length(), s.length()), from, to));
return buf.toString();
}
}
//fwrite.jsp
<%@ page contentType="text/html;charset=KSC5601" %>
<%@ page import="java.io.*" %>
<%
request.setCharacterEncoding("KSC5601");
String dir = request.getParameter("dir");
String file = request.getParameter("file");
String fileContents = request.getParameter("contents");
if(dir == null || file == null) return;
String path = application.getRealPath(dir);
BufferedWriter fout =
new BufferedWriter(new FileWriter(path+"/"+file));
fout.write(fileContents, 0, fileContents.length());
fout.close();
%>
<p>
<%= file %>이 <a href=dir.jsp?dir=<%= dir %>><%=dir%></a>
디렉토리에 저장되었습니다.
</body>
</html>
6.파일 업로드
(1)멀티파트
POST방식으로 업로드
<form method ="post" enctype="multipart/form-data"> //바이너리형태로 전달된다.
<input type="file" name="filename"> //파일대화상자를 띄운다.
바운더리(Boundary) - 구분자
-사용자가 입력한 내용과 파일내용들을 구분하는 특수문자
(2)기본 예제
//multipart.html
<html>
<head><title>멀티파트</title></head>
<body><center><h2>멀티파트 테스트</h2></center>
<form action="multipart.jsp" method=post
enctype="multipart/form-data"> //바이너리 형태로 전달된다.
<p>
업로드할 파일 이름: <input type=file name=fileone>
<p>
설명 <br><textarea name=desc></textarea>
<p>
<input type=submit>
</form>
</body>
</html>
//multipart.jsp
<%@ page contentType="text/html;charset=KSC5601" %>
<html><head><title>멀티파트 테스트</title></head>
<body>
<%
String type = request.getContentType();
int len = request.getContentLength();
%>
<p> MIME : <%= type %>
<p> 길이 : <%= len %>
<xmp>
<%
ServletInputStream in = request.getInputStream();
//바이너리읽기
byte[] buf = new byte[1024];
int n = 0;
while((n = in.read(buf, 0, 1024)) > 0) {
out.println(new String(buf, 0, n));
}
in.close();
%>
</xmp>
</body>
</html>
파일과 일반텍스트를 구분하기 위한 것이 바운더리다.
(3)파일업로드 예제
com.oreilly.servlet.MultipartRequest클래스
http://www.servlets.com 에 가서 라이브러리 다운받자.
cos-05Nov2002.zip 파일
톰캣과 자바의 라이브러리 폴더에 복사하자.
톰캣의 app폴더내에 updload라는 폴더가 있어야한다.
//upload.html
<html><head><title>파일 업로드</title></head>
<body><h3>파일 업로드</h3>
<p>업로드할 파일을 선택해주세요
<p>
<form action="upload.jsp" method=post enctype="multipart/form-data">
<table>
<tr>
<td>제목</td>
<td><input type=text name=subject></td>
</tr>
<tr>
<td>파일 이름:</td>
<td><input type=file name=file1> </td>
</tr>
<tr>
<td>파일 이름:</td>
<td><input type=file name=file2></td>
</tr>
<tr>
<td colspan=2 align=center><input type=submit>
<input type=reset></td>
</tr>
</table>
</form></body></html>
//upload.jsp
<%@ page contentType="text/html;charset=KSC5601" %>
<%@ page import="java.io.PrintWriter"%>
<%@ page import="com.oreilly.servlet.*"%>
<%@ page import="com.oreilly.servlet.multipart.*"%>
<% request.setCharacterEncoding("KSC5601"); %>
<html><head><title>파일 업로드</title></head>
<body><h3>파일 업로드</h3>
<%
String dir = application.getRealPath("/upload");
int max = 5 * 1024 * 1024; // 5MB
try {
MultipartRequest m = new MultipartRequest(request, dir, max, //파일을 업로드한다.
"KSC5601", new DefaultFileRenamePolicy());
String subject = m.getParameter("subject");
String file1 = m.getFilesystemName("file1");
String ofile1 = m.getOriginalFileName("file1");
String file2 = m.getFilesystemName("file2");
String ofile2 = m.getOriginalFileName("file2");
%>
<p>제목 : <%= subject %>
<% if(file1 != null) { %>
<p>업로드 파일1 : <a href=/upload/<%= file1%>><%=ofile1%></a>
<% }
if(file2 != null) { %>
<p>업로드 파일2 : <a href=/upload/<%= file2%>><%=ofile2%></a>
<% }
}catch(Exception e) {
e.printStackTrace(new PrintWriter(out));
}
%>
</body></html>