JAVA
[JAVA] HTML 태그 변환 방법!! (>,<,", ,&)
GoodDayDeveloper
2022. 3. 10. 15:07
반응형
데이터를 옮길때, 데이터에 특정 특수문자가 들어가면 데이터가 HTML 태그 그대로 나오게 됩니다.
그 이유는 XXS(Cross-site scripting)의 보안노출을 우려하여
웹 페이지에 렌더링이 되지 않고 HTML 태그 그대로 보여지게 되는거죠!
그래서 데이터의 특수문자를 치환하게 되면 웹 페이지에 잘 보여지게 됩니다.
위에 이미지에서의 데이터의 특수문자를 지환해주는 겁니다.
주로 이러한 작업은 마이그레이션(데이터 옮기는 작업)에 많이 사용됩니다.
특수문자를 태그로 변경 (> → >) 과 태그를 특수문자로 변경(> → >)
두가지를 정리해보았습니다.
특수문자를 태그로 변경 (> → >)
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;
}
|
cs |
태그를 특수문자로 변경 (> → >)
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;
}
|
cs |
반응형