java web复习 day12(EL表达式,sun el函数,web国际化,文件上传与下载)

        day12,明天又要去武汉开始一段新的求职历练,加油吧!

  一、EL表达式获取数据

        EL表达式全名为express language,其主要作用是:获取数据,执行运算,获取web开发常用对象,调用java方法。接下来,我们用一些实例来显示EL表达式的威力。

        首先我们简单地从pageContext域中获取数据中获取数据,

 <body>
    	<%
    		request.setAttribute("name", "aaaaa");
    	 %>
    	 ${name}
  </body>

        其中${name}实际上执行的代码是:pageContext.findAttribute("name");

        findAttribute方法,在四大域中搜寻属性,搜寻的顺序是page域、request域、session域、application域,从小域到大域开始搜索,如果搜索到就直接获取该值,如果所有域中都找不到,返回一个null.

        (在这里新建一个person类,有以下属性,其中address有name属性)

        在jsp页面中,使用el表达式可以获取bean的属性,获取bean属性的属性:

<body>         
        <%
    	 	Person p = new Person();
    	 	p.setName("crush");
                Address address = new Address();
                p.setAddress(address);    
                request.setAttribute("person", p);
    	  %>
    	  
    	  ${person.name}
          ${person.address.name}
</body>

        在jsp页面中,使用el表达式获取list集合中指定位置的数据:

<body>
<% 
	    	Person p1 = new Person();
	    	p1.setName("aa111");
	    	
	    	Person p2 = new Person();
	    	p2.setName("bb");
	    	
	    	List list = new ArrayList();
	    	list.add(p1);
	    	list.add(p2);
	    	
	    	request.setAttribute("list",list);
    	%>
    
   		 ${list[1].name }
</body>

迭代集合:

<body>
         <c:forEach var="person" items="${list}">
    	  	${person.name }
    	 </c:forEach>
</body>

在jsp页面中,使用el表达式获取map集合的数据:

<body>
<% 
    	Map map = new HashMap();
    	map.put("a","aaaa");
    	map.put("b","bbbb");
    	map.put("c","cccc");
    	map.put("1","1111");
    	request.setAttribute("map",map);
    %>
    
  	${map.c } 
  	${map["1"] }<!-- 根据关键字取map集合的数据 -->
</body>

迭代map集合:

<body>
     <c:forEach var="me" items="${map}">
  	${me.key}=${me.value }
     </c:forEach>
</body>
这里注意一点,被迭代的map输出的是一个个map.Entry对象,所以var为me。

二、EL表达式执行运算,JSTL一些标签的使用

数学计算,和判断

<body>
    	${365*2 } <!-- 730 -->
    	${user==null } <!-- true -->
  </body>

在非空条件下遍历集合

<body>   
<% 
    	List list = new ArrayList();
    	list.add("a");
    	list.add("b");
    	
    	request.setAttribute("list",list);
    %>
    
    <c:if test="${!empty(list)}">   <!-- ${empty(list)} 用预判空很好用-->
    	<c:forEach var="str" items="${list}">
    		${str }
    	</c:forEach>
    </c:if>
</body>

二元表达式的使用

<body>
 <% 
    	session.setAttribute("user",new User("vvvv")); //显示vvvv
    	//session.removeAttribute("user");   //显示对不起,您没有登陆
    %>
    ${user==null? "对不起,您没有登陆 " : user.username }
</body>

数据回显

  <body> 
    <%
    	User user = new User();
    	user.setGender("male");
    	
    	request.setAttribute("user",user);
     %>
     
     <input type="radio" name="gender" value="male" ${user.gender=='male'?'checked':'' }>男
     <input type="radio" name="gender" value="female" ${user.gender=='female'?'checked':'' }>女
  </body>
<!--男选项会被选中-->

三、EL隐式对象(侵删)


