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 8 article(s) for 'JSP'.

  1. 2015/12/07 spring 4 .... redirect
  2. 2015/11/18 request.getRealPath
  3. 2014/07/27 Eclipse Svn Connector 수동설치
  4. 2013/06/04 jsp 달력 예제
  5. 2013/06/04 jstl 함수 정리
  6. 2013/05/27 jsp UTF-8관련 개발
  7. 2013/04/16 JSP 날짜비교
  8. 2013/04/06 Simple Cross Site Scripting (XSS) Servlet Filter

spring 4 .... redirect

분류없음
2015/12/07 17:38
 
 @RequestMapping("/Member/CheckMember")
 public String doE(RedirectAttributes rttr){
     //logger.info("리다이렉트.....................");
 
   rttr.addFlashAttribute("msg", "이미 등록된 사용자 입니다.");
   return "redirect:/error";
 }
이올린에 북마크하기
TAG addFlashAttribute, java, JSP, redirect, RedirectAttributes, RequestMapping, spring
No received trackback. / No comment.

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

You can also say.

request.getRealPath

웹 프로그래밍
2015/11/18 17:47
 
request.getRealPath("/")

request.getSession().getServletContext().getRealPath("/")

큭.............. --;;;
이올린에 북마크하기
TAG getRealPath, java, JSP
Trackback 4 / No comment.

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

You can also say.

Eclipse Svn Connector 수동설치

웹 프로그래밍
2014/07/27 20:51
 
1. Help > Eclipse Marketplace.. 들어가서
2. SVN 으로 검색
3. Subversive - SVN Team Provider ... install
4. eclipse restart.. 여기서 SVN connector 설치 화면이 자동으로 실행이 안되면..
5. Windows > Preferences > Team > SVN 선택
  이때 SVN connector 가 설치가 안되어 있으면 설치하라는 화면이 뜬다..
6. SVN Kit 중에 버전 높은걸로 선택

이렇게 하면 일단 svn 접속이 가능한 상태가 된다.
그리고
Windows > Show View > Other... 를 선택하면
아래 SVN 메뉴가 있는 것을 확인 할 수 있다.


위에 5번으로 안될 경우
Help > Install New Software 에 들어가서

http://community.polarion.com/projects/subversive/download/eclipse/3.0/update-site/

입력 후 connector 를 설치할 수 있다.
이올린에 북마크하기
TAG eclipse, java, JSP, svn, svn connector
No received trackback. / No comment.

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

You can also say.

jsp 달력 예제

웹 프로그래밍
2013/06/04 16:10
 
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.util.Calendar"%>

<%
request.setCharacterEncoding("utf-8");
//Calender 클래스는 추상 클래스 이므로 객체생성이 되지 않는다.
//따라서 getInstance() 메서드를 이용하여 하위클래스의 객체를 생성하여 리턴한다.
//하위 클래스는 플랫폼의 나라 언어에 맞는 것을 자동으로 리턴해 줍니다.

//캘린더 객체 생성
Calendar cal = Calendar.getInstance();

//오늘 날짜 구하기
int nowYear=cal.get(Calendar.YEAR);
int nowMonth=cal.get(Calendar.MONTH)+1;

//월은 0부터 시작하므로 1월 표시를 위해 1을 더해 줍니다.
int nowDay=cal.get(Calendar.DAY_OF_MONTH);

//클라이언트가 선택하여 넘어온 날짜
String strYear=request.getParameter("year");
String strMonth=request.getParameter("month");

//표시할 달력의 년,월
int year=nowYear;
int month =nowMonth;

if(strYear!=null){// 값이 없으면
year=Integer.parseInt(strYear); //클라이언트가 선택한 값을 입력
}
if(strMonth!=null){// 값이 없으면
month=Integer.parseInt(strMonth); //클라이언트가 선택한 값을 입력
}

//전월 이동을 구하기
int preYear=year, preMonth=month-1;

if(preMonth<1){ //1월 전월은 작년 12월 이니깐...
preYear=year-1;
preMonth=12;
 }

//다음달 구하기
int nextYear=year,nextMonth=month+1;
if(nextMonth>12){ //12월 다음달은 내년 1월 이므로...
nextYear=year+1;
nextMonth=1;
}

