the5fire

关注Python、Django、Vim、Linux、Web开发、团队管理和互联网--Life is short, we need Python.


JSTL中函数的简单使用

作者:the5fire | 标签:     | 发布:2011-01-01 9:10 p.m. | 阅读量: 7514, 7409

因为函数的使用方法和EL表达式以及核心库中的标签的使用有点小区别,因此发这篇文章,并且根据fn的使用以及学习,后面我们就可以使用自定义的JSTL的函数库。 首先还是先建一个Servlet:JstlFnServlet.jsp:

.. code:: java

package com.jstl;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 演示JSTL函数库的使用
 * @author 胡阳
 *
 */
public class JstlFnServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //简单测试字符串
        request.setAttribute("hello", "Hello-World");

        //页面转发
        request.getRequestDispatcher("/jstl_fn.jsp").forward(request, response);
    }

}

然后还是xml配置,不用多说。

建立jsp页面:jstl_fn.jsp:

::

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<!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=GB18030">
<title>Insert title here</title>
</head>
<body>
    <h2>测试JSTL方法:fn:contains这个方法的使用</h2>
    <li>判断返回字符串中是否存在World这个词:</li>
    <c:if test="${fn:contains(hello, 'World')}">
        存在<br>
    </c:if>

    <li>判断返回字符串中是否存在nihao这个词:</li>
    <c:if test="${fn:contains(hello, 'nihao')}">
        存在“nihao”<br>
    </c:if>
</body>
</html>

在原先的index页面中添加:

::

<a href="servlet/JstlFnServlet">测试核心库</a>

然后启动index页面,完了

你可以自己看一下fn.tld这个文件的内容,我这里摘取一点,就比如说我这里用的“fn:contains”这个方法:

.. code:: xml

<function>
    <description>
      Tests if an input string contains the specified substring.
    </description>
    <name>contains</name>
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>
    <function-signature>boolean contains(java.lang.String, java.lang.String)</function-signature>
    <example>
      &lt;c:if test="${fn:contains(name, searchString)}">
    </example>
</function>

有点英文基础的童鞋一看就能看明白这里面说的是什么,首先是方法描述,然后是方法名称,下面的function-class就是这个方法在哪个jar包中,然后下面是方法定义,最后是举例。 不知道大家看这个觉不觉的眼熟呀,这个跟Servlet的配置是类似的。 接下来就可以自己写一个JSTL函数了。

- from the5fire.com
----EOF-----

微信公众号:Python程序员杂谈


其他分类: