JavaWeb基礎—EL表達式與JSTL標簽庫


EL表達式:

  EL 全名為Expression Language。EL主要作用

      獲取數據(訪問對象,訪問數據,遍歷集合等)

      執行運算

      獲取JavaWeb常用對象

      調用Java方法(EL函數庫)

給出一個小案例:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.jiangbei.domain2.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'a.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <%
        Address addr = new Address();
        addr.setCity("北京");
        addr.setStreet("王府井");
        
        Employee emp = new Employee();
        emp.setName("張三");
        emp.setSalary(20000);
        emp.setAddress(addr);
        
        request.setAttribute("emp", emp);
    %>
    <h3>使用el獲取request里的emp</h3>
    <!-- JavaBean導航,等同與調用了.getXxx()等方法 -->
    ${requestScope.emp.address.street }
    <!-- 輸出當前項目名 -->
    ${pageContext.request.contextPath }
    <!-- 以下為一個超鏈接小例,其它表單等類同 -->
    <a href="${pageContext.request.contextPath }/EL/a.jsp">點擊這里</a>
  </body>
</html>
View Code

  注意點:

EL表達式入門:JSP內置的表達式語言(報錯,選中、復制、刪除、粘貼)
  ${xxx} 完成全域查找(從小往大找,注意session的坑) 指定域查找 requestScope.xxx(必須要記住Scope的坑)
  request.setAttribute();,設置完后進行查找
  替代的是<%= %> 只能用來做輸出,要用來做設置,等JSTL
  主要用來做輸出,可以輸出的東西在下列11個內置對象中:(前10個都是map類型)
  map.key這是EL的操作形式,map['User-Agent']等,用於規避字符二義性
    pageScope
    requestScope
    sessionScope
    applicationScope
    跟參數相關:
      param;對應參數,適用單值參數,是map
      paramValues;適用於多值,通過下標[0]等進行訪問輸出操作
    跟頭相關:
      header;對應請求頭,適用單值,是map
      headerValues;類同上
      initParam;獲取web.xml中context-param的初始化參數
      cookie;Map<String, Cookie> 值是Cookie對象
  【注意】pageContext;${pageContext.request.contextPath}以后全部用此代替項目名,帶了斜杠
  而且此項目名會隨着一起變!相當於調用了getRequest().getContextPath()

EL函數庫:語法:${prefix:method(params)}

EL函數庫(由JSTL提供)
首先需要導入標簽庫(lib下myeclipse帶了jstl的jar包)

   基本示例如下:

fn:contains(string, substring) 
如果參數string中包含參數substring,返回true

 

fn:containsIgnoreCase(string, substring) 
如果參數string中包含參數substring(忽略大小寫),返回true

 

fn:endsWith(string, suffix) 
如果參數 string 以參數suffix結尾,返回true

 

fn:escapeXml(string) 
將有特殊意義的XML (和HTML)轉換為對應的XML character entity code,並返回

 

fn:indexOf(string, substring) 
返回參數substring在參數string中第一次出現的位置

 

fn:join(array, separator) 
將一個給定的數組array用給定的間隔符separator串在一起,組成一個新的字符串並返回。

 

fn:length(item) 
返回參數item中包含元素的數量。參數Item類型是數組、collection或者String。如果是String類型,返回值是String中的字符數。

 

fn:replace(string, before, after) 
返回一個String對象。用參數after字符串替換參數string中所有出現參數before字符串的地方,並返回替換后的結果

 

fn:split(string, separator) 
返回一個數組,以參數separator 為分割符分割參數string,分割后的每一部分就是數組的一個元素

 

fn:startsWith(string, prefix) 
如果參數string以參數prefix開頭,返回true

 

fn:substring(string, begin, end) 
返回參數string部分字符串, 從參數begin開始到參數end位置,包括end位置的字符

 

fn:substringAfter(string, substring) 
返回參數substring在參數string中后面的那一部分字符串

 

fn:substringBefore(string, substring) 
返回參數substring在參數string中前面的那一部分字符串

 

