JavaEE

JavaWeb基础恢复之标签、EL表达式、国际化

2018-04-23  本文已影响10人  平安喜乐698
目录
    1.JSTL标签库
    2.自定义标签
    3.EL表达式
    4.EL函数
    5.国际化
1.JSTL标签库
    旨在jsp中不再出现java代码
    为弥补html标签的不足,规范自定义标签的使用而诞生。
JSTL标签库的分类
    1.核心标签(最常用)
    2.国际化标签(I18N格式化标签)
    3.数据库标签(SQL标签,很少使用)
    4.XML标签(几乎不用)
    5.JSTL函数(EL函数)

1.1 核心标签

共13个   

按功能分为3类:
    (1)表达式控制标签:out标签、set标签、remove标签。
    (2)流程控制标签:catch标签、if标签、choose标签、when标签、otherwise标签、forEach标签、forTokens标签。
    (3)URL操作标签:import标签、url标签、redirect标签、param标签。

使用

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

表达式控制标签

<c:out>标签
    输出文本|EL(EL为空时输出空字符串)

    是否将特殊字符编码后输出(默认:true)
语法1
    <c:out value="要显示的数据对象" [escapeXml="true|false"] [default="为空时的默认值"]/>
语法2
    <c:out value="要显示的数据对象" [escapeXml="true|false"]>为空时的默认值</c:out>

例:
<c:out value="字符串" />
<c:out value="<a href='http://www.baidu.com/'>点击</a>字符串" />
<c:out value="<a href='http://www.baidu.com/'>点击</a>" escapeXml="false"/>
<c:out value="&lt未使用字符转义&gt" />
<c:out value="&lt使用字符转义&gt" escapeXml="false"/>
<c:out value="${null}" default="默认值"/></li>
<c:out value="${null}">默认值</c:out>
<c:set>标签
    设值

语法1
    <c:set value=”值” var=”name” [scope=”page|request|session|application”]/> 
语法2
    <c:set var=”name” [scope=”page|request|session|application”]>值</c:set>
语法3
    <c:set value=”值” target=”JavaBean对象” property=”属性名”/> 
语法4:
    <c:set target=”JavaBean对象” property=”属性名”>值</c:set>

例:
    <c:set var="name" value="sx" scope="page"/>
    <c:set target="${person}" property="name">hello</c:set>
<c:remove>标签
    删除变量

    <c:remove var=”变量名” [scope=”page|request|session|application”]/>

例:
    <c:remove var="age" />

流程控制标签

<c:catch>标签
    捕获异常

<c:catch [var="varName"]>可能异常代码</c:catch>

例:
    <c:catch var="errorInfo">
        <c:set target="person" property="hao"></c:set>
    </c:catch>
    异常:<c:out value="${errorInfo}" /><br />
    异常 errorInfo.getMessage:<c:out value="${errorInfo.message}" /><br />
    异常 errorInfo.getCause:<c:out value="${errorInfo.cause}" /><br />
    异常 errorInfo.getStackTrace:<c:out value="${errorInfo.stackTrace}" />
<c:if>标签
    if语句

    将结果存储在varName中
语法1
    <c:if test="testCondition" var="varName" [scope="{page|request|session|application}"]/>
语法2
    <c:if test="testCondition" [var="varName"] [scope="{page|request|session|application}"]>标签体内容</c:if>


例:
    <c:if test="${param.uname=='admin'}" var="adminchock">
        <c:out value="管理员欢迎您!"/>
    </c:if>
<c:choose>、<c:when>和<c:otherwise>标签

    <c:choose>
        <c:when test="条件1">
      //业务逻辑1
        <c:when>
        <c:when test="条件2">
      //业务逻辑2
        <c:when>
        <c:when test="条件n">
      //业务逻辑n
        <c:when>
        <c:otherwise>
      // 否则
        </c:otherwise>
    </c:choose>

