使用jsp和tld实现javaweb开发

TLD文件的解释术语:

标签库描述文件,用于存放标签名字和类的映射用的

标签库:它把类标签和后面的Java类映射起来,它减少了页面的代码,使页面更加的清晰,其实标签最后还是被解释成后台的java代码

原理是,在用户在jsp页面中使用标签时,系统首先会先到xml文件中的 标签中的《taglib-uri》和《taglib-location》这两对标签找到相对应的扩展名为tld文件,然后在 tld文件中的映射再找到相对应的taglib类。

创建的每个标签都必须在tld文件中声明,如果要在jsp页面用jsp的标签,必先先实现定义标签的类,然后在标签库描述文件(TLD)中将写好的类映射成jsp标签,然后在jsp页面中使用定义好的标签,然后就可以实现动态的jsp信息。
当需要使用自定义标签时就需要配置xml文件和tld文件
1、书写要配置的java代码:

/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.newtouch.modules.cms.utils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.ui.Model;

import com.google.common.collect.Lists;
import com.newtouch.common.config.Global;
import com.newtouch.common.mapper.JsonMapper;
import com.newtouch.common.persistence.Page;
import com.newtouch.common.utils.CacheUtils;
import com.newtouch.common.utils.SpringContextHolder;
import com.newtouch.common.utils.StringUtils;
import com.newtouch.modules.cms.entity.Article;
import com.newtouch.modules.cms.entity.Category;
import com.newtouch.modules.cms.entity.Link;
import com.newtouch.modules.cms.entity.Site;
import com.newtouch.modules.cms.service.ArticleService;
import com.newtouch.modules.cms.service.CategoryService;
import com.newtouch.modules.cms.service.LinkService;
import com.newtouch.modules.cms.service.SiteService;

/**
 * 内容管理工具类
 * @author ThinkGem
 * @version 2013-5-29
 */
public class CmsUtils {
	
	private static SiteService siteService = SpringContextHolder.getBean(SiteService.class);
	private static CategoryService categoryService = SpringContextHolder.getBean(CategoryService.class);
	private static ArticleService articleService = SpringContextHolder.getBean(ArticleService.class);
	private static LinkService linkService = SpringContextHolder.getBean(LinkService.class);
    private static ServletContext context = SpringContextHolder.getBean(ServletContext.class);

	private static final String CMS_CACHE = "cmsCache";
	
	/**
	 * 获得站点列表
	 */
	public static List<Site> getSiteList(){
		@SuppressWarnings("unchecked")
		List<Site> siteList = (List<Site>)CacheUtils.get(CMS_CACHE, "siteList");
		if (siteList == null){
			Page<Site> page = new Page<Site>(1, -1);
			page = siteService.findPage(page, new Site());
			siteList = page.getList();
			CacheUtils.put(CMS_CACHE, "siteList", siteList);
		}
		return siteList;
	}
	
	/**
	 * 获得站点信息
	 * @param siteId 站点编号
	 */
	public static Site getSite(String siteId){
		String id = "1";
		if (StringUtils.isNotBlank(siteId)){
			id = siteId;
		}
		for (Site site : getSiteList()){
			if (site.getId().equals(id)){
				return site;
			}
		}
		return new Site(id);
	}
	
	/**
	 * 获得主导航列表
	 * @param siteId 站点编号
	 * @param project 项目名称
	 */
	public static List<Category> getMainNavList(String siteId,String project){
		@SuppressWarnings("unchecked")
		List<Category> mainNavList = (List<Category>)CacheUtils.get(CMS_CACHE, "mainNavList_"+siteId);
//		if (mainNavList == null){*/
			Category category = new Category();
			category.setSite(new Site(siteId));
			category.setParent(new Category("1"));
			category.setInMenu(Global.SHOW);
			category.setProject(project);
			Page<Category> page = new Page<Category>(1, -1);
			page = categoryService.find(page, category);
			mainNavList = page.getList();
			CacheUtils.put(CMS_CACHE, "mainNavList_"+siteId, mainNavList);
//		}
		return mainNavList;
	}
	