//표시할 달력 세팅
cal.set(year,month-1,1); //년,월,일
int startDay=1;//달의 첫 날
int endDay=cal.getActualMaximum(Calendar.DAY_OF_MONTH);

//매년 해당월의 1일 구하기
int week =cal.get(Calendar.DAY_OF_WEEK);
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>달력 예제</title>
<style type="text/css">
table{text-align:center; background:#fff;}
table td{border:solid 1px #ccc}
.sun{color:red;}
.sat{color:blue;}
</style>
</head>
<body>

<table align="center" width="210" cellpadding="2" cellspacing="1">
<tr>
<td align="center">
  <a href="scheduleList2.jsp?year=<%=preYear %>&month=<%=preMonth %>">☜</a>
  &nbsp;<%=year %>년&nbsp;&nbsp;<%=month %>월
  <a href="scheduleList2.jsp?year=<%=nextYear %>&month=<%=nextMonth %>">☞</a>
</td>
</tr>
</table>

<!-- 달력표시 -->
<table align="center" width="210" cellpadding="0" cellspacing="1" bgcolor="#cccccc">
<tr>
<td class="sun">일</td>
<td>월</td>
<td>화</td>
<td>수</td>
<td>목</td>
<td>금</td>
<td class="sat">토</td>
</tr>
<%
//한주가 지나면 줄바꿈을 할 것이다.
int newLine=0;
out.print("<tr>");
for(int i=1; i < week; i++){
out.print("<td>&nbsp;</td>");
newLine++;
}
for(int i=startDay;i<=endDay;i++){ //1일 부터 말일까지 반복
String fontColor = (newLine == 0) ? "red" : (newLine == 6) ? "blue" : "black";
String bgColor = (nowYear == year) && (nowMonth == month) && (nowDay == i) ? "#e6e6e6" : "#fff";//오늘날짜음영
out.print("<td style='background:" + bgColor + "; color:" + fontColor + "'>" + i + "</td>");
newLine++;
if(newLine == 7 && i != endDay){ //7일째거나 말일이면 달력 줄바꿈이 일어난다.
out.print("</tr><tr>");
newLine=0;
}
} //3항 연산자로 for문으로 요일별 색상을 정한다.
 
while(newLine>0&&newLine<7){ //마지막날 이후 달력 채우기
out.print("<td>&nbsp;</td>");
newLine++;
}
out.print("</tr>");
%>
</table>

</body>
</html>

[출처] jsp 달력 예제|작성자 237

이올린에 북마크하기
TAG Calendar, JSP, 달력
No received trackback. / No comment.

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

You can also say.

jstl 함수 정리

웹 프로그래밍
2013/06/04 16:08
 

1 표현언어의 표현방식

$(expr}

2. 표현언어의 기본객체

pageContext :: PageContext 객체 .사용$(pageContext.request.requestURI}

pageScope :: page 범위에 포함된 속성 값에 접근

requestScope :: request 범위에 포함된 속성값에 접근 .사용$(requestScope.name}
sessionScope :: session 범위에 포함된 속성값에 접근
applicationScope :: application 범위에 포함된 속성값에 접근
param :: request.getParameter("aa")와 동일한 기능. 사용은 $(param.aa)
paramValues :: request.getParameterValues의 기능. $(paramValues.aa)
header :: request.getHeader('aa") 와 동일. $(header.aa)
headerValues :: request.getHeaderValues("aa")와 동일 $(headerValues.aa)
initParam :: 컨텍스트의 초기화 파라미터값
cookie :: 쿠키 정보에 접근
3.연산자
3.1 수치 연산자
+ : 덧셈
- :뺄셈
* :곱셈
/ or div :나눗셈
% or mod : 나머지
ex)
${"10"+1} =>11
$("일"+1} => 에러남 "일"이 숫자로 변경이 안되기 때문
${null +1} =>1 null은 0으로 처리
3.2 empty연산자
empty<값>
- 값이 null이면 true
- 빈문자열 true
- 길이가 0인배열 true
- 빈Map true
- 빈 Collection true
3.3 비교연산자 ,논리연산자 , 비교선택연산자(?:) ->자바연산자와 동일
4.JSTL이 제공하는 태크 종류
라이브러리하위기능접두어관련 URL
코어변수지원 , 흐름제어 , URL처리chttp://java.sun.com/jsp/jstl/core
XMLXML 코어 , 흐름제어 , XML변환xhttp://java.sun.com/jsp/jstl/xml
국제화지역 , 메시지 형식 , 숫자및 날짜형식fmthttp://java.sun.com/jsp/jstl/fmt
데이터베이스SOLsqlhttp://java.sun.com/jsp/jstl/sql
함수콜렉션처리 , String 처리fnhttp://java.sun.com/jsp/jstl/functions
-코어,함수 라이브 러리가 자주 사용되며 ,접두어는 다른접두어를 사용해도 상관없다.
- 필요한 jar 파일: jstl.jar , standard.jar (다운받는 방법 : http://www.cyworld.com/love82u/3054391)
4.1 코어태그(가장 많이 사용)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
기능분류태그설 명
변수지원setJSP에서 사용될 변수 설정
remove설정한 변수 제거
흐름제어if조건에 따라 내부코드수행
choose다중조건을처리
forEach콜렉션이나 Map의 항목처리시사용
forTokens구분자로 분리된 각각의 토근을 처리할때 사용
URL 처리importURL을 사용하여 다른자원의 결과삽입
redirect지정한 결로로 리다이렉트한다
urlurl재작성
기타태그catch예외처리에 사용
outJspWriter에 내용을 알맞게 처리후 출력
4.1.1변수지원
● set 태그(변수선언)
- <c:set var="varName" scope="session" value="someValue">
: c - > 접두어(선언된 접두어를 입력하면됨)
: var -> 값을 지정할 변수
: scope -> 변수를 지정한 영역 (page , request, session , application)
: value -> 변수의 값 지정
<c:set var="varName" scope="session"> <!--이런식으로 몸체에 값을 입력할 수도있다.
someValue
</c:set>
map 및 객체
: var를 target로 , property 선언후 똑같이 사용
● remove 태그(선언된 변수 삭제)
<c:remove var="varName" scope="session/>
4.1.2 흐름제어 태그(제일 많이 사용)
● if태그(java의 if와 같은 하지만 if-else의 효과는없음)
<c:if test="조건">
</c:if>
● choose 태그
<c:choose >
<c:when test="${num>10 && num<15}">
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
● forEach 태그(java의 for, do-while등등)
- 배열 , collection 또는 Map에 저장되어 있는 값 순차적으로 처리
<c:forEach var ="i" begin="1" end="100" step="2">
</c:corEach>
<c:forEach var ="i" items="${inarr}" begin="2" end="4">
[${i}]
</c:forEach>

<c:forEach var ="i" items="${map}">
${i.key} = ${i.value}</br>
</c:forEach>
● forTokens 태그(java의 java.util.StringTokenizer같은 기능제공)
<c:forTokens var="token" items"문자열" delims="구분자">
${token}
</c:forTokens>
4.1.3 URL 처리태그
● import(<jsp:include>와 같은기능)
-import와 <jsp:include>의 차이점으로는 import 태그는 같은 웹 어플리케이션 디렉터리에 포함되지 않았더라도 그리고 심지어 같은 서버에 있지 않은 자원에대해서도 접근가능
- 주의해야할 사항 : import태크를 사용한다고해서 읽어온 내용이 곧바로 import태그 위치에 포함되지 않는다는점.
<c:import url=http://media.daum.net charEncoding="euc-kr" var="daumNews" scope="request">
<c:param name="_top_G" value="news"/>
</c:import>
url : 읽어올 URL
charEncoding : 읽어 온 데이테의 캐릭터 셋
var : 읽어온 데이터를 저장할 변수명
scope : 변수를 저장할 범위 지정
-위와 같이읽어온 데이터를 var="daumNews"에 저장하기 때문에 곧바로 import 위치에 포함되지 않는다. 또한 읽어온 데이터를 쉽게 원하는 형태로 변경이 가능하다.
● url태그
- url을 생성하여 변수에 저장할때 사용
<c:url var="url1" value="/shopping.do" scope="session">
<c:param name="Add" value="isdn-001"/>
</c:url>
url : 생성한 URL이 저장될 변수
value : 생성할 url
scope : 변수를 저장할 범위 지정
● redirect 태그(response.sendRedirect와 비슷한기능)
- 지정한 페이지로 리다이렉트할때 사용
<c:redirect url="/ifTag.jsp">
<c:param name="name" value="bk"/>
</c:redirect>
4.1.4 기타태그
● out 태그
- JspWriter에서 데이터를 출력할때 사용
<c:out value="value" escapeXml="{true|false}" default="defaultValue"/>
value : JspWriter에 출력할 값을 나타냄
escapeXml : 이속성의 값이 true일경우 아래의 문자변경 ,생략가능
문자변환된 형태
<&lt;
>&gt;
&&amp;
'&#039;
'"&#034;
default : value 속성에서 지정한 값이 존재하지 않을때 사용될 값을 지정
● catch 태그
- 예외가 발생할때 사용되는 태그
<c:catch var="exName">
</c:catch>

fn:substringBefore , fn:substringAtter

파일 이름만 가져오고 싶었는데  lastIndexOf 를 써봐도 안됨.

jstl 함수에는 lastIndexOf가 없다

대신  fn:substringBefore , fn:substringAtter 존재


<c:set var="name" value="son01.gif />
${fn:substringBefore( name ,'.')}
<c:out value="${name}" />


결과 -> son01


<img src="${pageContext.request.contextPath}${ImgUrlPath}thumb/${fn:substringBefore(list.FILE_SAVE_NAME,'.')}<s:message code='board.thumb.backName' />.<s:message code='board.thumb.extension' />" alt="" />



fn:split

예) 02-123-4567 이란 값을 split 처리 할 경우 배열의 순서값으로 찾아서 처리 함.

${fn:split(list.TEL,'-')[1]} - ${fn:split(list.TEL,'-')[2]}

[출처] jstl 함수 정리2|작성자 237


${header.Host}
${header["User-Agent"]}
${headerValues.Accept[0]}    : Accept=>헤더이름 , [0]=>인텍스
${headerValues["Users-Data"][1] : Users-Data=>헤더이름 , [1]=>인텍스

${cookie.CART}   : CART=>쿠키이름
${cookie["User_Name"]} : User_Name=>쿠키이름
${cookie.CART.value} : CART=>쿠키이름 Cart의 값을 가져오라
${cookie["CART"]["value"]} : CART=>쿠키이름 Cart의 값을 가져오라
${cookie.CART["value"]}
${cookie["CART"].value}
${cookie.CART.domain}
${cookie.CART["path"]}
${cookie.CART["maxAge"]}

${initParam.PARAM_NAME}
${initParam["PARAM_NAME"]}

[출처] jstl 함수 정리|작성자 237

이올린에 북마크하기
TAG JSP, jstl
No received trackback. / No comment.

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

You can also say.

jsp UTF-8관련 개발

웹 프로그래밍
2013/05/27 10:19
 

OKJSP( http://www.okjsp.pe.kr/seq/72792 )

1. 모든 문서는 UTF-8 인코딩으로 저장되어야 합니다.

에디트 플러스의 경우 도구 -> 기본설정 -> 파일 부분에서 새 파일 형식을

UTF-8 로 해놓음으로써 새파일 작성시 UTF-8을 기본으로 작성할수 있고,

이미 다른 인코딩 타입에서 작성된 문서인 경우 내용을 모조리 Ctrl+C로 복사후

문서 -> 인코딩 변경 로드에서 UTF-8로 변경후 다시 붙여넣기 하면 됩니다.


이클립스의 경우 Package Explorer 에서 프로젝트에서 우측 버튼을 누른 후

Properties->Info->Text file encoding->Other 을 UTF-8 로 잡아주면 됩니다.

( 기존 다른 인코딩 타입에서 작성된 문서 내부 한글은 모조리 깨지게 됨 )


2. jsp 파일 상단에는 다음과 같은 방식으로 UTF-8 설정합니다.

<%@ page contentType = "text/html;charset=utf-8" %>


3. 서블릿은 다음과 같은 방식으로 UTF-8을 설정합니다.

request.setCharacterEncoding("utf-8")


4. 자바스크립트에서 encodeURIComponent 처리 및 톰캣 server.xml 의 설정 변경

위 1,2,3번의 방식으로 하면 post 방식의 데이터는 잘 받지만

get 방식의 데이터는 한글이 깨집니다.

이와 같은 경우 자바스크립트의 encodeURIComponent 함수와

server.xml 을 이용하여 처리하면 됩니다.


4.1 server.xml

톰캣 폴더의 conf 폴더에는 server.xml 파일이 존재합니다.

에디터로 열어보면


예)

    <Connector port="8080" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" />


값이 약간 틀릴수 있지만 초기 셋팅 값이 보통 저러하고,

Connector 은 초기에 2개가 있는데 8080 포트 부분을 수정하면 됩니다.

수정하는 방법은

URIEncoding="UTF-8" 을 추가하면 됩니다.


예)

    <Connector port="8080" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="utf-8" />


위와 같이 했다고 해결되는 것은 아닙니다. get 방식으로 데이터를 전송하면

자바 파일에서 확인 했을 경우 물음표 값만 넘어옵니다.


get 방식으로 보낼 경우 자바스크립트로 변환을 해줍니다.

예를 들어 "한글"을 자바스크립트에서

<SCRIPT>alert( encodeURIComponent("한글") )</SCRIPT>

처럼 encodeURIComponent 함수로 변환하게 되면 %ED%95%9C%EA%B8%80 으로

변환됩니다. 이 값을 주소에 "한글" 대신에 넣게 되면 자바에서 알아서 잘~ 받습니다 ^^

[출처] [본문스크랩] [스크랩][인코딩] UTF-8관련 개발|작성자 일리




utf-8 인코딩을 이용한 한글 url 처리
[ 조회수: 393 ]
 

개요

  • utf-8 은 유니코드를 위한 가변길이 문자 인코딩 방식중 하나로 켄 톰프슨과 롭 파이크가 만들었다.
  • 유니코드 한문자를 표시하기 위해 1byte~4byte 까지 가변적으로 표현한다.
  • U+0000부터 U+007F 범위에 있는 아스키 문자들은 UTF-8에서 1바이트만으로 표시된다. 4바이트로 표현되는 문자는 모두 기본 다중언어 평면(BMP) 바깥의 유니코드 문자이며, 거의 사용되지 않는다.

구조

  • U+007F(0~127) 까지의 문자는 7비트 아스키 문자와 동일하게 표시된다.
  • U+007F 이후의 문자는 4byte 까지의 비트 패턴으로 표시되며 7비트 아스키 문자와 혼동되지 않게 하기 위해 모든 바이트의 최상위 비트는 1 이다.
코드 범위UTF-16BE 표현UTF-8 표현설명
000000 ~00007F00000000 0xxxxxxx0xxxxxxx아스키와 동일한 범위
000080 ~0007FF00000xxx xxxxxxxx110xxxxx 10xxxxxx첫바이트는 110 으로 시작하고, 나머지 바이트는 10으로 시작함
000800 ~00FFFFxxxxxxxx xxxxxxxx1110xxxx 10xxxxxx 10xxxxxx첫바이트는 1110으로 시작하고 , 나머지는 10으로 시작함
010000 ~10FFFF110110yy yyxxxxxx 110111xx xxxxxxxx11110zzz 10zzxxxx 10xxxxxx 10xxxxxxUTF-16 "surrogate pair" 영역(yyyy=zzzzz -1)


utf-8 인코딩 예제

'위'(한글) --> U+C7404(유니코드)
U+0800부터 U+FFFF 사이의 영역에 있으므로, 표에 따라 1110xxxx 10xxxxxx 10xxxxxx 형식으로 인코딩
C704(16진수) --> 1100-0111-0000-0100(2진수) --> 11101100 10011100 10000100(utf-8 인코딩)
결과적으로 이 문자는 3바이트로 인코딩 되면 16진수로 표기하면 EC 9C 84가 된다.

(첫 128 문자는 1바이트로 표시되고, 그 다음 1920 문자 (판독 기호가 붙은 라틴 문자, 그리스 문자, 키릴 문자, 콥트 문자, 아르메니아 문자, 
히브리 문자, 아랍 문자)는 2바이트로 표시되며, 나머지 문자들 중 BMP 안에 들어 있는 것은 3바이트, 아닌 것은 4바이트로 표시된다.)

관련자료

  • ksc5601 문자셋 
  • cp949변환테이블 

utf-8 체크

    1. 입력된 문자열이 utf-8로 인코딩 되었는지 하기 위해서는 utf-8 의 인코딩 패턴을 조사한다. 즉 바이트 배열의 패턴이 utf-8 인코딩 패턴(1110xxxx 10xxxxxx 10xxxxxx)과 맞는지를 비교한다.
    2. 000080 ~0007FF 범위의 110xxxxx 10xxxxxx 패턴 일 경우엔 중복되는 코드값으로 인해 utf-8 인코딩인지 아닌지 체크하는것은 사실상 불가능하다.
      110xxxxx 10xxxxxx 패턴의 utf-8 판독

      110xxxxx 10xxxxxx 패턴의 코드일 경우 utf-8로 인코딩 되었는지 아닌지를 확인하는것은 사실상 불가능하다. 
      하지만 utf-8로 인코딩 되면 아스키 영역은 1byte 한글은 3byte 내지는 4byte를 사용하므로 단순하게 생각하여 2 바이트 110xxxxx 10xxxxxx 패턴의 경우는 utf-8 인코딩이 아님을 유추할수 있다. 
      판독 기호가 붙은 라틴 문자, 그리스 문자, 키릴 문자, 콥트 문자, 아르메니아 문자, 히브리 문자, 아랍 문자 등이 입력되면 판독 오류가 발생하겠지만 이는 무시해도 좋을듯 하다.

    3. Null 값의 경우 자바에서는 변형된 utf-8 인코딩 방식에 따라 1byte가 아닌 2byte(11000000 10000000)로 표기하므로 110xxxxx 10xxxxxx 의 경우 null 인지 비교해야 정확한 판독이 가능하지만 입력된 값의 인코딩여부를 판독하므로 상황에 따라서는 무시해도 괜찮을듯 하다.
    4. CJK 2바이트+한글 2바이트 가 '1110xxxx 10xxxxxx 10xxxxxx 0xxxxxxx' 와 같은 패턴으로 utf-8 3바이트 와 아스키1바이트 조합과 유사할 경우 앞자리 3바이트를 유니코드 형태로 역치환 해서 000800 ~00FFFF 범위가 맞는지 체크한다.

utf-8 인코딩 체크 예제

utf-8 인코딩 판독 예제

1. '위'.getBytes("ISO-8859-1") : -20 , -100, -124
2. unsigned byte = 236, 156, 132
3. 16진수 : EC , 9C, 84
4. 2진수 : 11101100 10011100 10000100
5. urf-8 패턴제거: 00001100 00011100 00000100 
6. 유니코드 타입으로 치환 : 00001100<<12 + 0011100<<6 + 00000100 = 11000000 00000100 
7. 16진수 : 000800 <= 00E704 =< 00FFFF

package util;

import java.io.UnsupportedEncodingException;

/** 
 *  <pre>
 *  작성자 : 이종희 (qola@naver.com)
 *  JAlbum.com (http://jalbum.net/download.jsp?ref=list) 소스 참고함.   
 *  <b>특정 문자열이 utf-8 인코딩인지 아닌지 체크한다.</b>
 * 
 *  utf-8 인코딩 패턴인  110xxxxx 10xxxxxx , 1110xxxx 10xxxxxx 10xxxxxx 인지 비교한다.
 *  2바이트 (110xxxxx 10xxxxxx) 패턴의 유니 코드 중복으로 인해 100% 검증할수 없지만 
 *  한글의 경우 3byte 로 표기 되므로  2바이트 패턴일 경우 utf-8 인코딩이 아닌것으로 간주한다.
 *  
 *  따라서 000080 ~0007FF 영역의 라틴 문자, 그리스 문자, 키릴 문자, 콥트 문자, 
 *  아르메니아 문자, 히브리 문자, 아랍 문자 등은 utf-8 인코딩을 비교할수 없다. 
 *  
 *  수정된 utf-8의 의한 null값 \u0000 은 11000000 10000000 로 표기되지만 무시하기로 한다.
 *  
 *  </pre>
 */

public class UTFUtil {
	   
	
	public static boolean isUTF8(String str) throws Exception{
		byte[] bytes=str.getBytes("ISO-8859-1");
		return isUTF8(bytes,0,bytes.length);
	}
	   
	public static boolean isUTF8(byte[] buf, int offset, int length) {

	       boolean yesItIs = false;
	       for (int i=offset; i<offset+length; i++) {
	          if ((buf[i] & 0xC0) == 0xC0) { // 11xxxxxx 패턴 인지 체크 
	             int nBytes;
	             for (nBytes=2; nBytes<8; nBytes++) {
	                int mask = 1 << (7-nBytes);
	                if ((buf[i] & mask) == 0) break;
	             }
	            
                      //CJK영역이나 아스키 영역의 경우 110xxxxx 10xxxxxx 패턴으로 올수 없다.
	             if(nBytes==2) return false;
	             
	             // Check that the following bytes begin with 0b10xxxxxx
	             for (int j=1; j<nBytes; j++) {
	                if (i+j >= length || (buf[i+j] & 0xC0) != 0x80) return false;
	             }
                
                if(nBytes==3){
                	// 유니코드 형태로 역치환 해서 0x0800 ~ 0xFFFF 사이의 영역인지 체크한다. 
                    char c = (char) (((buf[i] & 0x0f) << 12) + ((buf[i+1] & 0x3F) << 6) + (buf[i+2] & 0x3F));
                    if(!(c >= 0x0800 && c <= 0xFFFF)){
                        return false;
                    }	                	
                }
	                
	             yesItIs = true;
	          }
	       }
	       return yesItIs;
	 }
	    
}


 



한글 URL 사용시 문제 발생 케이스

  • IE에는 유니코드 지원을 위해 기본적으로 URL을 UTF-8 로 전송해 주지만 옵션 사항이므로 사용자 마다 환경이 다를수 있다.
  • utf-8로 다시 보내는 기능을 제공하지 않는 브라우저도 존재한다.
  • RSS 리더와 같은 별도의 클라이언트를 사용할경우 서버인코딩, 클라이언트, 브라우저 인코딩 이 모두 일치하여야만 한다.

해결책

  • REQUEST 요청시 URL이 UTF-8 인코딩 방식인지 아닌지를 체크하여 UTF-8 방식이면 "ISO-8859-1 --> UTF-8" 형태로 인코딩 변환을 해주고 그렇지 않으면 "ISO-8859-1 --> MS949" 로 인코딩 변환을 시켜준다.

구현 예제

  • APACHE MOD_REWRITE
    • 아래 예와 같이 MOD_REWRITE를 이용해 특정 패턴의 URL을 REWRITE 시킨다.
      RewriteEngine   on
          # // http://tag.naver.com/tag2/한글 --> http://tag.naver.com/tag/index.jsp?tag=한글
          RewriteRule ^/tag2/(.+)$  /tag/index.jsp?tag=$1 [PT]
  • JSP 샘플
    • isUTF8() 체크 메소드를 이용해 파라메터의 인코딩을 각각 처리해준다.
      <%@page language="java" contentType="text/html;charset=utf-8"%>
      <%@page import="java.net.URLEncoder, util.*" %>
      
      <html>
      <head>
      	<meta http-equiv="Content-type" content="text/html; charset=utf-8">
      </head>
      
      <body>
        index.jsp... <br>
        
        <%
          String uri=request.getRequestURL().toString();
        	String tag=request.getParameter("tag");
        	byte[] tagBytes=tag.getBytes("ISO-8859-1");
        	
        	out.println("byte[]===");
        		for(int i=0;i<tagBytes.length;i++){
        			out.println(tagBytes[i]+",");
        		}
        	out.println("<br>");  
        	
        	boolean isUTF8=UTFUtil.isUTF8(tag);
        	
        	if(isUTF8) {
        		out.println(util.Enco.toUtf(tag));
        		out.println("<br>");
        		out.println(isUTF8);
        		
        	}else{ 
        		out.println(new String(tag.getBytes("ISO-8859-1"),"ms949"));
        		out.println("<br>");
        		out.println(isUTF8);
        	}
        %>
        
        <a href="http://tag_test.com/tag2/한글">http://tag_test.com/tag2/한글</a><br>
        <a href="http://tag_test.com/tag2/코리아">http://tag_test.com/tag2/코리아</a><br>
        <a href="http://tag_test.com/tag2/위">http://tag_test.com/tag2/위</a>
      </body>
      </html>

      [출처] [본문스크랩] [스크랩][인코딩] UTF-8관련 개발|작성자 일리


이올린에 북마크하기
TAG JSP, tomcat, UTF-8
No received trackback. / No comment.

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

You can also say.

JSP 날짜비교

웹 프로그래밍
2013/04/16 18:14
 

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import="java.util.Calendar"%>
<%@ page import="java.util.Date"%>
<%@ page import="java.text.DecimalFormat"%>
<%@ page import="java.text.SimpleDateFormat" %>
<%!
public static String getdate(int mountdate){
   DecimalFormat df = new DecimalFormat("00");
   Calendar calendar = Calendar.getInstance();
   calendar.add(calendar.DATE, mountdate);
   String year = Integer.toString(calendar.get(Calendar.YEAR));
   String month = df.format(calendar.get(Calendar.MONTH) + 1);
   String day = df.format(calendar.get(Calendar.DATE));
   String date = year + "-" + month + "-" + day;
   return date;
}

public static int fnDateDiff(String stDate,String etDate){
 long d1,d2;
 Calendar c1 = Calendar.getInstance();
 Calendar c2 = Calendar.getInstance();
 String[] arr1 = stDate.split("-");
 String[] arr2 = etDate.split("-");
 c1.set(Integer.parseInt(arr1[0]),Integer.parseInt(arr1[1]),Integer.parseInt(arr1[2]));
 c2.set(Integer.parseInt(arr2[0]),Integer.parseInt(arr2[1]),Integer.parseInt(arr2[2]));
 d1 = c1.getTime().getTime();
 d2 = c2.getTime().getTime();

 int days =(int)((d2-d1)/(1000*60*60*24));
 return days;
}
%>
<%@ include file="socket.jsp" %>
<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires",0);
if (request.getProtocol().equals("HTTP/1.1")){
 response.setHeader("Cache-Control", "no-cache");
}

String sig_req_id = request.getParameter("sig_req_id");
Cookie[] cookies=request.getCookies();
String userDomain = "";
 
if(cookies !=null && cookies.length > 0){
 for(int i=0; i<cookies.length; i++){
  if( cookies[i].getName().equals("UD") ){
   userDomain = cookies[i].getValue();
  }
 }
}else{
 userDomain = "localhost";
}
String [] result = GetIsignData(sig_req_id,userDomain);
String nowDate = getdate(0);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="No-Cache">
</head>
<script type="text/javascript">
function init(){
 <% if( fnDateDiff(result[4],nowDate) >= 0 ){ %>
  parent.fnHndSingSocket('', '', '9999', '', '', '');  
 <% } else { %>
  parent.fnHndSingSocket('<%=result[0]%>', '<%=result[1]%>', '<%=result[2]%>', '<%=result[3]%>', '<%=result[4]%>', '<%=result[5]%>');
 <% } %>
}
init();
</script>
</html>

이올린에 북마크하기
TAG JSP, 날짜비교
No received trackback. / No comment.

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

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)

태그목록

  • 날짜비교
  • C언어
  • Image Buttron
  • 오픈오피스
  • tiles
  • Fishbowl
  • gts650
  • 히든메뉴
  • 갤럭시
  • 생산성
  • benchmark
  • 아이폰
  • 전업남편
  • PC일체형의자
  • hiddenmenu
  • 미국의료
  • 놀람
  • 카라타 에리카
  • MenuBar
  • 삼성
  • Billy Joel
  • mysql
  • 얻은것
  • 노트5
  • 탬버린
  • 울트라에디터
  • XSS
  • BHO
  • 디렉토리구조
  • Servlet

최근에 올라온 글

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

최근에 달린 댓글

  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22

최근에 받은 트랙백

  • 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
  • לאתר הבית שלנו. לאתר הבית שלנו 01/06

글 보관함

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

달력

«   2021/01   »
일 월 화 수 목 금 토
          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 : 261968
  • Today : 1
  • Yesterday : 42
Tattertools
Eolin
rss

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