는 다음 코드 세그먼트와 같이 컨트롤러 클래스가 html 마크 업만있는 index.jsp의 내용을 읽고 파싱하고 내용에 사용 된 태그에 대한 정보를 반환합니다. 수집 한 정보를 보는 방법을 살펴 보겠다.하지만 먼저 콘텐츠에 액세스하는 방법을 알 수 없었습니다. 자바에 익숙하지만 봄에 완전히 익숙합니다. 그래서 내 질문은 바보 같을 것이다. :) 정보를 얻기 위해 내가 알아낼 수없는 것은 HTML을 구문 분석하는 방법이 아니라 파일 내용을 얻는 방법입니다.스프링 MVC와 구문 분석 HTML
public class Main {
private static HTMLEditorKit.ParserCallback callback;
/**
* @param args
*/
public static void main(String[] args) {
try {
Reader r = new FileReader("D:/WS/TestP/resource/index.htm");
ParserDelegator parser = new ParserDelegator();
callback = new Detector();
parser.parse(r, callback, false);
} catch (Exception _ex) {
_ex.printStackTrace();
}
HashMap<String, Integer> map = ((Detector) callback).getMap();
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
String key;
ArrayList<TagFrequency> list = new ArrayList<TagFrequency>();
TagFrequency tf;
int i = 0, j = 0;
while (it.hasNext()) {
key = it.next();
i = map.get(key);
tf = new TagFrequency(key, i);
if (list.size() == 0)
list.add(tf);
else {
j = 0;
while (j < list.size() && tf.compareTo(list.get(j)) > 0) {
j++;
}
if (j==list.size())
list.add(tf);
else {
list.add(j, tf);
}
}
}
for (int ind = list.size(); ind>0 ; ind--) {
System.out.println(list.get(ind-1).toString());
}
}
}
Detector.java :
public class Detector extends HTMLEditorKit.ParserCallback {
private HashMap<String, Integer> map = new HashMap<String, Integer>();
public Detector() {
}
@Override
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
String str = t.toString();
if (map.get(str) == null) {
map.put(str, Integer.valueOf(1));
} else {
map.put(str, map.get(str) + 1);
}
}
public HashMap<String, Integer> getMap() {
return map;
}
}
및 TagFrequency.java :
이public class TagFrequency {
private String tag;
private Integer i;
public TagFrequency(String tag, Integer i) {
super();
this.tag = tag;
this.i = i;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Integer getI() {
return i;
}
public void setI(Integer i) {
this.i = i;
}
public String toString() {
return this.tag + " " + this.i;
}
public int compareTo(TagFrequency tf) {
if (tf.i > this.i)
return -1;
else if (tf.i < this.i)
return 1;
else
return (-1)*this.tag.compareToIgnoreCase(tf.tag);
}
}
만약에 그것의 어떤 안락, 그것의 하찮은 일은 PHP에서하십시오. :) – cletus