fn:toLowerCase(string) 
將參數string所有的字符變為小寫,並將其返回

 

fn:toUpperCase(string) 
將參數string所有的字符變為大寫,並將其返回

 

fn:trim(string) 
去除參數string 首尾的空格,並將其返回
例:(通過<%%>存在pageContext中)
${fn:toLowerCase("Www.SinA.org")} 的返回值為字符串“www.sina.org”
View Code

自定義函數庫:
  1.定義類MyFunction(注意:方法必須為 public static且帶返回值)

    例:(例子均來自jeesite)

/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.sys.dao.DictDao;
import com.thinkgem.jeesite.modules.sys.entity.Dict;

/**
 * 字典工具類
 * @author ThinkGem
 * @version 2013-5-29
 */
public class DictUtils {
    
    private static DictDao dictDao = SpringContextHolder.getBean(DictDao.class);

    public static final String CACHE_DICT_MAP = "dictMap";
    
    public static String getDictLabel(String value, String type, String defaultValue){
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
            for (Dict dict : getDictList(type)){
                if (type.equals(dict.getType()) && value.equals(dict.getValue())){
                    return dict.getLabel();
                }
            }
        }
        return defaultValue;
    }
    
    public static String getDictLabels(String values, String type, String defaultValue){
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
            List<String> valueList = Lists.newArrayList();
            for (String value : StringUtils.split(values, ",")){
                valueList.add(getDictLabel(value, type, defaultValue));
            }
            return StringUtils.join(valueList, ",");
        }
        return defaultValue;
    }

    public static String getDictValue(String label, String type, String defaultLabel){
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
            for (Dict dict : getDictList(type)){
                if (type.equals(dict.getType()) && label.equals(dict.getLabel())){
                    return dict.getValue();
                }
            }
        }
        return defaultLabel;
    }
    
    public static List<Dict> getDictList(String type){
        @SuppressWarnings("unchecked")
        Map<String, List<Dict>> dictMap = (Map<String, List<Dict>>)CacheUtils.get(CACHE_DICT_MAP);
        if (dictMap==null){
            dictMap = Maps.newHashMap();
            for (Dict dict : dictDao.findAllList(new Dict())){
                List<Dict> dictList = dictMap.get(dict.getType());
                if (dictList != null){
                    dictList.add(dict);
                }else{
                    dictMap.put(dict.getType(), Lists.newArrayList(dict));
                }
            }
            CacheUtils.put(CACHE_DICT_MAP, dictMap);
        }
        List<Dict> dictList = dictMap.get(type);
        if (dictList == null){
            dictList = Lists.newArrayList();
        }
        return dictList;
    }
    
    /**
     * 返回字典列表(JSON)
     * @param type
     * @return
     */
    public static String getDictListJson(String type){
        return JsonMapper.toJsonString(getDictList(type));
    }
    /**
     * 返回分類菜單列表
     * @return
     */
    public static List<String> getCategoryList(){
        String[] categorys = {"特色菜","招牌菜","魚類","涼菜","蔬菜","點心","酒水","其他"};
        List<String> categoryList = Arrays.asList(categorys);
        //List<String> categoryList = new ArrayList<String>();
        //categoryList.add("");
        return categoryList;
    }
}
View Code

  2.提供tld描述文件(new xml改后綴名tld),此文件可以放到WEB-INF下(推薦)或其目錄下.(在jstl下找fn.tld借一下)

  fns.tld如下:

 