<body>
    
    ${pageContext }  <!-- pageContext.findAttribute("name") -->
    
    
    <br/>
    
    <br/>---------------从指定的page域中查找数据------------------------<br/>
    <% 
    	pageContext.setAttribute("name","aaa");  //map
    %>
    ${pageScope.name }
   
   
   	<br/>---------------从request域中获取数据------------------------<br/>
   	<% 
   		request.setAttribute("name","bbb");  //map
   	%>
   	${requestScope.name }
   	
   	<br/>---------------从session域中获取数据------------------------<br/>
   	${sessionScope.user }
   	
   	
   	<br/>--------------获得用于保存请求参数map,并从map中获取数据------------------------<br/>
   	<!-- http://localhost:8080/day12/3.jsp?name=aaa  -->
   	${param.name } 
   	
   	<br/>--------------paramValues获得请求参数 //map{"",String[]}------------------------<br/>
   	<!-- http://localhost:8080/day12/3.jsp?like=aaa&like=bbb -->
   	${paramValues.like[0] }  
   	${paramValues.like[1] } 
   	
   	<br/>--------------header获得请求头------------------------<br/>
   	${header.Accept } 
   	${header["Accept-Encoding"] }
   	
   	
   	<br/>--------------获取客户机提交的cookie------------------------<br/>
   	<!-- 从cookie隐式对象中根据名称获取到的是cookie对象,要想获取值,还需要.value -->
   	${cookie.JSESSIONID.value }  //保存所有cookie的map
   	
   	
   	<br/>--------------获取web应用初始化参数------------------------<br/>
   	${initParam.xxx }  //servletContext中用于保存初始化参数的map
   	${initParam.root }
   	
  </body>

四、使用el调用java方法

1.(视频中的方法)开发自己的标签函数过程

1、编写一个包含静态方法的类

package cn.itcast;