例:
    <c:set var="score" value="85"/>
    <c:choose>
        <c:when test="${score>=90}">
            你的成绩为优秀!
        </c:when>
        <c:when test="${score>70 && score<90}">
            您的成绩为良好!
        </c:when>
        <c:when test="${score>60 && score<70}">
            您的成绩为及格
        </c:when>
        <c:otherwise>
            对不起,您没有通过考试!
        </c:otherwise>
    </c:choose>
<c:forEach>标签
    循环

<c:forEach 
      var=”name变量” 
      items=”Collection集合” 
      varStatus=”StatusName当前状态有4属性” 
      begin=”begin起始位置” 
      end=”end结束位置” 
      step=”step步长”>
    本体内容
</c:forEach>

varStatus
    index   int 当前循环的索引值
    count   int 循环的次数
    frist   boolean 是否为第一个位置
    last    boolean 是否为最后一个位置


例:
    <c:forEach var="fuwa" items="${list}" begin="1" end="3" step="2">
        &nbsp;<c:out value="${fuwa}"/><br/>
    </c:forEach>
<c:forTokens>标签
    遍历字符串,根据指定的字符将字符串截取

    <c:forTokens items=”strigOfTokens” 
            delims=”delimiters分隔符”
            [var=”name” 
            begin=”begin” 
            end=”end” 
            step=”len” 
            varStatus=”statusName状态同上有4属性”] >
        本体内容
    </c:forTokens>

URL操作标签

<c:import>标签
    把其他静态或动态文件包含到本JSP页面
    可以包含其他web应用中的文件,甚至是网络上的资源

语法1
    <c:import 
    url=”url” 
    [context=”context”]
    [value=”value”]
    [scope=”page|request|session|application”] 
    [charEncoding=”encoding”]/>

语法2
    <c:import 
    url=”url” 
    varReader=”name” 
    [context=”context”]
    [charEncoding=”encoding”]/>

URL为资源的路径,不存在时系统会抛出异常,应该放在<c:catch></c:catch>中。绝对路径和相对路径

例:
     <c:catch var="error1">
         <c:import url="http://wwww.baidu.com" charEncoding="utf-8"/>
     </c:catch>
<c:url>标签

语法1
    <c:url 
    value=”value” 
    [var=”name”]
    [scope=”page|request|session|application”]
    [context=”context”]/>

语法2:
    <c:url 
    value=”value” 
    [var=”name”]
    [scope=”page|request|session|application”]
    [context=”context”]>
      <c:param name=”参数名” value=”值”>
    </c:url>

例:
    <c:url value="http://www.baidu.com" var="paramUrl">
        <c:param name="userName" value="孤傲苍狼"/>
        <c:param name="pwd">123456</c:param>
    </c:url>
<c:redirect>标签
    重定向

语法1
    <c:redirect url=”url” [context=”context”]/>
语法2
    <c:redirect url=”url”[context=”context”]>
        <c:param name=”name1” value=”value1”>
    </c:redirect>

例:
    <c:redirect url="http://www.baidu.com">
        <c:param name="uname">GACL</c:param>
        <c:param name="password">123</c:param>
    </c:redirect>
2.自定义标签
自定义标签主要用于
    移除Jsp页面中的java代码
JspTag接口
    所有自定义标签的父接口,没有任何属性和方法
    有2个直接子接口:Tag接口(传统标签)、SimpleTag接口(简单标签)

SimpleTag接口
    继承自JspTag接口
    是否执行标签体、迭代标签体、对标签体内容进行修改等功能都可以在doTag方法中完成
SimpleTagSupport类
    继承自SimpleTag接口


Tag接口
    继承自JspTag接口,所有传统标签的父接口
    doStartTag()  [返回:EVAL_BODY_INCLUDE 则执行标记体 或 SKIP_BODY则跳过标记体]
    doEndTag()  [返回:EVAL_PAGE 则不忽略标记后的内容 或 SKIP_PAGE 则忽略标记后的所有内容]
    setParent()、getParent()、setPageContext()、release()
