做了个简单的面包屑导航功能,比如页面上大家经常看到的这种导航:
您所在的位置:音乐社区-->用户模块-->用户注册
我做成了标签的形式,利用jom4j来解析xml文件:
核心类SiteMapTag:
package org.forever.tag;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* 站点导航标签的实现
* @author Administrator
*
*/
public class SiteMapTag extends TagSupport {
private static final long serialVersionUID = -3531938467909884528L;
private String currentFilePath;
private Element target;
@Override
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
currentFilePath = request.getRequestURI().replaceFirst(request.getContextPath(), "");
try {
Element root = (Element)pageContext.getServletContext().getAttribute("webSiteMapSet");
if(root==null){
SAXReader reader = new SAXReader();
InputStream inputStream = SiteMapTag.class.getClassLoader().getResourceAsStream("sitemap.xml");
Document document = reader.read(inputStream);
root = document.getRootElement();
pageContext.getServletContext().setAttribute("webSiteMapSet", root);
}
parseParent(root);
StringBuffer content = new StringBuffer("");
Listtitles = new ArrayList();
Listhrefs = new ArrayList();
while(target!=null){
Attribute attTitle = target.attribute("title");
if(attTitle!=null){
titles.add(attTitle.getText());
}
Attribute attHref = target.attribute("href");
if(attHref!=null){
hrefs.add(attHref.getText());
}else{
hrefs.add("");
}
target = target.getParent();
}
for (int i = titles.size()-1; i >=0; i--) {
String href = hrefs.get(i);
if(href.equals("")){
content.append(titles.get(i)+"-->");
}else{
content.append(""+titles.get(i)+"-->");
}
}
if(content.length()>0){
this.pageContext.getOut().println(content.delete(content.length()-6, content.length()));
}
} catch (Exception e) {
e.printStackTrace();
throw new JspException(e);
}
return super.doStartTag();
}
private void parseParent(Element parent){
Iteratorit = parent.elementIterator();
while(it.hasNext()){
Element temp = it.next();
Attribute attr = temp.attribute("path");
if(attr!=null){
if(attr.getText().equals(currentFilePath)){
target = temp;
return;
}
}
parseParent(temp);
}
}
}
sitemap.tld文件:
站点导航标签
myTaglib siteMap
1.1
tagUtil
http://tag.forever.org/jsp/tagutil/sitemap
面包屑标签
siteMap
org.forever.tag.SiteMapTag
empty
在项目的src下面添加sitemap.xml文件:
要使用的jsp加入标签指令:
在想放的位置处加上标签:
您所在的位置:就可以了。
sitemap.jar带源码。用的时候别忘了添加jom4j的支持。