close

Trust Me!! Trust You!!


  • Blog
  • Local Log
  • Tag Cloud
  • Key Log
  • Guestbook
  • RSS Feed
  • Write a Post
  • Admin

혹시 블로그 스킨이 깨져 보이시나요? 최신버전의 Internet Explorer(Windows용), Opera, Firefox를 사용해보세요.

Found 2 article(s) for 'Servlet'.

  1. 2015/08/24 [java servlet에서 pdf 다루기,오라클자바커뮤니티 자바서블릿강좌]
  2. 2013/04/06 Simple Cross Site Scripting (XSS) Servlet Filter

[java servlet에서 pdf 다루기,오라클자바커뮤니티 자바서블릿강좌]

분류없음
2015/08/24 23:36
 
[java servlet에서 pdf 다루기,오라클자바커뮤니티 자바서블릿강좌]
 
PDF(Portable Document Format)는 Adobe systems에서 만든 파일 형식인 줄은 다 아실 겁니다.
:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /> 
PDF 페이지 내의 모든 요소는 모두 객체들로 이루어 져 있습니다.

객체들은 순차적으로 표현되고 마지막에는 파일내의 각 객체들을 OFFSET을 나열하는 상호참조 테이블로 구성하며 마지막 부분은 root 객체를 가리키고 있고 또한 상호 참조 테이블의 시작까지의 OFFSET을 포함 합니다.
 
PDF의 장점이라면 HTML, XML보다 유연하게 문서의 출력 형식을 제어 할 수 있다는 것이며 Adobe의 Acrobat Reader는 PDF를 읽고 쓰는 프로그램 입니다.
 
PDF 문서는 LZW 알고리즘을 이용하여 압축 하며 PDF를 텍스트 에디터로 열어 보면 알아볼 수 없는 문자가 나오는 것이 바로 이 때문 입니다.
 
PDF 파일에서 정확한 정보들을 읽어 내기 위해서는 PDF내의 텍스트 기반의 명령어들을 검색하여 적합한 데이터의 압축을 풀어야 합니다.
 
자바에서 사용 할 수 있는 PDF API로는 상법용과 무료버전 몇 가지가 있는데 간단히 소개하면 다음과 같습니다.
 
l  http://www.klg.com 시트라카/KL 그룹
l  http://www.InetSoftCorp.com StyleWriterEE
l  http://www.pdflib.com/pdflib C로 작성된 PDFlib가 있으며 자바 Wrapper를 사용 합니다. 상업용이 아니라면 무료
l  http://www.reportlab.org 에서는 자바 버전은 없지만 파이썬으로 만들어진 것은 있습니다.
l  http://www.etymon.com PDF의 전체 스펙을 제공하지는 않지만 PDF를 검색하고 수정하는 것을 자바 프로그램을 통해 편리하게 할 수 있습니다.
 
 
본 강좌에서는 http://www.pdflib.com/pdflib의 pdflib를 이용하여 서블릿으로(물론 JSP로 만들어도 무방 합니다.) PDF 파일을 만들어 보겠습니다.
 
환경에 대해 말씀 드리면…
 
전 Tomcat4.1에서 작업을 했으며 그 이상의 버전에도 문제가 없으리라 생각 됩니다…
(혹시 톰캣이 설치되어 있지 않으신 분들은 본 사이트의 Tomcat 설치 강좌를 참고 하시어 설치하시기 바랍니다.)
 
1.     http://www.pdflib.com/products/pdflib/download/601/PDFlib-6.0.1p1-Windows.zip 에서 pdflib를 다운 받습니다.
 
2.     다운받은 파일을 적당 한곳에 압축을 풉니다.
압축을 푼 후  PDFlib-6.0.1p1-Windows\bind\java 폴더로 이동 합니다.
 
그곳에 보면 pdflib.jar 파일이 있는데 이 파일을 톰캣 홈 아래 common/lib에 복사 합니다.
 
3.     마찬가지로 PDFlib-6.0.1p1-Windows\bind\java 아래의 pdf_java.dll 파일을 windows 폴더아래의system32 폴더에 복사 합니다.
 
4.     서블릿 파일을 만들어 명령프롬프트에서 컴파일 해야 하므로 톰캣 홈 아래 common/lib/servler.jar 파일을 환경변수의 클래스패스에 추가 합니다.(톰캣5 이상이면 common/lib/servlet-api.jar 파일 임)
 
5.     이제 서블릿 파일을 아래 처럼 작성 합니다. 톰캣홈/webapps/ROOT/WEB-INF/classes 에 만듭니다.
 
/**
PDF.java
**/
 
/* $Id: helloServlet.java,v 1.11 :namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />2004/05/17 12:47:19 rp Exp $
 *
 * PDFlib client: hello servlet example in Java
 */
 
import java.io.*;
import javax.servlet.*;
 
import com.pdflib.pdflib;
import com.pdflib.PDFlibException;
 
