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);
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章