	/**
	 * 获取栏目
	 * @param categoryId 栏目编号
	 * @return
	 */
	public static Category getCategory(String categoryId){
		return categoryService.get(categoryId);
	}
	
	/**
	 * 获得栏目列表
	 * @param siteId 站点编号
	 * @param parentId 分类父编号
	 * @param number 获取数目
	 * @param param  预留参数,例: key1:'value1', key2:'value2' ...
	 */
	public static List<Category> getCategoryList(String siteId, String parentId, int number, String param){
		Page<Category> page = new Page<Category>(1, number, -1);
		Category category = new Category();
		category.setSite(new Site(siteId));
		category.setParent(new Category(parentId));
		if (StringUtils.isNotBlank(param)){
			@SuppressWarnings({ "unused", "rawtypes" })
			Map map = JsonMapper.getInstance().fromJson("{"+param+"}", Map.class);
		}
		page = categoryService.find(page, category);
		return page.getList();
	}

	/**
	 * 获取栏目
	 * @param categoryIds 栏目编号
	 * @return
	 */
	public static List<Category> getCategoryListByIds(String categoryIds){
		return categoryService.findByIds(categoryIds);
	}
	
	/**
	 * 获取文章
	 * @param articleId 文章编号
	 * @return
	 */
	public static Article getArticle(String articleId){
		return articleService.get(articleId);
	}
	
	/**
	 * 获取文章列表
	 * @param siteId 站点编号
	 * @param categoryId 分类编号
	 * @param number 获取数目
	 * @param param  预留参数,例: key1:'value1', key2:'value2' ...
	 * 			posid	推荐位(1:首页焦点图;2:栏目页文章推荐;)
	 * 			image	文章图片(1:有图片的文章)
	 *          orderBy 排序字符串
	 * @return
	 * ${fnc:getArticleList(category.site.id, category.id, not empty pageSize?pageSize:8, 'posid:2, orderBy: \"hits desc\"')}"
	 */
	public static List<Article> getArticleList(String siteId, String categoryId, int number, String param){
		Page<Article> page = new Page<Article>(1, number, -1);
		Category category = new Category(categoryId, new Site(siteId));
		category.setParentIds(categoryId);
		Article article = new Article(category);
		if (StringUtils.isNotBlank(param)){
			@SuppressWarnings({ "rawtypes" })
			Map map = JsonMapper.getInstance().fromJson("{"+param+"}", Map.class);
			if (new Integer(1).equals(map.get("posid")) || new Integer(2).equals(map.get("posid"))){
				article.setPosid(String.valueOf(map.get("posid")));
			}
			if (new Integer(1).equals(map.get("image"))){
				article.setImage(Global.YES);
			}
			if (StringUtils.isNotBlank((String)map.get("orderBy"))){
				page.setOrderBy((String)map.get("orderBy"));
			}
		}
		article.setDelFlag(Article.DEL_FLAG_NORMAL);
		page = articleService.findPage(page, article, false);
		return page.getList();
	}
	
	/**
	 * 获取链接
	 * @param linkId 文章编号
	 * @return
	 */
	public static Link getLink(String linkId){
		return linkService.get(linkId);
	}
	
	/**
	 * 获取链接列表
	 * @param siteId 站点编号
	 * @param categoryId 分类编号
	 * @param number 获取数目
	 * @param param  预留参数,例: key1:'value1', key2:'value2' ...
	 * @return
	 */
	public static List<Link> getLinkList(String siteId, String categoryId, int number, String param){
		Page<Link> page = new Page<Link>(1, number, -1);
		Link link = new Link(new Category(categoryId, new Site(siteId)));
		if (StringUtils.isNotBlank(param)){
			@SuppressWarnings({ "unused", "rawtypes" })
			Map map = JsonMapper.getInstance().fromJson("{"+param+"}", Map.class);
		}
		link.setDelFlag(Link.DEL_FLAG_NORMAL);
		page = linkService.findPage(page, link, false);
		return page.getList();
	}
	