public class PDF extends GenericServlet
{
    public void service(ServletRequest request, ServletResponse response)
    {
       int font;
       pdflib p = null;
       byte[] buf;
       ServletOutputStream out;
 
       try{
           p = new pdflib();
           // Generate a PDF in memory; insert a file name to create PDF on disk
           if (p.begin_document("d:/test.pdf", "") == -1) {
                     throw new Exception("Error: " + p.get_errmsg());
           }
 
           p.set_info("Creator", "helloServlet.java");
           p.set_info("Author", "Thomas Merz");
           p.set_info("Title", "Hello world (Java/Servlet)!");
 
           p.begin_page_ext(595, 842, "");           
 
           font = p.load_font("Helvetica-Bold", "unicode", "");
 
           p.setfont(font, 18);
 
           p.set_text_pos(50, 700);
           p.show("Hello world!");
           p.continue_text("(says Java/Servlet)");
           p.end_page_ext("");                             
 
           p.end_document("");                           
 
           buf = p.get_buffer();
 
           response.setContentType("application/pdf");
           response.setContentLength(buf.length);
 
           out = response.getOutputStream();
           out.write(buf);
           out.close();
        } catch (PDFlibException e) {
            System.err.print("PDFlib exception occurred in hello sample:\n");
            System.err.print("[" + e.get_errnum() + "] " + e.get_apiname() +
                            ": " + e.get_errmsg() + "\n");
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            if (p != null) {
                p.delete();                   
            }
        }
    }
}
 
6.     서블릿을 컴파일 하신 후 실행 하기 위해 서블릿 등록 및 매핑을 합니다. 톰캣홈/webapps/ROOT/WEB-INF/web.xml 파일에 다음을 추가 합니다. (<web-app> 와 </web-app> 사이에 넣습니다.)
 
<servlet>
        <servlet-name>PDF</servlet-name>
        <servlet-class>PDF</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>PDF</servlet-name>
        <url-pattern>/servlet/PDF</url-pattern>
    </servlet-mapping>
 
7.     톰캣을 Shutdown 후 다시 Start 하시구요,,, 브라우저에서 http://localhost/servlet/PDF 라고 하신 후 화면에 오류가 없는 것을 확인 후 d:\ 에 가시면 test.pdf가 있을 겁니다.
 
열어 보시면 환하게 웃고 있는 “Hello World”를 보실 수가 있을 겁니다. ㅎㅎ
 
성공 하시기를 바라구요,
 
감사합니다.
 
참고로 JSP 예제는 아래를 참고 하세요~
 
<%@ page language="java" contentType="text/html; charset=euc-kr" %>
<%@ page import="java.io.*, javax.servlet.*, com.pdflib.* " %>
 
<%
    int font;
    pdflib p = null;
    byte[] buf;
    ServletOutputStream output;
 
 
       try {
                     p = new pdflib();
 
                     // Generate a PDF in memory; insert a file name to create PDF on disk
                     if (p.begin_document("d:/test.pdf", "") == -1) {
                                  System.err.println("Error: " + p.get_errmsg());
                                  System.exit(1);
                     }
 
                     p.set_info("Creator", "hello.jsp");
                     p.set_info("Author", "JCLEE");
                     p.set_info("Title", "PDF Demo JSP!");
 
                     p.begin_page(595, 842);               
 
                     font = p.load_font("Helvetica-Bold", "unicode", "");
 
                     p.setfont(font, 18);
 
                     p.set_text_pos(50, 700);
                     p.show("Hello world!");
                     p.continue_text("(says Java/JSP)");
                     p.end_page();                             
 
                     p.close();                                                 
 
                     buf = p.get_buffer();
 
                     response.setContentType("application/pdf");  //--> 요기가 키 포인틉니다.
                     response.setContentLength(buf.length);
 
                     output = response.getOutputStream();
                     output.write(buf);
                     output.close();
 
       }
       catch (PDFlibException e) {
                     System.err.println("PDFlib exception occurred in hello sample:\n");
                     System.err.println("[" + e.get_errnum() + "] " + e.get_apiname() +
                                                                          ": " + e.get_errmsg() + "\n");
       } catch (Exception e) {
                     System.err.println(e.getMessage());
       } finally {
                     if (p != null) {
                                  p.delete();                     
                     }
       }
%>


http://java-source.net/open-source/pdf-libraries
http://neosm.tistory.com/13
http://api.itextpdf.com/itext/com/itext ··· der.html
https://pdfbox.apache.org/

http://www.planet-source-code.com/vb/sc ··· gwid%3D1
이올린에 북마크하기
TAG java, pdf, Servlet, tomcat
No received trackback. / No comment.

Trackback Address :: http://viper150.cafe24.com/trackback/259

You can also say.

Simple Cross Site Scripting (XSS) Servlet Filter

웹 프로그래밍
2013/04/06 00:03
 

Simple Cross Site Scripting (XSS) Servlet Filter

Ran into some issues on some of our Java sites today and needed a quick fix to protect the sites from malicious Cross Site Scripting (XSS) attempts. If you're not aware of what XSS is and have websites that have sensitive user data, you may want to read up, you're probably vulnerable, which means your users are vulnerable. I'm not claiming this is a perfect solution, but it was easy to implement and corrected the vulnerabilities with form and url injection. We basically have a Servlet Filter that's going to intercept every request sent to the web application and then we use an HttpServletRequestWrapper to wrap and override the getParameter methods and clean any potential script injection.


