1. jquery를 이용한 변환 방법 (XSS 공격에 취약함)
$('<div/>').text('> 특수문자 처리 <').html();
2. 안전한 변환 방법
function decodeHTMLEntities (str) {
if(str !== undefined && str !== null && str !== '') {
str = String(str);
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
var element = document.createElement('div');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
특수문자를 태그로 변경 (> → >)
특수문자를 태그로 변경 (> → >)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public static String toReplace(String str) {
if(str == null) {
return null;
}
String returnStr = str;
returnStr = returnStr.replaceAll("<br>", "\n");
returnStr = returnStr.replaceAll(">", ">");
returnStr = returnStr.replaceAll("<", "<");
returnStr = returnStr.replaceAll(""", "");
returnStr = returnStr.replaceAll(" ", " ");
returnStr = returnStr.replaceAll("&", "&");
return returnStr;
}
|
태그를 특수문자로 변경(> → >)
태그를 특수문자로 변경 (> → >)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
public static String getReplace(String srcString) {
String rtnStr = null;
try{
StringBuffer strTxt = new StringBuffer("");
char chrBuff;
int len = srcString.length();
for(int i = 0; i < len; i++) {
chrBuff = (char)srcString.charAt(i);
switch(chrBuff) {
case '<':
strTxt.append("<");
break;
case '>':
strTxt.append(">");
break;
case '&':
strTxt.append("&");
break;
default:
strTxt.append(chrBuff);
}
}
rtnStr = strTxt.toString();
}catch(Exception e) {
e.printStackTrace();
}
return rtnStr;
}
|
'두번째 프로젝트 이야기' 카테고리의 다른 글
두 날짜 입력 요소 사이의 유효성 (0) | 2023.11.14 |
---|---|
oninput (0) | 2023.10.25 |
정규표현식-시분초 (0) | 2023.10.23 |
[mybatis] include refid(반복되는 쿼리 묶기!) (0) | 2023.10.06 |
이벤트 바인딩 (0) | 2023.10.05 |