	// ============== Cms Cache ==============
	
	public static Object getCache(String key) {
		return CacheUtils.get(CMS_CACHE, key);
	}

	public static void putCache(String key, Object value) {
		CacheUtils.put(CMS_CACHE, key, value);
	}

	public static void removeCache(String key) {
		CacheUtils.remove(CMS_CACHE, key);
	}

    /**
     * 获得文章动态URL地址
   	 * @param article
   	 * @return url
   	 */
    public static String getUrlDynamic(Article article) {
        if(StringUtils.isNotBlank(article.getLink())){
            return article.getLink();
        }
        StringBuilder str = new StringBuilder();
//        str.append(context.getContextPath()).append(Global.getFrontPath());
        str.append(Global.getFrontPath());
        str.append("view-").append(article.getCategory().getId()).append("-").append(article.getId()).append(Global.getUrlSuffix());
        return str.toString();
    }

    /**
     * 获得栏目动态URL地址
   	 * @param category
   	 * @return url
   	 */
    public static String getUrlDynamic(Category category) {
        if(StringUtils.isNotBlank(category.getHref())){
            if(!category.getHref().contains("://")){
//                return context.getContextPath()+Global.getFrontPath()+category.getHref();
                return Global.getFrontPath()+category.getHref();
            }else{
                return category.getHref();
            }
        }
        StringBuilder str = new StringBuilder();
//        str.append(context.getContextPath()).append(Global.getFrontPath());
        str.append(Global.getFrontPath());
        str.append("list-").append(category.getId()).append(Global.getUrlSuffix());
        return str.toString();
    }

    /**
     * 从图片地址中去除ContextPath地址
   	 * @param src
   	 * @return src
   	 */
    public static String formatImageSrcToDb(String src) {
        if(StringUtils.isBlank(src)) return src;
        if(src.startsWith(context.getContextPath() + "/userfiles")){
            return src.substring(context.getContextPath().length());
        }else{
            return src;
        }
    }

    /**
     * 从图片地址中加入ContextPath地址
   	 * @param src
   	 * @return src
   	 */
    public static String formatImageSrcToWeb(String src) {
        if(StringUtils.isBlank(src)) return src;
        if(src.startsWith(context.getContextPath() + "/userfiles")){
            return src;
        }else{
            return context.getContextPath()+src;
        }
    }
    
    public static void addViewConfigAttribute(Model model, String param){
        if(StringUtils.isNotBlank(param)){
            @SuppressWarnings("rawtypes")
			Map map = JsonMapper.getInstance().fromJson(param, Map.class);
            if(map != null){
                for(Object o : map.keySet()){
                    model.addAttribute("viewConfig_"+o.toString(), map.get(o));
                }
            }
        }
    }

    public static void addViewConfigAttribute(Model model, Category category){
        List<Category> categoryList = Lists.newArrayList();
        Category c = category;
        if(null == c)
        	return;
        boolean goon = true;
        do{
            if(c.getParent() == null || c.getParent().isRoot()){
                goon = false;
            }
            categoryList.add(c);
            c = c.getParent();
        }while(goon);
        Collections.reverse(categoryList);
        for(Category ca : categoryList){
        	addViewConfigAttribute(model, ca.getViewConfig());
        }
    }
}

以获取链接列表为例即getArticleList方法

