1.EL 表達式
1.1 EL 語法介紹
JSP EL語言定義 E L(Expression Language)
- 作用:簡化 JSP 的腳本編寫较幌,主要是替代 JSP 腳本表達式,EL主要是作頁面輸出.
學(xué)習(xí) EL 表達式主要的目標是編寫無腳本的 JSP少欺,因為EL表達式更看起來像標簽 - 語法:
${表達式}
注意:EL 表達式只能獲取域中的數(shù)據(jù)
1.2 EL 獲取各種類型的數(shù)據(jù)
注意:EL 獲取對象中的數(shù)據(jù)要跟對象中的屬性喳瓣,不要跟字段名稱
EL 不能再 JSP 腳本片段出現(xiàn)獲取簡單數(shù)類型
<%
//pageContext對象中的setAttribute 默認放于page域。
String name = "zhangsan";
pageContext.setAttribute("name", name);
%><br/>
el表達式:${name }<Br/>
- 獲取引用數(shù)據(jù)類型
// 使用Servlet 在放數(shù)據(jù)
UserModel um = new UserModel();
um.setName("lisi");
um.setAge(18);
LocalModel l = new LocalModel();
l.setShengfen("重慶");
l.setCity("江津");
um.setLocal(l);
req.setAttribute("user", um);
req.getRequestDispatcher("/demo3.jsp").forward(req, resp)
// 在JSP 中使用 EL 來獲取數(shù)據(jù)
取對象:${user }<Br/>
用戶的名稱:${user.name }<Br/>
用戶的年齡:${user.age }<Br/>
用戶的所屬的省份:${user.local.shengfen }<Br/>
用戶的所屬的城市:${user.local.city }<Br/>
- 如何來獲取集合數(shù)據(jù)(List),但是 EL 取不了SET 集合存儲數(shù)據(jù)赞别,下午學(xué)了 JSTL 標簽就可以取
// 在 Servlet 放數(shù)據(jù)
List<UserModel> users = new ArrayList<UserModel>();
for (int i = 0; i < 3; i++) {
UserModel u = new UserModel();
u.setName("test" + i);
users.add(u);
}
req.setAttribute("users", users);
req.getRequestDispatcher("/demo3.jsp").forward(req, resp);
// 在 Jsp 中來取數(shù)據(jù)
取到了集合:${users }<br>
取第一個元素:${users[0]}<br/>
取第一個元素中的名稱:${users[0].name }<br/>
取第一個元素中的名稱:${users[0]["name"] }<br/>
取到了集合:${users.get(0).name}<br>
- 獲取 Map 類型中的數(shù)據(jù)
// Servlet 放入 map 數(shù)據(jù)
Map<String, UserModel> maps = new HashMap<String, UserModel>();
UserModel um1 = new UserModel();
um1.setName("value1");
UserModel um2 = new UserModel();
um1.setName("value2");
maps.put("um1", um1);
maps.put("um2@", um2);
// 放入map 對象數(shù)據(jù)
req.setAttribute("maps", maps);
req.getRequestDispatcher("/demo3.jsp").forward(req, resp);
// JSP el來獲取數(shù)據(jù)
<%-- 以下是集合map對象中數(shù)據(jù)取法 調(diào)用對象屬性可以使用 --%>
map類型對象實例:${maps}<br/>
取um1key對應(yīng)的對象:${maps.um1 }<Br/>
取um1key對應(yīng)的對象:${maps["um1"] }<Br/>
取um2key對應(yīng)的對象:${maps["um2@"]}<Br/>
1.3 EL 表達式支持的運算符
- EL 表達式支持的運算一般只是一些簡單的運算符畏陕。
- EL 還支持三目運算符: 表達式 ?值1:值2.
- EL 還提供一個empty 運算符:判斷對象是否為null,字符串String 是否為 " " 空串仿滔,返回true惠毁,反之 為false
1.4 EL 表達式中的11 個內(nèi)置對象
內(nèi)置對象引用名稱 | 內(nèi)置對象具體的類型 | 說明 |
---|---|---|
pageScope | java.util.Map | Page作用域 |
requestScope | java.util.Map | request作用域 |
sessionScope | java.util.Map | session作用域 |
applicationScope | java.util.Map | application作用域 |
pageContext | org.apache.jasper.runtime.PageContextImpl | 當前頁面的pageContext |
initParam | java.util.Map | 應(yīng)用上下文參數(shù) |
cookie | java.util.Map | 獲取請求中的cookie |
param | java.util.Map | 獲取請求對象中的參數(shù) |
paramValues | java.util.Map | 獲取請求對象中參數(shù)對應(yīng)的多個值 |
header | java.util.Map | 獲取請求頭 |
headerValues | java.util | 獲取請求頭對應(yīng)的多個值 |
2.JSTL 標簽
2.1 JSTL 概述
注意:JSTL標簽一般跟EL表達式聯(lián)合使用
- JSTL(JSP Standard Tag Library犹芹,JSP標準標簽庫) Jsp中的技術(shù)規(guī)范
- Apache 提供 JSP 中的 JSTL 標簽實現(xiàn)
依賴包:taglibs-standard-impl-1.2.5.jar
taglibs-standard-spec-1.2.5.jar
在 JSP 中引入核心標簽庫:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
2.2 JSTL 標簽分類
- 國際化標簽 fmt
- sql 標簽 sql
- xml 標簽 xml
- 核心標簽 core
2.2 JSTL 核心標簽應(yīng)用
- 迭代標簽 forEach
跌代標簽: items 屬性:支持 el 表達式,定義一個需要遍歷的集合
var 屬性:跌代過程中取的每一個元素,放入到page域中鞠绰,并給這個元素取個別名<Br/>
varStatus 屬性:每次跌代元素記錄的狀態(tài)保存到一個對象中并存到page域中腰埂,給這個狀態(tài)取個別名
begin 屬性: 下標索引從0開始計算,從哪個索引值開始取數(shù)據(jù)
end 屬性:結(jié)束索引下標值
step 屬性:設(shè)置遍歷數(shù)據(jù)的步調(diào)
- if 標簽
test 屬性:條件蜈膨,支持el
scope 屬性:支持 el 表示把數(shù)據(jù)存到哪個域屿笼。
var 屬性: 存域中數(shù)據(jù)別個別名
3.JSP 做驗證碼
作用:防止惡意破解密碼、刷票翁巍、論壇灌水驴一,有效防止某個黑客對某一個特定注冊用戶用特定程序暴力破解方式進行不斷的登陸嘗試
<%@ page contentType="image/jpeg" language="java" import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" pageEncoding="utf-8"%>
<%!
//生成 隨機的顏色
Color getRandColor(int fc,int bc){
Random random = new Random();
if(fc > 255){
fc = 255;
}
if(bc < 255){
bc = 255;
}
int r = fc +random.nextInt(bc-fc);
int g = fc +random.nextInt(bc-fc);
int b = fc +random.nextInt(bc-fc);
return new Color(r,g,b);
}
%>
<%
//設(shè)置頁面不緩存 告訴瀏覽器不緩存數(shù)據(jù)
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-catch");
response.setDateHeader("Expires",0);
//在內(nèi)存中創(chuàng)建圖象
int width = 60;
int height = 20;
// 生成一個圖片緩存區(qū) 畫板
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//創(chuàng)建圖象 通過畫板拿到畫筆
Graphics g = image.getGraphics();
//生成隨機對象
Random random = new Random();
//設(shè)置背景色
g.setColor(getRandColor(200,250));
//在畫板上畫一個矩形
g.fillRect(0,0,width,height);
//設(shè)置畫筆的字體
g.setFont(new Font("Tines Nev Roman",Font.PLAIN,18));
//設(shè)置畫筆的顏色
g.setColor(getRandColor(160,200));
//隨機產(chǎn)生干擾線
for(int i = 0; i < 255; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
}
//隨機產(chǎn)生認證碼,4位數(shù)字
String sRand = "";
for(int i = 0; i < 4; i++){
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
//將認證碼顯示到圖象中
g.setColor(new Color(20 + random.nextInt(110),20 + random.nextInt(110),20 + random.nextInt(110)));
g.drawString(rand,13*i+6,16);
}
// 重點:產(chǎn)生的驗證碼值,要保存到session 域中
session.setAttribute("rCode",sRand);
//圖像生效
g.dispose();
//輸出圖像到頁面
ImageIO.write(image,"JPEG",response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
- 介紹 google 驗證碼組件 kaptcha
filters-2.0.235.jar
kaptcha-0.0.9.jar
4.文件上傳
4.1 文件上傳開發(fā)步驟:
- 導(dǎo)包
commons-fileupload-1.3.2.jar
commons-io-1.4.jar - 開發(fā)上傳頁面 JSP
<!-- 開發(fā)上傳的表單灶壶,表單的提交方式必須為 post
表單的編碼方式需要改為:enctype = multipart/form-data -->
<form action="" method="post" enctype="multipart/form-data">
文件上傳:<input type="file" name="imagFile"/><Br/>
<input type="submit" value="上傳"/>
</form>
- 文件處理類 Servlet
package com.xingxue.jsp.util;
import java.io.File;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUtil {
public static void handlerFile(HttpServletRequest request) {
// Create a factory for disk-based file items
// 創(chuàng)建一個針對 磁盤文件的條目的工廠肝断,該工程用于創(chuàng)建文件的條目
DiskFileItemFactory factory = new DiskFileItemFactory();
// 獲取應(yīng)用的上下文對象 ServletContext.
ServletContext servletContext = request.getServletContext();
// 通過該對象ServletContext 獲取臨時目錄,可以獲取到上傳文件的臨時保存路徑
// javax.servlet.context.tempdir 臨時目錄的常量
File repositoryDoc = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
// 設(shè)置 工廠的倉庫位置
factory.setRepository(repositoryDoc);
// ServletFileUpload 該類用于處理上傳文件(提取數(shù)據(jù))
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 處理請求
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
// isFormFiled是用于判斷是否是文本數(shù)據(jù)驰凛,如果是文本數(shù)據(jù)胸懈,返回true
if (!fileItem.isFormField()) {
String filename = fileItem.getName();
// 為了重復(fù)提交相同名稱的文件,所有文件的名稱要生產(chǎn)一個唯一的值
filename = System.nanoTime() + filename.substring(filename.lastIndexOf("."));
// 獲取上傳文件的 格式
// String contentType = fileItem.getContentType();
// 創(chuàng)建一個新文件 來保存臨時文件
// 創(chuàng)建新文件 統(tǒng)一放于upload 文件夾中
// 1.獲取文件 upload 路徑
File newFileDoc = new File(servletContext.getRealPath("/WEB-INF/upload"));
// 如果沒有uplaod 文件夾洒嗤,就創(chuàng)建
if (!newFileDoc.exists()) {
newFileDoc.mkdirs();
}
// 2.創(chuàng)建 新文件來準備要保存上傳的臨時文件 newFile 文件有數(shù)據(jù)沒箫荡?
File newFile = new File(newFileDoc, filename);
fileItem.write(newFile);
fileItem.delete();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}