<?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/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
    
  <description>JSTL 1.1 functions library</description>
  <display-name>JSTL functions sys</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>fns</short-name>
  <uri>http://java.sun.com/jsp/jstl/functionss</uri>

  <function>
    <description>獲取管理路徑</description>
    <name>getAdminPath</name>
    <function-class>com.thinkgem.jeesite.common.config.Global</function-class>
    <function-signature>java.lang.String getAdminPath()</function-signature>
    <example>${fns:getAdminPath()}</example>
  </function>
  <function>
    <description>獲取網站路徑</description>
    <name>getFrontPath</name>
    <function-class>com.thinkgem.jeesite.common.config.Global</function-class>
    <function-signature>java.lang.String getFrontPath()</function-signature>
    <example>${fns:getFrontPath()}</example>
  </function>
  <function>
    <description>獲取網站URL后綴</description>
    <name>getUrlSuffix</name>
    <function-class>com.thinkgem.jeesite.common.config.Global</function-class>
    <function-signature>java.lang.String getUrlSuffix()</function-signature>
    <example>${fns:getUrlSuffix()}</example>
  </function>
  <function>
    <description>獲取配置</description>
    <name>getConfig</name>
    <function-class>com.thinkgem.jeesite.common.config.Global</function-class>
    <function-signature>java.lang.String getConfig(java.lang.String)</function-signature>
    <example>${fns:getConfig(key)}</example>
  </function>
  <function>
    <description>獲取常量</description>
    <name>getConst</name>
    <function-class>com.thinkgem.jeesite.common.config.Global</function-class>
    <function-signature>java.lang.Object getConst(java.lang.String)</function-signature>
    <example>${fns:getConst(key)}</example>
  </function>
  
  <!-- UserUtils -->
  <function>
    <description>獲取當前用戶對象</description>
    <name>getUser</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.UserUtils</function-class>
    <function-signature>com.thinkgem.jeesite.modules.sys.entity.User getUser()</function-signature>
    <example>${fns:getUser()}</example>  
  </function>
  
  <function>
    <description>根據編碼獲取用戶對象</description>
    <name>getUserById</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.UserUtils</function-class>
    <function-signature>com.thinkgem.jeesite.modules.sys.entity.User get(java.lang.String)</function-signature>
    <example>${fns:getUserById(id)}</example>  
  </function>
  
  <function>
    <description>獲取授權用戶信息</description>
    <name>getPrincipal</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.UserUtils</function-class>
    <function-signature>com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal getPrincipal()</function-signature>
    <example>${fns:getPrincipal()}</example>  
  </function>
  
  <function>
    <description>獲取當前用戶的菜單對象列表</description>
    <name>getMenuList</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.UserUtils</function-class>
    <function-signature>java.util.List getMenuList()</function-signature>
    <example>${fns:getMenuList()}</example>  
  </function>
  
  <function>
    <description>獲取當前用戶的區域對象列表</description>
    <name>getAreaList</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.UserUtils</function-class>
    <function-signature>java.util.List getAreaList()</function-signature>
    <example>${fns:getAreaList()}</example>  
  </function>
  
  <function>
    <description>獲取當前用戶的部門對象列表</description>
    <name>getOfficeList</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.UserUtils</function-class>
    <function-signature>java.util.List getOfficeList()</function-signature>
    <example>${fns:getOfficeList()}</example>  
  </function>
  
  <function>
    <description>獲取當前用戶緩存</description>
    <name>getCache</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.UserUtils</function-class>
    <function-signature>java.lang.Object getCache(java.lang.String, java.lang.Object)</function-signature>
    <example>${fns:getCache(cacheName, defaultValue)}</example>  
  </function>
    
  <!-- DictUtils -->
  <function>
    <description>獲取字典標簽</description>
    <name>getDictLabel</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.DictUtils</function-class>
    <function-signature>java.lang.String getDictLabel(java.lang.String, java.lang.String, java.lang.String)</function-signature>
    <example>${fns:getDictLabel(value, type, defaultValue)}</example>  
  </function>
  
  <function>
    <description>獲取字典標簽(多個)</description>
    <name>getDictLabels</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.DictUtils</function-class>
    <function-signature>java.lang.String getDictLabels(java.lang.String, java.lang.String, java.lang.String)</function-signature>
    <example>${fns:getDictLabels(values, type, defaultValue)}</example>  
  </function>

  <function>
    <description>獲取字典值</description>
    <name>getDictValue</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.DictUtils</function-class>
    <function-signature>java.lang.String getDictValue(java.lang.String, java.lang.String, java.lang.String)</function-signature>
    <example>${fns:getDictValue(label, type, defaultValue)}</example>  
  </function>
  
  <function>
    <description>獲取字典對象列表</description>
    <name>getDictList</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.DictUtils</function-class>
    <function-signature>java.util.List getDictList(java.lang.String)</function-signature>
    <example>${fns:getDictList(type)}</example>  
  </function>
  
  <function>
    <description>獲取字典對象列表</description>
    <name>getDictListJson</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.DictUtils</function-class>
    <function-signature>java.lang.String getDictListJson(java.lang.String)</function-signature>
    <example>${fns:getDictListJson(type)}</example>  
  </function>
  <function>
    <description>獲取菜單分類列表</description>
    <name>getCategoryList</name>
    <function-class>com.thinkgem.jeesite.modules.sys.utils.DictUtils</function-class>
    <function-signature>java.util.List getCategoryList()</function-signature>
    <example>${getCategoryList()}</example>  
  </function>
  <!-- Encodes -->
  <function>
    <description>URL編碼</description>
    <name>urlEncode</name>
    <function-class>com.thinkgem.jeesite.common.utils.Encodes</function-class>
    <function-signature>java.lang.String urlEncode(java.lang.String)</function-signature>
    <example>${fns:urlEncode(part)}</example>  
  </function>
  <function>
    <description>URL解碼</description>
    <name>urlDecode</name>
    <function-class>com.thinkgem.jeesite.common.utils.Encodes</function-class>
    <function-signature>java.lang.String urlDecode(java.lang.String)</function-signature>
    <example>${fns:urlDecode(part)}</example>  
  </function>
  <function>
    <description>HTML編碼</description>
    <name>escapeHtml</name>
    <function-class>com.thinkgem.jeesite.common.utils.Encodes</function-class>
    <function-signature>java.lang.String escapeHtml(java.lang.String)</function-signature>
    <example>${fns:escapeHtml(html)}</example>  
  </function>
  <function>
    <description>HTML解碼</description>
    <name>unescapeHtml</name>
    <function-class>com.thinkgem.jeesite.common.utils.Encodes</function-class>
    <function-signature>java.lang.String unescapeHtml(java.lang.String)</function-signature>
    <example>${fns:unescapeHtml(html)}</example>  
  </function>
  
  <!-- StringUtils -->
  <function>
    <description>從后邊開始截取字符串</description>
    <name>substringAfterLast</name>
    <function-class>org.apache.commons.lang3.StringUtils</function-class>
    <function-signature>java.lang.String substringAfterLast(java.lang.String, java.lang.String)</function-signature>
    <example>${fns:substringAfterLast(str,separator)}</example>  
  </function>
  <function>
    <description>判斷字符串是否以某某開頭</description>
    <name>startsWith</name>
    <function-class>org.apache.commons.lang3.StringUtils</function-class>
    <function-signature>boolean startsWith(java.lang.CharSequence, java.lang.CharSequence)</function-signature>
    <example>${fns:startsWith(str,prefix)}</example> 
  </function>
  <function>
    <description>判斷字符串是否以某某結尾</description>
    <name>endsWith</name>
    <function-class>org.apache.commons.lang3.StringUtils</function-class>
    <function-signature>boolean endsWith(java.lang.CharSequence, java.lang.CharSequence)</function-signature>
    <example>${fns:endsWith(str,suffix)}</example> 
  </function>
  <function>
    <description>縮寫字符串,超過最大寬度用“...”表示</description>
    <name>abbr</name>
    <function-class>com.thinkgem.jeesite.common.utils.StringUtils</function-class>
    <function-signature>java.lang.String abbr(java.lang.String, int)</function-signature>
    <example>${fns:abbr(str,length)}</example>  
  </function>
  <function>
    <description>替換掉HTML標簽</description>
    <name>replaceHtml</name>
    <function-class>com.thinkgem.jeesite.common.utils.StringUtils</function-class>
    <function-signature>java.lang.String replaceHtml(java.lang.String)</function-signature>
    <example>${fns:replaceHtml(html)}</example>  
  </function>
  <function>
    <description>轉換為JS獲取對象值,生成三目運算返回結果。</description>
    <name>jsGetVal</name>
    <function-class>com.thinkgem.jeesite.common.utils.StringUtils</function-class>
    <function-signature>java.lang.String jsGetVal(java.lang.String)</function-signature>
    <example>${fns:jsGetVal('row.user.id')}  返回:!row?'':!row.user?'':!row.user.id?'':row.user.id</example>  
  </function>
  
  <!-- DateUtils -->
  <function>
    <description>獲取當前日期</description>
    <name>getDate</name>
    <function-class>com.thinkgem.jeesite.common.utils.DateUtils</function-class>
    <function-signature>java.lang.String getDate(java.lang.String)</function-signature>
    <example>${fns:getDate(pattern)}</example>  
  </function>
  <function>
    <description>獲取過去的天數</description>
    <name>pastDays</name>
    <function-class>com.thinkgem.jeesite.common.utils.DateUtils</function-class>
    <function-signature>long pastDays(java.util.Date)</function-signature>
    <example>${fns:pastDays(date)}</example>  
  </function>
  
  <!-- JsonMapper -->
  <function>
    <description>對象轉換JSON字符串</description>
    <name>toJson</name>
    <function-class>com.thinkgem.jeesite.common.mapper.JsonMapper</function-class>
    <function-signature>java.lang.String toJsonString(java.lang.Object)</function-signature>
    <example>${fns:toJson(object)}</example>  
  </function>
  
