当前位置:  技术问答>java相关

谁告诉我可以调通这个文件??高分相送!!(关于JSP TAG的,附精彩原文)

    来源: 互联网  发布时间:2015-01-23

    本文导语:  这是一个JSP TAG实现,代码如下: import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** * Given a URI, uses the servlet context to find out how large the * "real" file is in bytes. * * @author Simon Brown */ public c...

这是一个JSP TAG实现,代码如下:

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
* Given a URI, uses the servlet context to find out how large the
* "real" file is in bytes.
*
* @author Simon Brown
*/
public class SizeTag extends javax.servlet.jsp.tagext.TagSupport {

        /** the URI of the file */
        private String uri;

        /**
        * Performs the processing of this tag.
        */
        public int doStartTag() throws JspException {
            StringBuffer html = new StringBuffer();

            // ask the container (via the servlet context) for the
            // real path of a file pointed to by a URI
            String realPath = pageContext.getServletContext().getRealPath(uri);

            // we can now find out how large the file is
            File f = new File(realPath);
            long fileLength = f.length();

            // build up the HTML piece by piece ...
            html.append(fileLength);
            html.append(" bytes");

            // ... and write it
            try {
                pageContext.getOut().write(html.toString());
            } catch (IOException ioe) {
                throw new JspException(ioe.getMessage());
            }

            return EVAL_BODY_INCLUDE;
        }

        /**
        * Standard JavaBeans style property setter for the URI.
        *
        * @param s a String representing the URI
        */
        public void setUri(String s) {
            this.uri = s;
        }

}


下面是原文出处:
《functionality in JSP --Build your own custom JSP tag with Tomcat 》



Summary 
JavaServer Pages (JSP) are a great mechanism for delivering dynamic Web-based content. JSP provides a set of predefined tags, but you can also define your own tag extensions that encapsulate common functionality. This article will show how easy it is to build, deploy, and use your own custom JSP tag, using the Servlet/JSP reference implementation, Tomcat. (1,700 words) 
By Simon Brown 


ike HTML, JavaServer Pages (JSP) use the concept of tags as their building blocks. A handful of tags are available to you as a JSP developer, allowing you to embed Java code, include other documents, and even make use of JavaBeans components. Although those tags are all you need to build Websites with dynamic content, you will probably find yourself duplicating small bits of functionality into your JSP pages after a while. If that is the case, tag libraries may be the answer. 

What are tag libraries? 
Tag libraries, or taglibs, are a feature of JSP 1.1 that enables you to build libraries of reusable JSP tags. That means you can encapsulate common behavior in your own JSP tag and use it across the JSP pages in your Web apps. The ability to extract common functionality from a JSP page and easily reuse it in other pages and Web applications can be very powerful. But isn't that what JavaBeans were designed for? 

JavaBeans are reusable software components. It's true that there are JSP tags that let you use JavaBeans within your pages. The only ability those tags allow you, however, is to bind named, scoped instances, and then get/set those instances' properties. If you need to call methods on your JavaBeans, you need to embed the appropriate Java code inside a scriptlet. 

Tags or JavaBeans? 
I've established that you can use JavaBeans or JSP tags to encapsulate common functionality. That in essence labels both JavaBeans and tags as reusable software components and raises the question of when one is more appropriate to use over the other. While no hard and fast rules explain that, a couple of factors can be taken into account. 

Server-side JavaBeans are nonvisual components, and I generally use them for maintaining session state and business information. A good example would be using a bean to maintain the user's current state in a Web-based mail application. 

Tags on the other hand can represent actions on a page, and I tend to use those to hide common functionality that generates dynamic HTML or controls the page in some way. 

One of the key differences between JavaBeans and JSP tags is that tags are much more aware of the environment in which they are running. That includes the page context (containing the request, response, and so on) and the servlet context of the Web application in which the tag is running. JSP tags can use those contexts to access the HTTP session information and to also make use of JavaBeans that contain session and/or business state. 

An example tag 
That's enough about what tags are and how you can use them. The next questions I'll address are what they look like and how to write them. First, I'll present an example, showing how to write a simple JSP tag; then I'll show you how to deploy and use it in your JSP pages. 

To keep things simple, I'll use the current reference implementation of the Servlet/JSP specification -- Tomcat from the Apache Group. Tomcat supports the new J2EE Web applications and, to save creating your own, you can use Tomcat's example Web application. That can be found under your Tomcat installation directory (TOMCAT_HOME) in webapps/examples. 

Further information about Tomcat, including details on where you can download it, can be found in the Resources section. 

Displaying a file size 
To set the scene, imagine that your Web application lets the user download a file via a hyperlink. Your JSP page could get the filename (or URI) from a JavaBean and generate the hyperlink dynamically. Let's say you realize that some of those files may be very large, and you'd like to display the file size so that the user can make an informed decision as to whether he or she wishes to download the file. 