2.定义tld文件,必须位于WEB-INF目录或其子目录

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
    
  <description>JSTL 1.1 functions library</description>
  <display-name>JSTL functions cms</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>fnc</short-name>
  <uri>http://java.sun.com/jsp/jstl/functionsc</uri>

  <function>
    <description>获取当前管理站点编号</description>
    <name>getCurrentSiteId</name>
    <function-class>com.newtouch.modules.cms.entity.Site</function-class>
    <function-signature>java.lang.String getCurrentSiteId()</function-signature>
    <example>${fnc:getCurrentSiteId()}</example>  
  </function>
  
  <function>
    <description>获取站点</description>
    <name>getSite</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>com.newtouch.entity.cms.Site getSite(java.lang.String)</function-signature>
    <example>${fnc:getSite(siteId)}</example>  
  </function>
  
  <function>
    <description>获取站点列表</description>
    <name>getSiteList</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>java.util.List getSiteList()</function-signature>
    <example>${fnc:getSiteList()}</example>  
  </function>
  
  <function>
    <description>获取主导航列表</description>
    <name>getMainNavList</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>java.util.List getMainNavList(java.lang.String,java.lang.String)</function-signature>
    <example>${fnc:getMainNavList(siteId,project)}</example>  
  </function>
  
  <function>
    <description>获取栏目</description>
    <name>getCategory</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>com.newtouch.entity.cms.Category getCategory(java.lang.String)</function-signature>
    <example>${fnc:getCategory(categoryId)}</example>  
  </function>
  
  <function>
    <description>获得栏目列表</description>
    <name>getCategoryList</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>java.util.List getCategoryList(java.lang.String, java.lang.String, int, java.lang.String)</function-signature>
    <example>${fnc:getCategoryList(siteId, parentId, number, param)}</example>  
  </function>
  
  <function>
    <description>获得栏目列表</description>
    <name>getCategoryListByIds</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>java.util.List getCategoryListByIds(java.lang.String)</function-signature>
    <example>${fnc:getCategoryListByIds(categoryIds)}</example>  
  </function>
  
  <function>
    <description>获取文章</description>
    <name>getArticle</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>com.newtouch.entity.cms.Article getArticle(java.lang.String)</function-signature>
    <example>${fnc:getArticle(articleId)}</example>  
  </function>
  
  <function>
    <description>获取文章列表</description>
    <name>getArticleList</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>java.util.List getArticleList(java.lang.String, java.lang.String, int, java.lang.String)</function-signature>
    <example>${fnc:getArticleList(siteId, categoryId, number, param)}</example>  
  </function>
  
  <function>
    <description>获取链接</description>
    <name>getLink</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>com.newtouch.entity.cms.Link getLink(java.lang.String)</function-signature>
    <example>${fnc:getLink(linkId)}</example>  
  </function>
  
  <function>
    <description>获取链接列表</description>
    <name>getLinkList</name>
    <function-class>com.newtouch.modules.cms.utils.CmsUtils</function-class>
    <function-signature>java.util.List getLinkList(java.lang.String, java.lang.String, int, java.lang.String)</function-signature>
    <example>${fnc:getLinkList(siteId, categoryId, number, param)}</example>  
  </function>
  
</taglib>

3、jsp页面的使用
引入tld文件

<%@ taglib prefix="fnc" uri="/WEB-INF/tlds/fnc.tld" %>
<c:forEach items="${fnc:getArticleList(site.id,'067a5a4fb0984b23930b40471bda24ac', 10, '')}" var="article">
	                    <li class="clear">
							<a class="clear" href="${ctxWx}${project}/news${article.url}" >
							<c:if test="${not empty article.imageSrc}">
								<img class="fl" src="${pageContext.request.contextPath}${article.imageSrc}" />
								<div class="fr">
									<h2>${fns:abbr(article.title,100)}</h2>   
				                  	<p>${article.description}</p>
				                  	<p style="text-align:right;color:#999;line-height:0.7rem;height:0.7rem;"><fmt:formatDate value="${article.updateDate}" pattern="yyyy.MM.dd"/></p>
								</div>
							</c:if>
							<c:if test="${empty article.imageSrc}">
								<div class="fr" style="width:100%">
									<h2>${fns:abbr(article.title,100)}</h2>   
				                  	<p>${article.description}</p>
				                  	<p style="text-align:right;color:#999;line-height:0.7rem;height:0.7rem;"><fmt:formatDate value="${article.updateDate}" pattern="yyyy.MM.dd"/></p>
								</div>
							</c:if>
							</a>
					</li>
            	</c:forEach>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值