1. 程式人生 > >SSH:Struts1框架(自定義標籤函式庫)

SSH:Struts1框架(自定義標籤函式庫)

JSTL函式庫

1.JstlFnAction.java

package com;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class JstlFnAction extends Action {

 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  
  request.setAttribute("hello", "Hello World !");
  
  List<String> list = new ArrayList<String>();
  list.add("a");
  list.add("b");
  request.setAttribute("list", list);
  
  request.setAttribute("username", "KIMURA SAORI");
  return mapping.findForward("success");
 }

}

2.jstl_fn.jsp

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="mf" uri="myURI" %>
<!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>測試JSTL函式庫</title>
</head>
<body>
 <h1>測試JSTL函式庫</h1><hr>
 <li>JSTL函式庫</li><br>
 hello.length(JSP指令碼)=<%=request.getAttribute("hello").toString().length() %><br>
 hello.length(JSTL標籤)=${fn:length(hello) }<br>
 list.size=${fn:length(list) }<br>
 <p>
 <li>測試自定義函式庫</li><br>
 sayHello:${mf:sayHello(username) }
</body>
</html>

注:使用自定義函式庫

* 定義類和方法(方法必須是public static)

* 編寫自定義tld檔案,並且將此檔案放到WEB-INF或WEB-INF任意子目錄下

3.my.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/j2eehttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
   
  <description>my functions library</description>
  <display-name>my functions</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>mf</short-name>
  <uri>myURI</uri>
 
  <function>
    <name>sayHello</name>
    <function-class>com.MyFunction</function-class>
    <function-signature>java.lang.String sayHello(java.lang.String)</function-signature>
  </function>

</taglib>

4.MyFunction.java

package com;

public class MyFunction {
 
 public static String sayHello(String name) {
  return "Hello "+name+" !";
 }
}

執行結果:

Struts <wbr>1.2筆記:JSTL函式庫與自定義函式庫