Obviously, a few options are open to you, one being to use the JavaBean to store the file size. Of course that isn't a good option if the contents of the file change frequently. Instead, you would use a custom tag that, given a file's URI, uses its environment to find out how large the file is. 

Design and describe the tag 
First, you'll need to describe your tag, giving it a name and specifying any attributes it may have. You do that by creating a tag library descriptor (.tld) file -- an XML file that describes your tag library. 

For the purpose of that example, I'll create a file called taglib.tld and place it under the web-inf directory. The contents of the file as are follows. 







    1.0
    1.1
    examples
    http://www.mycompany.com/taglib
    An example tag library

    
        size
        examples.SizeTag
        Works out how large a file, pointed to by a URI, is in bytes
        
            uri
            true
            false
        
    





I'll skim over the top of the file and concentrate on the tag library that I am defining. A tag library has a short name, a brief description, and a URI. That doesn't need to be a real URI as it's just an identifier for the library. A tag library can have one or more tags, each tag having a name, some brief commentary about its purpose, and a fully qualified class name. That class name is the name of the Java class that contains the functionality provided by your custom tag. I'll write that class shortly. 

My tag has one mandatory (required) attribute called uri, allowing me to specify the URI of the file whose size I want. When using custom tags on a JSP page, you can provide a Java scriptlet as the value of an attribute. The value between the  tags indicates that such may be the case and that the JSP engine should evaluate the runtime expression beforehand. For this simple example, I'll just pass a hard-coded URI, so I've set that to false for now. 

Build the tag 
Once you have described your tag and its attributes, you need to write the class that will provide the functionality. All JSP tags are required to implement the javax.servlet.jsp.tagext.Tag interface. When a tag is used on a page, the JSP engine instantiates the class and begins by calling the various life cycle methods that the interface defines. That includes telling the tag about its environment by referring to a PageContext object. 

The following code shows the SizeTag class. There are two places where supporting classes can go but, for the purpose of this example, I'll place the tag under the web-inf/classes directory. There should already be an examples package in which I can place the tag. 

package examples; 



import java.io.*;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
* Given a URI, uses the servlet context to find out how large the
* "real" file is in bytes.
*
* @author Simon Brown
*/
public class SizeTag extends javax.servlet.jsp.tagext.TagSupport {

        /** the URI of the file */
        private String uri;

        /**
        * Performs the processing of this tag.
        */
        public int doStartTag() throws JspException {
            StringBuffer html = new StringBuffer();

            // ask the container (via the servlet context) for the
            // real path of a file pointed to by a URI
            String realPath = pageContext.getServletContext().getRealPath(uri);

            // we can now find out how large the file is
            File f = new File(realPath);
            long fileLength = f.length();

            // build up the HTML piece by piece ...
            html.append(fileLength);
            html.append(" bytes");

            // ... and write it
            try {
                pageContext.getOut().write(html.toString());
            } catch (IOException ioe) {
                throw new JspException(ioe.getMessage());
            }

            return EVAL_BODY_INCLUDE;
        }

        /**
        * Standard JavaBeans style property setter for the URI.
        *
        * @param s a String representing the URI
        */
        public void setUri(String s) {
            this.uri = s;
        }

}




You may have noticed that instead of implementing the Tag interface, I'm actually extending a class called TagSupport. That is provided as part of the standard Servlet/JSP distribution and contains a default implementation of the methods defined in the Tag interface. 

There are only two methods of interest in this tag, doStartTag() and setUri(). When I defined the tag in the tag library descriptor, I said that it would have an attribute called uri. Attribute values are passed to tags via the appropriate set method. The Java code that performs that is generated by the JSP engine, which uses Java's reflection mechanism to check that the appropriate method does exist on the tag. For that reason, tags must define a set method for each of its defined attributes. The name of the method should follow the JavaBeans convention of changing the first character of the property name to uppercase. The setUri() method is defined as taking a String, although you can use any object. 

Custom tags on a JSP use the XML notion of an opening and closing tag, reflected by the doStartTag() and doEndTag() methods defined in the Tag interface. As my tag is a very simple example, I've chosen only to implement doStartTag(), which gets called when the JSP engine encounters the opening (or starting) tag. My implementation uses the tag's page context to find out a file's local location, to which the specified URI points. Once the tag has that information, it uses a standard java.io.File object to work out the file's length and generates a small, dynamic HTML string. That generated HTML is then sent back to the JSP engine, using the output stream associated with the page context. The return value tells the JSP engine how the tag processing should continue. In that case, you're telling the engine to continue as normal and evaluate any body content. 

You should now compile the above class, ensuring that you have the Servlet/JSP classes in your classpath. Those can be found in TOMCAT_HOME/lib/servlets.jar. 