Here's the Filter:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.greatwebguy.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class CrossScriptingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    public void destroy() {
        this.filterConfig = null;
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
    }
}

Here's the wrapper:

?
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
package com.greatwebguy.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public final class RequestWrapper extends HttpServletRequestWrapper {
    public RequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }
    public String[] getParameterValues(String parameter) {
      String[] values = super.getParameterValues(parameter);
      if (values==null)  {
                  return null;
          }
      int count = values.length;
      String[] encodedValues = new String[count];
      for (int i = 0; i < count; i++) {
                 encodedValues[i] = cleanXSS(values[i]);
       }
      return encodedValues;
    }
    public String getParameter(String parameter) {
          String value = super.getParameter(parameter);
          if (value == null) {
                 return null;
                  }
          return cleanXSS(value);
    }
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null)
            return null;
        return cleanXSS(value);
    }
    private String cleanXSS(String value) {
                //You'll need to remove the spaces from the html entities below
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        return value;
    }
}

Add this to the top of your web.xml:

?
1
2
3
4
5
6
7
8
9
10
<filter>
    <filter-name>XSS</filter-name>
    <display-name>XSS</display-name>
    <description></description>
    <filter-class>com.greatwebguy.filter.CrossScriptingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>XSS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

I'm sure the cleanXSS replacements aren't the most efficient way of doing this, you could replace it StringEscapeUtils.escapeHtml from commons lang to simplify it a little, it's up to you, it all depends on what your site is doing and whether it's going to be a pain having all the html escaped, you could also adjust the url-pattern of the filter to be more specific to your application urls, so that everything under your app isn't running through the filter.

Some things to be aware of with this approach, you'll need to account for what you've encoded or in some cases you'll end up with weird characters in your database and possibly in validation of your input boxes. Some would recommend a more positive validation rather than negative validation and only allow a certain range of characters, it's up to you, but it is something to think about.



value = value.replaceAll(“(?i)script”, “”); instead of
value = value.replaceAll(“(?i)script”, “”); for a case insensitive replacement.



NHN 공개 XSS Filter
http://local.dev.naver.com/projects/lucy-xss/download


이올린에 북마크하기
TAG Filter, javascript, JSP, Servlet, XSS, 보안
Trackback 3 / No comment.

Trackback Address :: http://viper150.cafe24.com/trackback/209

You can also say.

Prev 1 Next
블로그 이미지
이것저것 불펌금지도 퍼다가 담습니다. 외부에 비공개된 페이지 입니다. By. 어른왕자

카테고리

  • 전체 (298)
    • 사는 이야기 (115)
    • 웹 프로그래밍 (102)
    • App 프로그래밍 (22)
    • IT 뉴스&기타 (22)
    • 박한별 (4)
    • 역사&기타지식 (9)

태그목록

  • 여자
  • 팝
  • 프레젠테이션 매거진
  • 남여관계
  • CRC32
  • 초경합금
  • 마녀사냥
  • ligagg
  • 윈도우7
  • Dialog Base
  • 개통이력
  • spring security
  • NWS
  • 훈장
  • vga성능
  • jQuery
  • 탕평책
  • 방화벽예외
  • 게임의자
  • 아이폰
  • C#
  • 갤럭시
  • 광개토대왕
  • 학술연구정보서비스
  • Ultraedit
  • Calendar
  • 환상의 커플
  • 부팅횟수 확인
  • 생생정보통
  • web.xml

최근에 올라온 글

  • 보험사의 조정신청 대응방법.
  • 어느 천재의 앞선 시선.
  • [병맛더빙] 누구게..... (1)
  • 韓경제 `회색 코뿔소` 상황...
  • SVN Connector 설치 URL.
  • 군대를 가지 않는 서울대생.
  • “운은 하늘의 귀여움 받는...
  • 목장에서 알바하다가 캐스...
  • [펌]믿고 거르는 관상.
  • 하루에 1세트씩 하면 좋다...

최근에 달린 댓글

  • <p align="center"><a href="h... 받아먹기 03/07
  • <p align="center"><a href="h... 라임애드 02/14
  • <div style="OVERFLOW: hidden... 고사니 02/12
  • <p align="center"><a href="h... 라임정보 02/07
  • <p><img src="https://i.imgur... 브레드 01/22

최근에 받은 트랙백

  • read this post from Bookie 7. read this post from Bookie 7 02/28
  • công ty may đồng phục. công ty may đồng phục 01/08
  • Israelnightclub`s recent blo... Israelnightclub`s recent blo.. 01/06
  • Suggested Browsing. Suggested Browsing 01/06
  • similar site. similar site 01/06

글 보관함

  • 2019/03 (1)
  • 2018/12 (1)
  • 2018/09 (1)
  • 2018/08 (1)
  • 2018/02 (1)

달력

«   2021/03   »
일 월 화 수 목 금 토
  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      

링크

  • Total : 263861
  • Today : 4
  • Yesterday : 26
Tattertools
Eolin
rss

어른왕자's blog is powered byTattertools1.1.2.2 : Animato