日期:2014-05-16  浏览次数:20436 次

JSP 自定义标签库实现步骤

java类:

package com.Aaron.test;

import java.util.Properties;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;

public class MessageTag extends TagSupport {
?private String key;

?public MessageTag(){
??
?}
?@Override
?public int doEndTag() throws JspException {
??try {
???Properties ps = (Properties)pageContext.getAttribute("ps",pageContext.APPLICATION_SCOPE);
???Properties ps_zh = (Properties)pageContext.getAttribute("ps_zh",pageContext.APPLICATION_SCOPE);
???HttpSession session = pageContext.getSession();
???String language = (String)session.getAttribute("language");
???String message = null;
???if(language != null && language.equals("Chinese")){
????message = ps_zh.getProperty(key);
???}else{
????message = ps.getProperty(key);
???}
???pageContext.getOut().print(message);
??} catch (Exception e) {
???throw new JspTagException(e.getMessage());
??}
??return SKIP_BODY;
?}
?@Override
?public void release() {
??super.release();
?}
?public String getKey() {
??return key;
?}

?public void setKey(String key) {
??this.key = key;
?}
?
}

**************************************************

?

tld标签:

<?xml version="1.0" encoding="UTF-8"?>
<!-- <!DOCTYPE taglib PUBLIC "-//Sun Microsystems,Inc.//DTD JSP Tag Library
1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd "> -->
<taglib>
??? <tlibversion>1.0</tlibversion>
??? <jspversion>1.1</jspversion>
??? <shortname>mytaglib</shortname>
??? <uri>/mytaglib</uri>
??? <tag>
??????? <name> message</name>
??????? <tagclass>com.Aaron.test.MessageTag </tagclass>
??????? <bodycontent>empty </bodycontent>
??????? <info>produce message by key</info>
??????? <attribute>
??????????? <name>key</name>
??????????? <required>true</required>
??????? </attribute>
??? </tag>
</taglib>

?

******************************************************

web.xml:

?<taglib>
??<taglib-uri>/mytaglib</taglib-uri>
??<taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
?</taglib>

?

***************************************************

?

jsp 页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="ISO-8859-1" %>
< %@taglib uri="/mytaglib" prefix="msg" %>
?<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd ">
<html>
??? <head>
??????? <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
??????? <title><msg:message key="hello.hello"/></ title>
??? </head>
??? <body>
??????? <%
???????? String language = request.getParameter("language");
???????? language? = language == null ? "English" : language;
???????? session.setAttribute("language",language);
?? %>
??????? <msg:message key="login.user