Registering the tag library 
Now that you've defined your tag and written its supporting class, you now need to tell the Web application where to find the tags by registering the taglib with it. The Web application configuration file (web.xml) is stored under the web-inf directory. Open up the web.xml file and insert the following XML fragment. The ordering of XML elements in the file is important, so the fragment below should be placed before or after the existing example taglib. 


    
        
            http://www.mycompany.com/taglib
        
        
          /WEB-INF/taglib.tld
        
    



That tells the Web application where to find the taglib descriptor and the URI that refers to the taglib. Again, that doesn't have to be a real URI, but it should be the same as the one specified in the taglib.tld file that you created above. 

Using the tag 
The final step in this example is to actually use the tag in a JSP page. To do that, you'll write a very simple JSP page as illustrated below. It should be saved with the normal .jsp extension and can be placed in the examples root directory (TOMCAT_HOME/webapps/examples). 

 
 
 
 

 
The file is . 
 
 


The taglib directive tells the JSP engine that your JSP wishes to use a taglib referred to by the specified URI. The taglib directive also takes a prefix that tags on the page will use. For the sake of this example, I'll be using the examples prefix. 

On the JSP, your tag consists of the prefix (like an XML namespace), the tag name, and any attributes. It's written by using normal XML notation, and the example above uses the shorthand for combining the opening and closing tags. The URI that you pass your tag just points to an HTML file provided with the JSP examples. 

All you need now is to start up Tomcat and request the JSP from your browser. What you should notice is that your custom tag has been completely processed and substituted with the HTML that it generated dynamically. If you take a look at the HTML source via the browser, you should also notice that no trace of your tag remains. 

Summary 
I hope this article has given you an introduction and overview of JSP tag libraries. I've covered some of the tag basics, illustrated when you would use custom tags over JavaBeans, and presented a short example of how to build and deploy a tag. 

Although there's a lot more to taglibs than has been presented here, the article aimed to give you a good starting point from which to explore further and begin to develop your own taglibs. Custom tags are a very powerful addition to the current JSP specification and a great mechanism for wrapping up reusable functionality on your JSPs. 

About the author 
Simon Brown is a distributed systems designer and developer with more than three years of commercial Java experience. He has considerable knowledge of large-scale distributed developments for major clients, having designed and implemented a number of important Java systems, largely in the banking and media sectors. Considered one of Synamic's more senior Java specialists, he acts as technical lead and mentor to other team members and presents at Java events, including a BOF session at JavaOne 2000. Simon is a Sun-certified enterprise architect for J2EE and developer for Java 2. 



|
我编译过了,没有出错。我的编译情况:
F:javatest>javac SizeTag.java

F:javatest>

你有javax.servlet包吗?建议你在classpath中指定servlet.jar,我的classpath是:.;D:JDK1.3libdt.jar;D:JDK1.3libtools.jar;E:TOMCATlibservlet.jar;D:j2sdkee1.2.1libj2ee.jar

servlet.jar的内容为:

F:java>jar -ft servlet.jar
META-INF/
META-INF/MANIFEST.MF
javax/
javax/servlet/
javax/servlet/http/
javax/servlet/jsp/
javax/servlet/jsp/tagext/
javax/servlet/http/Cookie.class
javax/servlet/http/HttpServlet.class
javax/servlet/http/NoBodyResponse.class
javax/servlet/http/NoBodyOutputStream.class
javax/servlet/http/HttpServletRequest.class
javax/servlet/http/HttpServletResponse.class
javax/servlet/http/HttpSession.class
javax/servlet/http/HttpSessionBindingEvent.class
javax/servlet/http/HttpSessionBindingListener.cl
javax/servlet/http/HttpSessionContext.class
javax/servlet/http/HttpUtils.class
javax/servlet/http/LocalStrings.properties
javax/servlet/http/LocalStrings_es.properties
javax/servlet/jsp/tagext/BodyContent.class
javax/servlet/jsp/tagext/BodyTag.class
javax/servlet/jsp/tagext/BodyTagSupport.class
javax/servlet/jsp/tagext/Tag.class
javax/servlet/jsp/tagext/TagAttributeInfo.class
javax/servlet/jsp/tagext/TagData.class
javax/servlet/jsp/tagext/TagExtraInfo.class
javax/servlet/jsp/tagext/TagInfo.class
javax/servlet/jsp/tagext/TagLibraryInfo.class
javax/servlet/jsp/tagext/TagSupport.class
javax/servlet/jsp/tagext/VariableInfo.class
javax/servlet/jsp/HttpJspPage.class
javax/servlet/jsp/JspEngineInfo.class
javax/servlet/jsp/JspException.class
javax/servlet/jsp/JspFactory.class
javax/servlet/jsp/JspPage.class
javax/servlet/jsp/JspTagException.class
javax/servlet/jsp/JspWriter.class
javax/servlet/jsp/PageContext.class
javax/servlet/GenericServlet.class
javax/servlet/RequestDispatcher.class
javax/servlet/Servlet.class
javax/servlet/ServletConfig.class
javax/servlet/ServletContext.class
javax/servlet/ServletException.class
javax/servlet/ServletInputStream.class
javax/servlet/ServletOutputStream.class
javax/servlet/ServletRequest.class
javax/servlet/ServletResponse.class
javax/servlet/SingleThreadModel.class
javax/servlet/UnavailableException.class
javax/servlet/LocalStrings.properties

