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"/>  




原文地址:https://www.cnblogs.com/jiangbei/p/6690902.html