IterationTag接口(重复执行标签体)
    继承了Tag接口,实现了BodyTagSupport类
    doAfterBody()  [返回:EVAL_BODY_AGAIN则重复执行标签体内容 或 SKIP_BODY则去执行doEndTag()]
BodyTag接口(修改标签体)
    继承了IterationTag接口,实现了BodyTagSupport类
    doStartTag方法还可以返回EVAL_BODY_BUFFERED ,WEB容器就会创建一个BodyContent对象(用于捕获标签体运行结果),然后调用setBodyContent方法将BodyContent对象的引用传递给标签处理器,WEB容器接着将标签体的执行结果写入到BodyContent对象中。在标签处理器的后续事件方法中,可以通过先前保存的BodyContent对象的引用来获取标签体的执行结果,然后调用BodyContent对象特有的方法对BodyContent对象中的内容(即标签体的执行结果)进行修改和控制其输出。

2.1.1 自定义传统标签(Tag)(不用)

JSP引擎遇到自定义标签时,首先创建标签处理器类的实例对象,然后依次调用:
 1、public void setPageContext(PageContext pc)传入PageContext对象
 2、public void setParent(Tag t)将当前标签的父标签传递给当前标签处理器,如果没有则为null。
 3、public int doStartTag()处理开头
 4、public int doEndTag()处理结尾
 5、public void release()处理完后标签处理器会驻留在内存中直至停止web应用时会调用release方法。

自定义标签类

package com.sst.cx;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class CusTag  implements Tag{

    
    private PageContext pageContext;
    
    
    @Override
    public int doEndTag() throws JspException {

        System.out.println("调用doEndTag()方法");
        return 0;
    }

    @Override
    public int doStartTag() throws JspException {
        System.out.println("调用doStartTag()方法");
        HttpServletRequest request =(HttpServletRequest) pageContext.getRequest();
        JspWriter out = pageContext.getOut();
        String ip = request.getRemoteAddr();
        try {
            //这里输出的时候会抛出IOException异常
            out.write(ip);
        } catch (IOException e) {
            //捕获IOException异常后继续抛出
            throw new RuntimeException(e);
        }
        return 0;
    }

    @Override
    public Tag getParent() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void release() {
        System.out.println("调用release()方法");
    }

    @Override
    public void setPageContext(PageContext pageContext) {
        System.out.println("setPageContext(PageContext pageContext)");
        this.pageContext = pageContext;
    }

    @Override
    public void setParent(Tag arg0) {
        // TODO Auto-generated method stub  
    }
}

MyCusTag.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用来添加对taglib(标签库)的描述 -->
    <description>自定义标签库</description>
    <!--taglib(标签库)的版本号 -->
    <tlib-version>1.0</tlib-version>
    <short-name>MyCusTag</short-name>
    <!-- 
        为自定义标签库设置一个uri,uri以/开头,/文件名 ,
        在Jsp页面中引用标签库时,需要通过uri找到标签库
        在Jsp页面中就要这样引入标签库:<%@taglib uri="/xxx" prefix="sx"%>
    -->
    <uri>/MyCusTag</uri>
    
    <!--一个taglib(标签库)中包含多个自定义标签,每一个自定义标签使用一个tag标记来描述  -->
    <!-- 一个tag标记对应一个自定义标签 -->
     <tag>
        <description>这个标签的作用是用来输出客户端的IP地址</description>
        <!-- 
            为标签处理器类配一个标签名,在Jsp页面中使用标签时是通过标签名来找到要调用的标签处理器类的
            通过viewIP就能找到对应的类
         -->
        <name>viewIP</name>
        <!-- 标签对应的处理器类-->
        <tag-class>com.sst.cx.CusTag</tag-class>
        <body-content>empty</body-content>
    </tag>
    
</taglib>

显示界面jsp

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

<%@taglib uri="/MyCusTag" prefix="sx" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.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>
    <sx:viewIP/>
  </body>