public class HtmlFilter {

     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("<");
                    break;
                case '>':
                    result.append(">");
                    break;
                case '&':
                    result.append("&");
                    break;
                case '"':
                    result.append(""");
                    break;
                default:
                    result.append(content[i]);
                }
            }
            return (result.toString());

        }
}
2、在web-inf\目录下新建一个tld文件,对想被jsp页面调用的函数进行描述
<?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>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>SimpleTagLibrary</short-name>
    <uri>/itcast</uri>
    
    <function>
        <name>filter</name>
        <function-class>cn.itcast.HtmlFilter</function-class>
        <function-signature>java.lang.String filter(java.lang.String)</function-signature>
    </function>
</taglib>


3、在jsp页面导入标签库,并调用el函数
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/itcast.tld" prefix="fn" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP '4.jsp' starting page</title>
  </head>
 
  <body>
 
      ${fn:filter("<a href=''>这是超链接</a>") }
      
  </body>
</html>

五、使用常用的sun  el函数(官方轮子,最为好用!!)

这是jstl的一些标签函数,除了去除jsp中的脚本代码,还十分好用,在使用之前要导入标签库:

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

转大写/转小写:

${fn:toUpperCase("adasdadasd") }
${fn:toLowerCase("ADSADASDA") }

得到集合长度:

        <%
    		List list = Arrays.asList("1","2","3");
    		request.setAttribute("list",list);
    	 %>
    	 ${fn:length(list) }
    	 ${fn:length("aaaaa") }

分割字符串,连接字符串:

${fn:split("aaa.bbb.ccc",".")[1] } <!-- 获取分割字符串之后的得到的数组的第二个元素 -->
${fn:join(fn:split("www,flx,com",","),".") }<!-- 以,来分割字符串之后用.来连接字符串 -->

使用el函数回显数据:       

         <%
       	 	User user = new User();
       	 	String likes[] = {"dance","sing"};
       	 	user.setLikes(likes);
       	 	request.setAttribute("user", user);
       	  %>
       	  
       	 <input type="checkbox" name="like" value="sing" ${fn:contains(fn:join(user.likes,","),"sing")?'checked':'' }>唱歌
         <input type="checkbox" name="like" value="dance"  ${fn:contains(fn:join(user.likes,","),"dance")?'checked':'' }>跳舞
     	 <input type="checkbox" name="like" value="basketball"  ${fn:contains(fn:join(user.likes,","),"basketball")?'checked':'' }>蓝球
      	 <input type="checkbox" name="like" value="football"  ${fn:contains(fn:join(user.likes,","),"football")?'checked':'' }>足球
         <br/><hr><br/>
转义函数标签:
 ${fn:escapeXml("<a href=''>点点</a>") }

url标签,好用!!做超链接,带参数。

<br/>-----------------------c:url标签(重点)--------------------------------------<br/>
    <c:url value="/servlet/ServletDemo1" var="servletdemo1">
    	<c:param name="name" value="中国"/>
    	<c:param name="password" value="我是一个"/>
    </c:url>
    <a href="${servletdemo1 }">点点</a>

六、web国际化

web国际化是为了软件开发时,要使它能同时应对世界不同地区和国家的访问,并针对不同地区和国家的访问,提供相应的、符合来访者阅读习惯的页面或数据。它的要求是对于程序中固定使用的文本元素,例如菜单栏、导航条等中使用的文本元素、或错误提示信息,状态信息等,需要根据来访者的地区和国家,选择不同语言的文本为之服务,同时对于程序动态产生的数据,例如(日期,货币等),软件应能根据当前所在的国家或地区的文化习惯进行显示。

开发步骤是:

1.在src目录下新建properties文件,用于保存不同语言环境下的,所显示的文本。(需要一个默认的资源文件myproperties.properties)

eg:

username=username
password=password
submit=submit

message=At {0, time, short} on {0, date}, a destroyed {1} houses and caused {2, number, currency} of damage.

在保存中文属性值时,需要在

中操作,不然会产生编码错误。

第二步,我们从中获取

package cn.itcast.i18n;

import java.util.Locale;
import java.util.ResourceBundle;

public class Demo1 {

	public static void main(String[] args) {
		
		ResourceBundle bundle = ResourceBundle.getBundle("cn.itcast.resource.myproperties",Locale.CHINA);
		//该方法用于获得资源文件,第二个参数指代当地时间。
		String username = bundle.getString("username");
		String password= bundle.getString("password");
		
		System.out.println(username);
		System.out.println(password);
	}

}

在JSP页面中,我们通过fmt标签来获取

首先导入fmt的标签库

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

<body>
 
  	
    <fmt:setBundle var="bundle"  basename="cn.itcast.resource.myproperties" scope="page"/>
    <!--获取base资源文件-->
    <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> 
  </body>

格式化日期:

Date date = new Date();  //当前这一刻的时间(日期、时间)
		
		//输出日期部分
		DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, Locale.GERMAN);
		String result = df.format(date);
		System.out.println(result);
		
		//输出时间部分
		df = DateFormat.getTimeInstance(DateFormat.FULL, Locale.CHINA);
		result = df.format(date);
		System.out.println(result);
		
		
		//输出日期和时间
		df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, Locale.CHINA);
		result = df.format(date);
		System.out.println(result);
		
		
		//把字符串反向解析成一个date对象
		String s = "10-9-26 下午02时49分53秒";
		df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, Locale.CHINA);
		Date d = df.parse(s);
		System.out.println(d);

格式化数字:

package cn.itcast.i18n;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class Demo3 {

	/**
	 * NumberFormat实例
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException {
		
		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()+1);
		
		double num = 0.5;
		nf = NumberFormat.getPercentInstance();
		System.out.println(nf.format(num));
	}

}

向占位符中添加文本:

package cn.itcast.i18n;

import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;

public class Demo4 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String pattern = "On {0}, a hurricance destroyed {1} houses and caused {2} of damage.";
		
		MessageFormat format = new MessageFormat(pattern,Locale.CHINA);
		Object arr[] = {new Date(),99,100000000};
		
		String result = format.format(arr);
		System.out.println(result);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值