</taglib>
View Code

  3.在jsp頁面中采用taglib引入函數庫

【更新,之后引入請使用單獨頁面作為引入頁面,其他頁面直接引入此JSP頁面即可】

  taglib.jsp:

<%@ taglib prefix="shiro" uri="/WEB-INF/tlds/shiros.tld" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fns" uri="/WEB-INF/tlds/fns.tld" %>
<%@ taglib prefix="fnc" uri="/WEB-INF/tlds/fnc.tld" %>
<%@ taglib prefix="sys" tagdir="/WEB-INF/tags/sys" %>
<%@ taglib prefix="act" tagdir="/WEB-INF/tags/act" %>
<%@ taglib prefix="cms" tagdir="/WEB-INF/tags/cms" %>
<c:set var="ctx" value="${pageContext.request.contextPath}${fns:getAdminPath()}"/>
<c:set var="ctxStatic" value="${pageContext.request.contextPath}/static"/>
View Code

 

  頁面引入:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>

  4.在el表達式中采用前綴+冒號+函數名稱使用

<form:options items="${fns:getDictList('party_position')}" itemLabel="label" itemValue="value" htmlEscape="false"/>

 

JSTL標簽庫:目的是為了不在jsp頁面中直接出現java業務邏輯的代碼 

  JSTL標簽庫(依賴EL):標簽庫====重點
    使用JSTL需要導入JSTL的jar包(myeclipse自帶)
  重點是四大庫:
    core:核心庫(重點)
    fmt:格式化庫,日期,數字
    sql:過時
    xml:過時

  核心庫:

    導入標簽庫:先導jar包,再使用taglib導(會有提示的)

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    前綴一般是c,所以被親切的稱為c標簽

