jsp调用java函数的方法

来源:互联网 发布:男士去油洗面奶 知乎 编辑:程序博客网 时间:2024/06/05 07:16

1.编写java类

[java] view plain copy
  1. package myEL;  
  2.   
  3. public class ELFun {  
  4.       
  5.   public static String processStr(String s) {  
  6.       
  7.     s=s.toUpperCase();  
  8.     return s;  
  9.       
  10. }  
  11.       
  12. }  

EL函数对应的java类的方法必须是静态的

2.编写tld文件

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">  
  4.  <tlib-version>1.0</tlib-version>  
  5.  <uri>myelfun</uri>  
  6.  <function>  
  7.   <name>elfunction</name>  
  8.   <function-class>myEL.ELFun</function-class>  
  9.   <function-signature>  
  10.      java.lang.String processStr(java.lang.String)  
  11.   </function-signature>  
  12.  </function>>  
  13. </taglib>  

TLD文件的扩展名必须是.tld

3.web.xml配置

[html] view plain copy
  1. <jsp-config>  
  2.   <taglib>  
  3.   <taglib-uri>/WEB-INF/TLD/elfun.tld  
  4.   </taglib-uri>  
  5.   <taglib-location>  
  6.   /WEB-INF/TLD/elfun.tld  
  7.   </taglib-location>  
  8.   </taglib>  
  9.  </jsp-config>  

4.jsp中调用

[html] view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <%@ taglib uri="/WEB-INF/TLD/elfun.tld"  prefix="elfun" %>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'elfun.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.    <form method="POST">  
  27.                   请输入一个字符串:  
  28.      <input type="text" name="text"/>  
  29.      <p>  
  30.      <input type="submit" value ="提交"/>  
  31.    </form>  
  32.    <p>  
  33.                           直接输出文本框中的内容:  
  34.     <p>  
  35.        ${param.text }  
  36.     <p>  
  37.       
  38.      ${elfun:elfunction(param.text)}  
  39.     <p>  
  40.       
  41.     <br>  
  42.   </body>  
  43. </html>  

如果用URI引用TLD文件,JSP引擎会先在WEB-INF目录及子目录中寻找所有的*.tld文件,如果发现某个.tld文件中的<uri>标签定义的URI和talib中的uri属性的值相等,就会记住这个.tld路径,在生成servlet的同时就会将这个TLD文件的路径也加进来。


原创粉丝点击