</html>

2.1.2 自定义传统标签(TagSupport)

常用
    按2.1.1的步骤,只是处理类不一样

    控制jsp页面某一部分内容是否执行。
        继承TagSupport覆写doStartTag() 返回不同常量
    控制整个jsp页面是否执行。
        继承TagSupport覆写doEndTag() 返回不同常量
    控制jsp页面内容重复执行。
        继承TagSupport覆写doStartTag()返回Tag.EVAL_BODY_INCLUDE、doEndTag()返回不同常量
    修改jsp页面内容输出
        继承TagSupport覆写doStartTag()返回BodyTag.EVAL_BODY_BUFFERED、doEndTag()如下:

    public int doEndTag() throws JspException {
        //this.getBodyContent()得到代表标签体的bodyContent对象
        BodyContent bodyContent = this.getBodyContent();
        //拿到标签体
        String content = bodyContent.getString();
        //修改标签体里面的内容,将标签体的内容转换成大写
        String result = content.toUpperCase();
        try {
            //输出修改后的内容
            this.pageContext.getOut().write(result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
        return Tag.EVAL_PAGE;
    }

2.2 自定义简单标签

 SimpleTag接口
    实现SimpleTag接口的标签通常称为简单标签
 SimpleTagSupport类
    继承自SimpleTag接口
方法的执行顺序
   1.setJspContext() 传入pageContext对象
   2.有父标签则调用setParent() 传入父标签处理对象。getParent() 可获取父标签处理对象
   3.设置了属性则分别设值
   4.有标签体则调用setJspBody() 传入代表标签体的JspFragment对象
   5.doTag() 所有逻辑(输出、迭代、修改标签体内容)
       抛出javax.servlet.jsp.SkipPageException异常,则不再执行标签后的所有页面内容


JspFragment对象有2个方法
   getJspContext方法
    用于返回代表调用页面的JspContext对象
  public abstract void invoke(java.io.Writer out)
       传StringWriter输出流对象,则标签内容写入该流(用于可以修改标签内容再输出)
       传null则将标签内容输出到浏览器(将执行结果写入到JspContext.getOut()方法返回的输出流对象中),不调用则不会输出标签体内容,多次调用会多次输出

处理类

package com.sst.cx;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class SimpleTag extends SimpleTagSupport {

    /* 所有的业务逻辑
     */
    @Override
    public void doTag() throws JspException, IOException {
        //得到代表jsp标签体的JspFragment
        JspFragment jspFragment = this.getJspBody();
        
        //得到jsp页面的的PageContext对象
        //PageContext pageContext = (PageContext) jspFragment.getJspContext();
        //调用JspWriter将标签体的内容输出到浏览器
        //jspFragment.invoke(pageContext.getOut());

        /* 1.注释掉,则不再输出标签体
         */
        // 将标签体的内容输出到浏览器
//        jspFragment.invoke(null);
        
       /*
        2.迭代
          
        for (int i = 0; i < 5; i++) {
            // 将标签体的内容输出到浏览器
            jspFragment.invoke(null);
        }
       */


        /*
         3.修改内容
          
        StringWriter sw = new StringWriter();
        //将标签体的内容写入到sw流中
        jspFragment.invoke(sw);
        //获取sw流缓冲区的内容
        String content = sw.getBuffer().toString();
        content = content.toUpperCase();
        PageContext pageContext = (PageContext) this.getJspContext();
        //将修改后的content输出到浏览器中
        pageContext.getOut().write(content);
        */
        

        /*
         4.是否执行标签后的所有页面内容

          throw new SkipPageException();
         */
    }
}

tld中+

<!--
tld通常放在WENB_INF下

引用标签库方式一
        <%@taglib uri="/MyCusTag" prefix="hello" %> 
引用标签库方式二(多个uri相同时)
        <%@taglib uri="/WEB-INF/MyCusTag.tld" prefix="hello"%>
-->

      <tag>
        <description>SimpleTag(简单标签)</description> 
        <name>simple</name>
        <!-- 标签对应的处理器类-->
        <tag-class>com.sst.cx.SimpleTag</tag-class>
        <!--
        tld文件中有四种标签体类型 
            empty         表示没有标签体
            JSP           表示有标签体,可以是任意内容
            scriptless    表示标签体的内容不允许是java脚本代码
            tagdepentend  表示标签体里面的内容是给标签处理器类使用的
        在简单标签(SampleTag)中标签体body-content的值只允许是empty和scriptless、tagdependent,不允许设置成JSP否则异常
        在传统标签中标签体body-content的值只允许是empty和JSP
        -->
        <body-content>scriptless</body-content>        
      </tag>

jsp+

<%@taglib uri="/MyCusTag" prefix="hello" %> 

<hello:simple>nihao</hello:simple>

标签带有属性

如果标签的属性值是8种基本数据类型,JSP引擎会自动将字符串转换成相应的类型,但如果是复合数据类型则无法自动转换,必须是EL表达式
 步骤

处理类中+
    private int count;
    public void setCount(int count) {
        this.count = count;
    }
doTag()中使用+
    for (int i = 0; i < this.count; i++) {
        // 将标签体的内容输出到浏览器
        jspFragment.invoke(null);
    }

tld文件的tag中+
<attribute>
    <description>描述</description>
    <!-- 属性名 -->
    <name>count</name>
    <!-- 是否必填 -->
    <required>true</required>
    <!-- 是否可以是一个表达式-->
    <rtexprvalue>true</rtexprvalue>
</attribute>

jsp改为
<hello:simple count="3">nihao</hello:simple>
3.EL表达式
EL(Expression Language)
    用于替换JSP页面中的脚本表达式
1、获取数据
    某个web域 中的对象
    javabean的属性
    list集合
    map集合
    数组
2、执行运算
    关系运算、逻辑运算和算术运算
3、获取web隐式对象
4、调用Java方法
    可以自定义EL函数,以在JSP页面中通过EL表达式调用Java类的方法。
获取数据
 
 ${标识符}
 实质:调用pageContext.findAttribute(page->request->session->application),找不到则返回空字符串

 ${name}    等同于 pageContext.findAttribute("name")
 ${list[1].name}
 ${map["1"]}
 ${person.age}
 ${person.address.name}
 
 <c:forEach var="person" items="${list}">
    ${person.name}
 </c:forEach>
 <c:forEach var="me" items="${map}">
    ${me.key}=${me.value}<br/>
 </c:forEach>
执行运算

    关系运算
        == eq
        != ne
        < lt
        > gt
        <= le
        >= ge
 
    逻辑运算
        &&  and
        ||  or
        !   not
    计算运算符
        +
        -
        *
        /
    empty运算   ${!empty(list)}
    二元表达式   ${user!=null?user.name :""}
    [] 和 . 号运算符
 
 
 ${365+24}
 ${user == null}
 ${empty(emptyList)}
获取web隐式对象
     11个
 pageContext        pageContext对象
 pageScope          page域
 requestScope       request域
 sessionScope       session域
 applicationScope   application域
 param              所有请求参数
 paramValues        所有请求参数
 header             所有http请求头字段
 headerValues       所有http请求头字段
 cookie             所有cookie
 initParam          所有web应用初始化参数
 
 例:
 ${requestScope.name}
 ${pageContext.request.contextPath}/servlet/RegisterServlet
 ${param.username}
 ${paramValues.like[0]}
 ${header["Accept-Encoding"]}
 ${cookie.JSESSIONID.value}
 ${cookie.JSESSIONID.name}
 
 ${initParam.xxx}
 <context-param>
    <param-name>xxx</param-name>
    <param-value>yyyy</param-value>
 </context-param>
 调用Java自定义方法
    只能是Java类的静态方法
 
    1、编写一个Java类的静态方法
   2、编写标签库描述符(.tld xml)文件,在tld文件中描述自定义函数。
   3、在JSP页面中导入和使用自定义函数

例:

处理类

package com.sst.cx;

public class CusFilter {
       public static String filter(String message) {

            if (message == null)
                return (null);

            char content[] = new char[message.length()];
            message.getChars(0, message.length(), content, 0);
            StringBuffer result = new StringBuffer(content.length + 50);
            for (int i = 0; i < content.length; i++) {
                switch (content[i]) {
                case '<':
                    result.append("&lt;");
                    break;
                case '>':
                    result.append("&gt;");
                    break;
                case '&':
                    result.append("&amp;");
                    break;
                case '"':
                    result.append("&quot;");
                    break;
                default:
                    result.append(content[i]);
                }
            }
            return (result.toString());
        }
}

customEL.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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 web-jsptaglibrary_2_0.xsd">
 <tlib-version>1.0</tlib-version>
 <short-name>EL Function</short-name>
 <!-- 
     自定义EL函数库的引用URI,
     在JSP页面中可以这样引用:<%@taglib uri="/ELFunction" prefix="fn" %> 
 -->
 <uri>/ELFunction</uri>
 
 <!--<function>元素用于描述一个EL自定义函数 -->
  <function>
        <description>html标签转义处理方法</description>
        <!--<name>子元素用于指定EL自定义函数的名称-->
        <name>filter</name>
        <!--<function-class>子元素用于指定完整的Java类名-->
        <function-class>com.sst.cx.CusFilter</function-class>
        <!--<function-signature>子元素用于指定Java类中的静态方法的签名,
            方法签名必须指明方法的返回值类型及各个参数的类型,各个参数之间用逗号分隔。-->
        <function-signature>java.lang.String filter(java.lang.String)</function-signature>
    </function>
 
</taglib>

使用页jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/ELFunction" prefix="fn" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.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>
     ${fn:filter("<a href='hh'>点点</a>")}
  </body>
</html>
 注意
    1.编写完标签库描述文件后,需要将它放置到<web应用>\WEB-INF目录中或WEB-INF目录下的除了classes和lib目录之外的任意子目录中。
   2.TLD文件中的<uri> 元素用指定该TLD文件的URI,在JSP文件中需要通过这个URI来引入该标签库描述文件。
   3.<function>元素用于描述一个EL自定义函数,其中:
   4.<name>子元素用于指定EL自定义函数的名称。
   5.<function-class>子元素用于指定完整的Java类名,
   6.<function-signature>子元素用于指定Java类中的静态方法的签名,方法签名必须指明方法的返回值类型及各个参数的类型,各个参数之间用逗号分隔。
 
    <%@ page isELIgnored="false" %>
保留关键字
   And、 Or、 No、 instanceof、 eq、 ne、 lt、 empty、 gt、 le、 ge、 div、true、false、mod、null
4.EL函数
jsp中+ 
  <%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
 
 转小写
    ${fn:toLowerCase("Www.CNBLOGS.COM")}
 转大写
    ${fn:toUpperCase("cnblogs.com")}
 删除首尾空格
    ${fn:trim("  cnblogs.com  ")}
 返回一个集合或数组大小
    ${fn:length(list)}
 字符串的长度
    ${fn:length("cnblogs.com")}
 分割
    ${fn:split("cnblogs.com",".")[0]}
 拼接
    ${fn:join(StringArray,".")}
 第一次匹配的索引
    ${fn:indexOf("www.iteye.com","eye")}
 是否包含
    ${fn:contains("sing11","sing")}
 是否以指定字符串开头
    ${fn:startsWith("www.iteye.com","iteye")}
 是否以指定字符串结尾
    ${fn:endsWith("www.iteye.com","com")}
 替换指定字符
    ${fn:replace("www iteye com", " ", ".")}
 字符串截取
    ${fn:substring("www.it315.org", 4, 9)}
    ${fn:substringAfter("www.it315.org",".")}
    ${fn:substringBefore("www.it315.org",".")}
5. 国际化
国际化(internationalization)又称为 i18n
    针对不同地区和国家的访问,提供相应的、符合来访者阅读习惯的页面或数据。
 
处理2种情况:
    1.静态数据(固定文本,如导航栏标题)
    2.动态数据(动态产生)

静态数据

新建File(properties),一组properties文件称之为一个资源包。
    myproperties_en.properties
    myproperties_zh.properties
    myproperties.properties
内容格式
    键=值
    properties使用ASCII进行编码,不能直接写中文(终端输入native2ascII再输入中文回车可获取编码)
 jsp中使用:

 <%
 //加载i18n资源文件,request.getLocale()获取访问用户所在的国家地区
 ResourceBundle myResourcesBundle = ResourceBundle.getBundle("com.sst.cx.resource.myproperties",request.getLocale());
 %>
 <%=myResourcesBundle.getString("username")%>
 
 或者
 
 <%--导入国际化标签库 --%>
 <%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
 
 <fmt:setBundle var="bundle"  basename="com.sst.cx.resource.myproperties" scope="page"/>
 <form action="">
    <fmt:message key="username" bundle="${bundle}"/><input type="text" name="username"><br/>
    <fmt:message key="password" bundle="${bundle}"/><input type="password" name="password"><br/>
    <input type="submit" value="<fmt:message key="submit" bundle="${bundle}"/>">
 </form>
类中使用:

// 资源包基名(包名+myproperties)
String basename = "com.sst.cx.resource.myproperties";
// 设置语言环境
Locale currentLocale = Locale.getDefault();
currentLocale=Locale.CHINA;//中文
currentLocale=Locale.US;//英文
// 根据基名和语言环境加载对应的语言资源文件
ResourceBundle myResources = ResourceBundle.getBundle(basename,currentLocale);

String username = myResources.getString("username");

动态数据

使用相关API处理

 Locale类
    代表一个特定的地理,政治、文化区域
 DateFormat类
    日期格式化
    Date date = new Date(); // 当前时间
    // 输出日期部分
    DateFormat df = DateFormat.getDateInstance(DateFormat.FULL,Locale.CHINA);
    // 输出时间部分
    DateFormat df = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CHINA);
    // 输出日期和时间部分
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG,Locale.CHINA);
    //
    String result = df.format(date);

    // 字符串->Date
    String s = "10-9-26 下午02时49分53秒";
    df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG,Locale.CHINA);
    Date d = df.parse(s);
 NumberFormat类
    数字格式化
    int price = 89;
    // 钱->字符串
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
    String result = nf.format(price);
    System.out.println(result);
    // 字符串->钱
    String s = "¥89.00";
    nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
    Number n = nf.parse(s);
    System.out.println(n.doubleValue());
    // 小数->百分号
    double num = 0.5;
    nf = NumberFormat.getPercentInstance();
    System.out.println(nf.format(num));
 
 MessageFormat类
    文本格式化
    // 模式字符串
    String pattern = "On {0}, a hurricance destroyed {1} houses and caused {2} of damage.";
    // 实例化MessageFormat对象,并装载相应的模式字符串
    MessageFormat format = new MessageFormat(pattern, Locale.CHINA);
    Object arr[] = {new Date(), 99, 100000000};
    // 格式化模式字符串,参数数组中指定占位符相应的替换对象
    String result = format.format(arr);
    System.out.println(result);
 
 占位符3格式
    {argumentIndex}: 0-9 之间的数字,表示要格式化对象数据在参数数组中的索引号
   {argumentIndex,formatType}: 参数的格式化类型
   {argumentIndex,formatType,FormatStyle}: 格式化的样式,它的值必须是与格式化类型相匹配的合法模式、或表示合法模式的字符串。
    String pattern = "At {0, time, short} on {0, date}, a destroyed {1} houses and caused {2, number, currency} of damage.";

上一篇 下一篇

猜你喜欢

热点阅读