core常用標簽庫:(當然可以標簽內結束,目前個人認為推薦)
  輸出標簽(幾乎不用):<c:out value="value" escapeXml=”{true|false}” default="default value"></c:out>
    escapeXml就是是否轉義(比如一連串的alert)
  變量賦值標簽:<c:set var="" value="" target="" property=""scope=""></c:set>
    可以理解為創建域的屬性(類同request.setAttribute()中),注:requet每次請求完就死了
    默認是page域
  移除變量標簽:<c:remove var=""></c:remove>
    與上對應,刪除域變量,默認刪除所有域中的,也可以指定域
  條件表達式標簽:<c:if test="" var=”” scope=””></c:if>
    對應JAVA中的if語句(沒有else)test中包含一個boolean值,test="${not empty a}"

    更新:一般可以用 test=!empty empty等非空/空的判斷
  選擇標簽:<c:choose test=”{true|flse}”></c:choose>
    里面有when,對應else
    <c:when test="${score>=90}"></c:when>
  url標簽:<c:url value="" />
    value指定路徑名,會在前面自動加項目名
    子標簽:<c:param>可以追加參數
    <c:url value="/index.jsp">
    <c:param name="username" value="張三"/>
    </c:url>
    屬性var 不輸出到頁面,而是保存到域中
    這里可以和${pageContext.request.contextPath}相同功能PK
    <c:url value="/AServlet"/>但是得引標簽庫
    循環標簽:

    <c:forEach var=””  items=””   begin=””   end=””   sep=””  varStatus=””></c:forEach>

  <c:forEach var="每個變量名字" 
       items