|
javax.servlet 这个类应该是自定义的吧?反正我在帮助文件里没找到

    
 
 

您可能感兴趣的文章:

  • 高分相送:谁能告诉我freebsd5.1的详细步骤和配置步骤阿,只送第一个解决者
  • 高分,请告诉指点迷津!!!!!!!!!!!!!!!!!!!!!!!
  • .net/c#/asp.net iis7站长之家
  • 哪位能告诉我下载Jbuilder6.0企业版和注册码的网址?高分相送。
  • 高分求助 。。。。。。。。。。。。各位高手。可以不可以告诉我。当我下载完resin之后应该如何配置好一个jsp的环境。我的操作系统是win2k professional
  • 如何在jbuilder中运行jdk的程序呢,可以详细告诉我吗(高分)
  • 高分弱智问题啊。。。请把linux所有分区的符号含义告诉我(要全而且详细哦)
  • 请问有没有完整的javamail的例子?有的话请告诉小弟,小弟急着用。高分送
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • 请告诉一下,下载的.iso文件怎么用?见笑见笑
  • 怎么把头文件路径告诉makefile
  • 谁能告诉我下不同操作系统对单个文件大小的限制
  • 有谁会用linux里面的wget?有一个参数是-i 后面加上url地址文件,我不明白什么叫url地址文件,那位大侠告诉我?
  • 哪位仁兄可以告诉我在linux下如何访问本机windows下的文件?
  • 如何告诉GDB我的共享库文件在哪里
  • 如何指定用javac编译生成类的存放路径。(最好不要告诉我再生成之后再把文件流重新到出这种)
  • 我想访问局域网中服务器中的一个文件,但告诉我连接被拒绝!
  • 谁能告诉我,linux下可可执行文件是什么?
  • com.borland.dbswing.* 在什么文件里啊?可以发给我一个吗?Rex_fa@163.com 告诉我也行
  • 谁能告诉我,做一个象网易那样的聊天室,用什么方法,不要告诉我是用数据库或读写文件,是不是用多线程,socket协议。来讨论者皆有分。
  • 紧急求救,请问谁的linux中有libXm.so.2这个文件,请寄给我并请告诉我路径,真诚期待,万分感激!(sailoremail@163.com)
  • 能不能告诉我使用editplus编写java如何编译成字节码文件,如何解释?,虽然问题简单一点,可对我很需要
  • 谁能告诉我,怎么调试jsp程序呀!我在jsp中调用java,但是Tomcat这家伙只会给我报jsp文件出错。这可怎么办呀?
  • 大家请把自己知道的 Unix/Linux 下的垃圾文件通配符类型告诉我,好吗?送上100分。
  • 各位高人,关于IDE的驱动程序,我看蒙了,谁能告诉我到底linux源文件中到底那些是跟IDE硬盘驱动有关的?
  • 我下载了一个xmms-1.2.7.tar.gz音频文件包。怎么样在系统下安装。可以告诉我严格的安装顺序吗?
  • 谁能告诉我怎样些Makefile文件
  • 谁能告诉我哪儿有 j2sdk-1_3_1-win.exe 下载,最好告诉我url
  • 我的是red hat linux9,那位好心人告诉我如何在这个系统下搭建lamp平台,按照网上装了半天,总是出错,希望有人能告诉我一个可用的方法,详细点的,谢谢
  • 谁能告诉我类和库有什么区别,送分???????
  • 那里有IBM的WEBSPHERE下载,能告诉我下载的网址吗?
  • 请告诉我websphere4的详细安装步骤
  • 推荐一本电子版的xml与java编程的书,告诉我下载地址。
  • 谁能告诉我pop3邮件操作命令列表?
  • 50分相送,告诉我gcc地址
  • 谁能告诉我JSP中怎样使用类??先谢谢了
  • 有谁能告诉我如何在Solaris下播放音乐CD呀?
  • linux进入界面需要login我不知道,谁能告诉我,谢谢
  • 各位大侠,谁告诉我怎么屏蔽?
  • 各位,能否告诉小弟那里有《thinking in java》可以下载啊!thx


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3