="要迭代的list"
        varStatus
="每個對象的狀態" begin="循環從哪兒開始"
        end
="循環到哪兒結束"
        step
="循環的步長"> 循環要輸出的東西 </c:forEach>

    其中,較靈活的varStatus請參見:http://blog.csdn.net/ocean_30/article/details/6794743

 例;<c:forEach var="i" begin="1" end="10">
    </c:forEach> step還可以調步長i+=2     當然還可以類似增強for循環遍歷數組等,items后跟的是要遍歷的數組集合等     <c:forEach items="${strs}" var="str">${str}<br/></c"forEach> 在這里標簽里items后不能有空格!
    依賴於EL表達式 ${} 注意!     items后絕對不能亂加空格!var類似於增強for后面的單個變量     varStatus:每個對象的狀態;類似於一個變量:varStatus 擁有count index等屬性

 

    其中index表示下標,從0開始

    后期要注意一定要注意items里的東西必須放到域里面

例如:常用的例子:

22         <c:when test="${score>=90}">
23             你的成績為優秀!
24         </c:when>
25         <c:when test="${score>70 && score<90}">
26             您的成績為良好!
27         </c:when>
28         <c:when test="${score>60 && score<70}">
29             您的成績為及格
30         </c:when>
31         <c:otherwise>
32             對不起,您沒有通過考試!
33         </c:otherwise>
View Code

   【更新】:EL如何嵌套使用:使用set標簽進行

            <c:set var="position" value="${partyMember.position}"></c:set>
                    <%-- ${partyMember.position} --%>
                    ${fns:getDictLabel(position, "party_position","1")}

   

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
    <title>黨員信息管理</title>
    <meta name="decorator" content="default"/>
    <script type="text/javascript">
        $(document).ready(function() {
            //$("#name").focus();
            $("#inputForm").validate({
                submitHandler: function(form){
                    loading('正在提交,請稍等...');
                    form.submit();
                },
                errorContainer: "#messageBox",
                errorPlacement: function(error, element) {
                    $("#messageBox").text("輸入有誤,請先更正。");
                    if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
                        error.appendTo(element.parent().parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });
        });
    </script>
</head>
<body>
    <ul class="nav nav-tabs">
        <li><a href="${ctx}/pm/partyMember/">黨員信息列表</a></li>
        <li class="active"><a href="${ctx}/pm/partyMember/form?id=${partyMember.id}">黨員信息<shiro:hasPermission name="pm:partyMember:edit">${not empty partyMember.id?'修改':'添加'}</shiro:hasPermission><shiro:lacksPermission name="pm:partyMember:edit">查看</shiro:lacksPermission></a></li>
    </ul><br/>
    <form:form id="inputForm" modelAttribute="partyMember" action="${ctx}/pm/partyMember/save" method="post" class="form-horizontal">
        <form:hidden path="id"/>
        <sys:message content="${message}"/>        
        <div class="control-group">
            <label class="control-label">黨員名稱:</label>
            <div class="controls">
                <form:input path="name" htmlEscape="false" maxlength="100" class="input-xlarge required"/>
                <span class="help-inline"><font color="red">*</font> </span>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">黨員生日:</label>
            <div class="controls">
                <input name="birthday" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate required"
                    value="<fmt:formatDate value="${partyMember.birthday}" pattern="yyyy-MM-dd HH:mm:ss"/>"
                    onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>
                <span class="help-inline"><font color="red">*</font> </span>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">黨員身份證號:</label>
            <div class="controls">
                <form:input path="idcard" htmlEscape="false" maxlength="18" class="input-xlarge required"/>
                <span class="help-inline"><font color="red">*</font> </span>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">黨員聯系電話:</label>
            <div class="controls">
                <form:input path="phone" htmlEscape="false" maxlength="200" class="input-xlarge "/>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">黨員職位:</label>
            <div class="controls">
                <%-- <form:input path="position" htmlEscape="false" maxlength="1" class="input-xlarge "/> --%>
                <form:select path="position" class="input-medium">
                    <form:option value="" label=""/>
                    <form:options items="${fns:getDictList('party_position')}" itemLabel="label" itemValue="value" htmlEscape="false"/>
                </form:select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">黨員所屬支部:</label>
            <div class="controls">
                <sys:treeselect id="partyOrganization" name="partyOrganization.id" value="${partyMember.partyOrganization.id}" labelName="partyOrganization.name" labelValue="${partyMember.partyOrganization.name}"
                    title="部門" url="/po/partyOrganization/treeData" cssClass="required" allowClear="true" notAllowSelectParent="true"/>
                <span class="help-inline"><font color="red">*</font> </span>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">入黨時間:</label>
            <div class="controls">
                <input name="joinDate" type="text" readonly="readonly" maxlength="20" class="input-medium Wdate required"
                    value="<fmt:formatDate value="${partyMember.joinDate}" pattern="yyyy-MM-dd HH:mm:ss"/>"
                    onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"/>
                <span class="help-inline"><font color="red">*</font> </span>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">備注信息:</label>
            <div class="controls">
                <form:textarea path="remarks" htmlEscape="false" rows="4" maxlength="255" class="input-xxlarge "/>
            </div>
        </div>
        <div class="form-actions">
            <shiro:hasPermission name="pm:partyMember:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/>&nbsp;</shiro:hasPermission>
            <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
        </div>
    </form:form>
</body>
</html>
View Code

 

例如,使用JSTL以及EL表達式遍歷集合

 <!-- 在jsp頁面中,使用el表達式獲取map集合的數據 -->
60     <% 
61         Map<String,String> map = new LinkedHashMap<String,String>();
62         map.put("a","aaaaxxx");
63         map.put("b","bbbb");
64         map.put("c","cccc");
65         map.put("1","aaaa1111");
66         request.setAttribute("map",map);
67     %>
68     
69     <!-- 根據關鍵字取map集合的數據 -->
70       ${map.c}  
71       ${map["1"]}
72       <hr>
73       <!-- 迭代Map集合 -->
74       <c:forEach var="me" items="${map}">
75           ${me.key}=${me.value}<br/>
76       </c:forEach>

再例如遍歷其它集合(注意var保存在域中):
  <c:forEach items="${strs}" var="str">${str}<br/></c"forEach> 在這里標簽里items后不能有空格!
View Code

   【更新】 EL表達式錯誤:attribute items does not accept any expressions

        參見:http://blog.csdn.net/snihcel/article/details/7573491

  【更新】fmt標簽的使用資料參見:http://www.runoob.com/jsp/jstl-format-formatdate-tag.html 

      (所有這些JSTL都需要jstl.jar的支持!)

      要使用<fmt>首先需要引入:<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

        (可更換為統一引入的方式,例如:)

 

<%@ include file="/WEB-INF/views/modules/cms/front/include/taglib.jsp"%>

    實例:(更多API參見上述菜鳥教程鏈接)

<fmt:formatDate pattern="yyyy-MM-dd" value="${now}" />

     數字格式化實例:

 <fmt:formatNumber type="number" value="${tItem.price*tItem.ton}" pattern="0.00" maxFractionDigits="2"/>  
 
        

 

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM