Java Server Pagejavascript
從用戶角度看待 ,就是是一個網頁 , 從程序員角度看待 , 實際上是一個java類, 它繼承了servlet,因此能夠直接說jsp 就是一個Servlet.html
html 多數狀況下用來顯示靜態內容 , 一成不變的。 可是有時候咱們須要在網頁上顯示一些動態數據, 好比: 查詢全部的學生信息, 根據姓名去查詢具體某個學生。 這些動做都須要去查詢數據庫,而後在網頁上顯示。 html是不支持寫java代碼 , jsp裏面能夠寫java代碼。java
<%@ 指令名字 %>mysql
代表jsp頁面中能夠寫java代碼程序員
其實即便說這個文件是什麼類型,告訴瀏覽器我是什麼內容類型,以及使用什麼編碼sql
contentType="text/html; charset=UTF-8" text/html MIMEType 這是一個文本,html網頁
pageEncoding jsp內容編碼數據庫
extends 用於指定jsp翻譯成java文件後,繼承的父類是誰,通常不用改。數組
import 導包使用的,通常不用手寫。瀏覽器
session服務器
值可選的有true or false .
用於控制在這個jsp頁面裏面,可以直接使用session對象。
具體的區別是,請看翻譯後的java文件 若是該值是true , 那麼在代碼裏面會有getSession()的調用,若是是false : 那麼就不會有該方法調用,也就是沒有session對象了。在頁面上天然也就不能使用session了。
指的是錯誤的頁面, 值須要給錯誤的頁面路徑
上面的errorPage 用於指定錯誤的時候跑到哪個頁面去。 那麼這個isErroPage , 就是聲明某一個頁面究竟是不是錯誤的頁面。
包含另一個jsp的內容進來。
<%@ include file="other02.jsp"%>
能夠理解爲靜態包含 ,把包含的頁面全部元素標籤所有拿過來,與include動做標籤不一樣。把另一個頁面的全部內容拿過來一塊兒輸出。 全部的標籤元素都包含進來。
<%@ taglib prefix="" uri=""%> uri: 標籤庫路徑 prefix : 標籤庫的別名
<jsp:include page=""></jsp:include> <jsp:param value="" name=""/> <jsp:forward page=""></jsp:forward>
<jsp:include page="other02.jsp"></jsp:include>
包含指定的頁面, 這裏是動態包含。 也就是不把包含的頁面全部元素標籤所有拿過來輸出,而是把它的運行結果拿過來。
jsp:forward
<jsp:forward page=""></jsp:forward>
前往哪個頁面。
<jsp:forward page="other02.jsp"></jsp:forward>
等同於
<% //請求轉發 request.getRequestDispatcher("other02.jsp").forward(request, response); %>
意思是: 在包含某個頁面的時候,或者在跳轉某個頁面的時候,加入這個參數。
向other02.jsp發送參數 <jsp:forward page="other02.jsp"> <jsp:param value="beijing" name="address"/> </jsp:forward>
在other02.jsp中獲取參數 <br>收到的參數是:<br> <%= request.getParameter("address")%>
所謂內置對象,就是咱們能夠直接在jsp頁面中使用這些對象。 不用建立。
以上4個是做用域對象 ,
表示這些對象能夠存值,他們的取值範圍有限定。 setAttribute 和 getAttribute
使用做用域來存儲數據<br> <% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 取出四個做用域中的值<br> <%=pageContext.getAttribute("name")%> <%=request.getAttribute("name")%> <%=session.getAttribute("name")%> <%=application.getAttribute("name")%>
做用域範圍大小:
pageContext < request < session < application
做用域僅限於當前的頁面。
還能夠獲取到其餘八個內置對象。
做用域僅限於一次請求, 只要服務器對該請求作出了響應。 這個域中存的值就沒有了。好比重定向是兩次請求,重定向到的頁面也取不到值
做用域限於一次會話(屢次請求與響應) 當中。
整個工程均可以訪問, 服務器關閉後就不能訪問了。
是爲了簡化我們的jsp代碼,具體一點就是爲了簡化在jsp裏面寫的那些java代碼。
注意:在Eclipse中沒有代碼提示
${表達式 }
若是從做用域中取值,會先從小的做用域開始取,若是沒有,就往下一個做用域取。 一直把四個做用域取完都沒有, 就沒有顯示。
<% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 按普通手段取值<br> <%= pageContext.getAttribute("name")%> <%= request.getAttribute("name")%> <%= session.getAttribute("name")%> <%= application.getAttribute("name")%> <br>使用EL表達式取出做用域中的值<br> ${ pageScope.name } ${ requestScope.name } ${ sessionScope.name } ${ applicationScope.name }
若是域中所存的是數組
<% String [] a = {"aa","bb","cc","dd"}; pageContext.setAttribute("array", a); %> 使用EL表達式取出做用域中數組的值<br> ${array[0] } , ${array[1] },${array[2] },${array[3] }
若是域中鎖存的是集合
使用EL表達式取出做用域中集合的值<br> ${li[0] } , ${li[1] },${li[2] },${li[3] } <br>-------------Map數據----------------<br> <% Map map = new HashMap(); map.put("name", "zhangsna"); map.put("age",18); map.put("address","北京.."); map.put("address.aa","深圳.."); pageContext.setAttribute("map", map); %>
取出Map集合的值
<% Map map = new HashMap(); map.put("name", "zhangsna"); map.put("age",18); map.put("address","北京..");
map.put("address.aa","深圳.."); pageContext.setAttribute("map", map);
%> 使用EL表達式取出做用域中Map的值
${map.name } , ${map.age } , ${map.address } , ${map["address.aa"] }
從域中取值。 得先存值。 <%
//pageContext.setAttribute("name", "zhangsan"); session.setAttribute("name", "lisi..."); %>
直接指定說了,到這個做用域裏面去找這個name
${ pageScope.name }
//先從page裏面找,沒有去request找,去session,去application
${ name }
指定從session中取值
${ sessionScope.name }
若是這份值是有下標的,那麼直接使用[]
<% String [] array = {"aa","bb","cc"} session.setAttribute("array",array); %> ${ array[1] } --> 這裏array說的是attribute的name
若是沒有下標, 直接使用 .的方式去取
<% User user = new User("zhangsan",18); session.setAttribute("u", user); %> ${ u.name } , ${ u.age }
通常使用EL表達式,用的比較多的,都是從一個對象中取出它的屬性值,好比取出某一個學生的姓名。
${ 對象名.成員 }
做用域相關對象
- pageScope
- requestScope
- sessionScope
- applicationScope
頭信息相關對象
- header
- headerValues
參數信息相關對象
- param
- paramValues
全稱 : JSP Standard Tag Library jsp標準標籤庫
簡化jsp的代碼編寫。 替換 <%%> 寫法。 通常與EL表達式配合
導入jar文件到工程的WebContent/Web-Inf/lib jstl.jar standard.jar
在jsp頁面上,使用taglib 指令,來引入標籤庫
注意: 若是想支持 EL表達式,那麼引入的標籤庫必須選擇1.1的版本,1.0的版本不支持EL表達式。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set></c:set>
<c:if test=""></c:if>
<c:forEach></c:forEach>
c:set
<!-- 聲明一個對象name, 對象的值 zhangsan , 存儲到了page(默認) , 指定是session --> <c:set var="name" value="zhangsan" scope="session"></c:set> ${sessionScope.name }
c:if
判斷test裏面的表達式是否知足,若是知足,就執行c:if標籤中的輸出 , c:if 是沒有else的。
<c:set var="age" value="18" ></c:set> <c:if test="${ age > 26 }"> 年齡大於了26歲... </c:if> <c:if test="${ age <= 26 }"> 年齡小於了26歲... </c:if> ------------------------------ 定義一個變量名 flag 去接收前面表達式的值,而後存在session域中 <c:if test="${ age > 26 }" var="flag" scope="session"> 年齡大於了26歲... </c:if>
c:forEach
從1 開始遍歷到10 ,獲得的結果 ,賦值給 i ,而且會存儲到page域中, step , 增幅爲2, <c:forEach begin="1" end="10" var="i" step="2"> ${i } </c:forEach> ----------------------------------------------- <!-- items : 表示遍歷哪個對象,注意,這裏必須寫EL表達式。 var: 遍歷出來的每個元素用user 去接收。 --> <c:forEach var="user" items="${list }"> ${user.name } ----${user.age } </c:forEach>
先寫 login.jsp , 而且搭配一個LoginServlet 去獲取登陸信息。
建立用戶表, 裏面只要有id , username 和 password
建立UserDao, 定義登陸的方法
/**
建立UserDaoImpl , 實現剛纔定義的登陸方法。
public class UserDaoImpl implements UserDao { @Override public boolean login(String userName , String password) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 獲得鏈接對象 conn = JDBCUtil.getConn(); String sql = "select * from t_user where username=? and password=?"; //2. 建立ps對象 ps = conn.prepareStatement(sql); ps.setString(1, userName); ps.setString(2, password); //3. 開始執行。 rs = ps.executeQuery(); //若是可以成功移到下一條記錄,那麼代表有這個用戶。 return rs.next(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return false; } }
在LoginServlet裏面訪問UserDao, 判斷登陸結果。 以區分對待
建立stu_list.jsp , 讓登陸成功的時候跳轉過去。
建立學生表 , 裏面字段隨意。
定義學生的Dao . StuDao
public interface StuDao { /** * 查詢出來全部的學生信息 * @return List集合 */ List<Student> findAll(); }
對上面定義的StuDao 作出實現 StuDaoImpl
public class StuDaoImpl implements StuDao {
@Override public List<Student> findAll() { List<Student> list = new ArrayList<Student>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 獲得鏈接對象 conn = JDBCUtil.getConn(); String sql = "select * from t_stu"; ps = conn.prepareStatement(sql); rs = ps.executeQuery();
//數據多了,用對象裝, 對象也多了呢? 用集合裝。 while(rs.next()){ //10 次 ,10個學生
Student stu = new Student(); stu.setId(rs.getInt("id")); stu.setAge(rs.getInt("age")); stu.setName(rs.getString("name")); stu.setGender(rs.getString("gender")); stu.setAddress(rs.getString("address")); list.add(stu); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return list; } }
在登陸成功的時候,完成三件事情。
查詢全部的學生
把這個全部的學生集合存儲到做用域中。
跳轉到stu_list.jsp
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //提交的數據有可能有中文, 怎麼處理。 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); //1. 獲取客戶端提交的信息 String userName = request.getParameter("username"); String password = request.getParameter("password"); //2. 去訪問dao , 看看是否知足登陸。 UserDao dao = new UserDaoImpl(); boolean isSuccess = dao.login(userName, password); //3. 針對dao的返回結果,作出響應 if(isSuccess){ //response.getWriter().write("登陸成功."); //1. 查詢出來全部的學生信息。 StuDao stuDao = new StuDaoImpl(); List<Student> list = stuDao.findAll(); //2. 先把這個集合存到做用域中。 request.getSession().setAttribute("list", list); //2. 重定向 response.sendRedirect("stu_list.jsp"); }else{ response.getWriter().write("用戶名或者密碼錯誤!"); }
}
在stu_list.jsp中,取出域中的集合,而後使用c標籤 去遍歷集合。
<table border="1" width="700"> <tr align="center"> <td>編號</td> <td>姓名</td> <td>年齡</td> <td>性別</td> <td>住址</td> <td>操做</td> </tr> <c:forEach items="${list }" var="stu"> <tr align="center"> <td>${stu.id }</td> <td>${stu.name }</td> <td>${stu.age }</td> <td>${stu.gender }</td> <td>${stu.address }</td> <td><a href="#">更新</a> <a href="#">刪除</a></td> </tr> </c:forEach>
JSP
三大指令
page include taglib
三個動做標籤 <jsp:include> <jsp:forward> <jsp:param>
九個內置對象
四個做用域 pageContext request session application out exception response page config
${ 表達式 }
取4個做用域中的值
${ name }
有11個內置對象。
pageContext pageScope requestScope sessionScope applicationScope header headerValues param paramValues cookie initParam
使用1.1的版本, 支持EL表達式, 1.0不支持EL表達式
拷貝jar包, 經過taglib 去引入標籤庫
<c:set> <c:if> <c:forEach>
package com.itheima.util; import javax.servlet.http.Cookie; public class CookieUtil { /** * 從一個cookie數組中找到具體咱們想要的cookie對象 * @param cookies * @param name * @return */ public static Cookie findCookie(Cookie[] cookies , String name){ if(cookies != null){ for (Cookie cookie : cookies) { if(name.equals(cookie.getName())){ return cookie; } } } return null; } }
demo1
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Cookie的簡單使用。 //cookie 發送給客戶端,而且保存在客戶端上的一份小數據 response.setContentType("text/html;charset=utf-8"); /* * 方法參數要什麼就給什麼。 對象 * * 建立對象的幾種手法 * * 1. 直接new * * 2. 單例模式 | 提供靜態方法 * * 3. 工廠模式構建 stu * * StuFactory StuBuilder */ //發送cookie給客戶端 Cookie cookie = new Cookie("aa", "bb"); //給響應,添加一個cookie response.addCookie(cookie); response.getWriter().write("請求成功了..."); //獲取客戶端帶過來的cookie Cookie[] cookies = request.getCookies(); if(cookies != null){ for (Cookie c : cookies) { String cookieName = c.getName(); String cookieValue = c.getValue(); System.out.println(cookieName + " = "+ cookieValue); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
demo2
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo02 */ public class Demo02 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //取客戶端發送過來的cookie. Cookie[] cookies = request.getCookies(); if(cookies != null){ for (Cookie cookie : cookies) { System.out.println(cookie.getName()+" = "+cookie.getValue()); } } //1. 先寫cookie 能夠給客戶端返回多個cookie Cookie cookie = new Cookie("name", "zhangsan"); //2. 這個cookie的有效期。 默認狀況下 , //關閉瀏覽器後,cookie就沒有了。 ---> 針對沒有設置cookie的有效期。 // expiry: 有效 以秒計算。 //正值 : 表示 在這個數字事後,cookie將會失效。 //負值: 關閉瀏覽器,那麼cookie就失效, 默認值是 -1 cookie.setMaxAge(60 * 60 * 24 * 7); //賦值新的值 //cookie.setValue(newValue); //用於指定只有請求了指定的域名,纔會帶上該cookie cookie.setDomain(".itheima.com"); //只有訪問該域名下的cookieDemo的這個路徑地址纔會帶cookie cookie.setPath("/CookieDemo"); response.addCookie(cookie); Cookie cookie2 = new Cookie("age", "18"); response.addCookie(cookie2); response.getWriter().write("hello Cookie..."); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
demo3
package com.itheima.servlet; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.itheima.util.CookieUtil; /** * Servlet implementation class Demo03 */ public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)){ //獲取cookie last-name --- > Cookie [] cookies = request.getCookies(); //從數組裏面找出咱們想要的cookie Cookie cookie = CookieUtil.findCookie(cookies, "last"); //是第一次登陸,沒有cookie if(cookie == null){ Cookie c = new Cookie("last", System.currentTimeMillis()+""); c.setMaxAge(60*60); //一個小時 response.addCookie(c); response.getWriter().write("歡迎您, "+userName); }else{ //1. 去之前的cookie第二次登陸,有cookie long lastVisitTime = Long.parseLong(cookie.getValue()); //2. 輸出到界面, response.getWriter().write("歡迎您, "+userName +",上次來訪時間是:"+new Date(lastVisitTime)); //3. 重置登陸的時間 cookie.setValue(System.currentTimeMillis()+""); response.addCookie(cookie); } }else{ response.getWriter().write("登錄失敗 "); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.util; import javax.servlet.http.Cookie; public class CookieUtil { /** * 從一個cookie數組中找到具體咱們想要的cookie對象 * @param cookies * @param name * @return */ public static Cookie findCookie(Cookie[] cookies , String name){ if(cookies != null){ for (Cookie cookie : cookies) { if(name.equals(cookie.getName())){ return cookie; } } } return null; } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ClearHistory */ public class ClearHistory extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getCookies(); //history : 1#2#4 //演練清除cookie : Cookie cookie = new Cookie("history",""); cookie.setMaxAge(0); //設置當即刪除 cookie.setPath("/CookieDemo02"); response.addCookie(cookie); response.sendRedirect("product_list.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.itheima.util.CookieUtil; /** * Servlet implementation class ProductInfoServlet */ public class ProductInfoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("----來到servlet----"); //獲取到當前用戶準備瀏覽的商品ID。 String id = request.getParameter("id"); Cookie[] cookies = request.getCookies(); Cookie cookie = CookieUtil.findCookie(cookies, "history"); //第一次瀏覽。 if(cookie == null){ System.out.println("----第一次訪問----"); //1. 響應返回cookie Cookie c = new Cookie("history", id); //設置有效期。 c.setMaxAge(60*60*24*7); //設置訪問這個工程的時候,才帶cookie過來 c.setPath("/CookieDemo02"); response.addCookie(c); // //2. 跳轉到具體界面 // response.sendRedirect("product_info.htm"); }else{ //第二次 //1. 獲取之前的cookie , 由於之前的cookie , 包含了瀏覽記錄123 String ids = cookie.getValue(); //2. 讓如今瀏覽的商品, 和 之前瀏覽的商品,造成cookie新的值。 cookie.setValue(id+"#"+ids); //設置有效期。 cookie.setMaxAge(60*60*24*7); //設置訪問這個工程的時候,才帶cookie過來 cookie.setPath("/CookieDemo02"); response.addCookie(cookie); } //3. 跳轉 response.sendRedirect("product_info.htm"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.domain; public class User { private String name; private int age ; public User(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
el_jsp
<%@page import="java.util.Map"%> <%@page import="java.util.HashMap"%> <%@page import="java.util.ArrayList"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 按普通手段取值<br> <%= pageContext.getAttribute("name")%> <%= request.getAttribute("name")%> <%= session.getAttribute("name")%> <%= application.getAttribute("name")%> <br>使用EL表達式取出做用域中的值<br> ${ pageScope.name } ${ requestScope.name } ${ sessionScope.name } ${ applicationScope.name } ${name } <br>-----------------------------<br> <% String [] a = {"aa","bb","cc","dd"}; pageContext.setAttribute("array", a); %> 使用EL表達式取出做用域中數組的值<br> ${array[0] } , ${array[1] },${array[2] },${array[3] } <br>-------------集合數據----------------<br> <% List list = new ArrayList(); list.add("11"); list.add("22"); list.add("33"); list.add("44"); //pageContext.setAttribute("li", list); session.setAttribute("li", list); %> 使用EL表達式取出做用域中集合的值<br> ${li[0] } , ${li[1] },${li[2] },${li[7] } <br>-------------Map數據----------------<br> <% Map map = new HashMap(); map.put("name", "zhangsna"); map.put("age",18); map.put("address","北京.."); map.put("address.aa","深圳.."); //pageContext.setAttribute("map", map); application.setAttribute("m", map); %> 使用EL表達式取出做用域中Map的值<br> ${applicationScope.m.name } , ${m.age } , ${m.address } , ${m["address.aa"] } </body> </html>
el02
<%@page import="com.itheima.domain.User"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 從域中取值。 得先存值。 <% //pageContext.setAttribute("name", "zhangsan"); session.setAttribute("name", "lisi..."); %> <br>直接指定說了,到這個做用域裏面去找這個name<br> ${ pageScope.name } <br>//先從page裏面找,沒有去request找,去session,去application <br> ${ name } <br>指定從session中取值<br> ${ sessionScope.name } <br>---------------------------------------------<br> <% User user = new User("zhangsan",18); session.setAttribute("u", user); %> ${ u.name } , ${ u.age } ${ a > b} ${ a gt b } ${ empty u } </body> </html>
el03
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 這是el03頁面 <jsp:forward page="el04.jsp"> <jsp:param value="beijing...." name="address"/> </jsp:forward> </body> </html>
el04
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 這是el04頁面<br> <%=request.getParameter("address") %> <br> 使用EL表達式獲取這個參數 <%-- response.addCookie(new Cookie("name","value")); ${cookie.name } --%> ${param.address } </body> </html>
jsp_action
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <%-- <jsp:include page=""></jsp:include> <jsp:param value="" name=""/> <jsp:forward page=""></jsp:forward> --%> 這是jsp_action的頁面. <%-- <jsp:include page="other02.jsp"></jsp:include> --%> <%-- <jsp:forward page="other02.jsp"></jsp:forward> 等同於如下代碼 --%> <% //請求轉發 //request.getRequestDispatcher("other02.jsp").forward(request, response); %> <jsp:forward page="other02.jsp"> <jsp:param value="beijing" name="address"/> </jsp:forward> </body> </html>
jstl
<%@page import="com.itheima.domain.User"%> <%@page import="java.util.List"%> <%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 聲明一個對象name, 對象的值 zhangsan , 存儲到了page(默認) , 指定是session --> <c:set var="name" value="zhangsan" scope="session"></c:set> ${sessionScope.name } <br>----------------------<br> <c:set var="age" value="18" ></c:set> <c:if test="${ age > 26 }" var="flag" scope="session"> 年齡大於了26歲... </c:if> <c:if test="${ age <= 26 }"> 年齡小於了26歲... </c:if> ${flag } <br>----------------------<br> 從1 開始遍歷到10 ,獲得的結果 ,賦值給 i ,而且會存儲到page域中, step , 增幅爲2, <c:forEach begin="1" end="10" var="i" step="2"> ${i } </c:forEach> <br>----------------------<br> <% List list =new ArrayList(); list.add(new User("zhangsan",18)); list.add(new User("lisi",28)); list.add(new User("wagnwu",38)); list.add(new User("maliu",48)); list.add(new User("qianqi",58)); pageContext.setAttribute("list", list); %> <!-- items : 表示遍歷哪個對象,注意,這裏必須寫EL表達式。 var: 遍歷出來的每個元素用user 去接收。 --> <c:forEach var="user" items="${list }"> ${user.name } ----${user.age } </c:forEach> </body> </html>
other
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%-- <%@ include file="other02.jsp"%> --%> <%-- <%@ taglib prefix="" uri=""%> --%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <jsp:include page="other02.jsp"></jsp:include> 這是other頁面的內容. </body> </html>
other2
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h3>這是other022222的內容</h3> <br>收到的參數是:<br> <%= request.getParameter("address")%> <% %> </body> </html>
other3
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 這是other03的頁面 <br>使用做用域來存儲數據<br> <% pageContext.setAttribute("name", "page"); request.setAttribute("name", "request"); session.setAttribute("name", "session"); application.setAttribute("name", "application"); %> 取出四個做用域中的值<br> <%=pageContext.getAttribute("name")%> <%=request.getAttribute("name")%> <%=session.getAttribute("name")%> <%=application.getAttribute("name")%> <!-- //跳轉到下一個界面去了 --> <% //請求轉發. 一次請求 //request.getRequestDispatcher("other04.jsp").forward(request, response); //重定向 2次請求 response.sendRedirect("other04.jsp"); %> </body> </html>
other4
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h3>這是04的頁面</h3><br> 取出四個做用域中的值<br> <%=pageContext.getAttribute("name")%> <%=request.getAttribute("name")%> <%=session.getAttribute("name")%> <%=application.getAttribute("name")%> </body> </html>
other5
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 這是other05的頁面<br> <% out.write("這是使用out對象輸出的內容"); %> <br> <% response.getWriter().write("這是使用response對象輸出的內容"); %> </body> </html>
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)){ //response.getWriter().write("登陸成功"); /* * 早期的寫法: * response.setStatus(302); response.setHeader("Location", "login_success.html");*/ //重定向寫法: 從新定位方向 /根目錄 response.sendRedirect("login_success.html"); //請求轉發的寫法: // request.getRequestDispatcher("login_success.html").forward(request, response); }else{ response.getWriter().write("登陸失敗"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //獲得會話ID String id = session.getId(); //存值 //session.setAttribute(name, value); //取值 //session.getAttribute(name); //移除值 //session.removeAttribute(name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String sessionid= request.getSession().getId(); System.out.println("sessionid="+sessionid); response.getWriter().write("收到請求了。。"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CarServlet */ public class CarServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //1. 獲取要添加到購物車的商品id int id = Integer.parseInt(request.getParameter("id")); // 0 - 1- 2 -3 -4 String [] names = {"Iphone7","小米6","三星Note8","魅族7" , "華爲9"}; //取到id對應的商品名稱 String name = names[id]; //2. 獲取購物車存放東西的session Map<String , Integer> iphoen7 3 //把一個map對象存放到session裏面去,而且保證只存一次。 Map<String, Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart"); //session裏面沒有存放過任何東西。 if(map == null){ map = new LinkedHashMap<String , Integer>(); request.getSession().setAttribute("cart", map); } //3. 判斷購物車裏面有沒有該商品 if(map.containsKey(name)){ //在原來的值基礎上 + 1 map.put(name, map.get(name) + 1 ); }else{ //沒有購買過該商品,當前數量爲1 。 map.put(name, 1); } String sId = request.getSession().getId(); Cookie cookie = new Cookie("JSESSIONID", sId); cookie.setMaxAge(60*60*24*7); response.addCookie(cookie); //4. 輸出界面。(跳轉) response.getWriter().write("<a href='product_list.jsp'><h3>繼續購物</h3></a><br>"); response.getWriter().write("<a href='cart.jsp'><h3>去購物車結算</h3></a>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class ClearCartServlet */ public class ClearCartServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //強制幹掉會話,裏面存放的任何數據就都沒有了。 session.invalidate(); //從session中移除某一個數據 //session.removeAttribute("cart"); response.sendRedirect("cart.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.itheima.util; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCUtil { static String driverClass = null; static String url = null; static String name = null; static String password= null; static{ try { //1. 建立一個屬性配置對象 Properties properties = new Properties(); // InputStream is = new FileInputStream("jdbc.properties"); //使用類加載器,去讀取src底下的資源文件。 後面在servlet InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); //導入輸入流。 properties.load(is); //讀取屬性 driverClass = properties.getProperty("driverClass"); url = properties.getProperty("url"); name = properties.getProperty("name"); password = properties.getProperty("password"); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取鏈接對象 * @return */ public static Connection getConn(){ Connection conn = null; try { Class.forName(driverClass); //靜態代碼塊 ---> 類加載了,就執行。 java.sql.DriverManager.registerDriver(new Driver()); //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb"); //2. 創建鏈接 參數一: 協議 + 訪問的數據庫 , 參數二: 用戶名 , 參數三: 密碼。 conn = DriverManager.getConnection(url, name, password); } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 釋放資源 * @param conn * @param st * @param rs */ public static void release(Connection conn , Statement st , ResultSet rs){ closeRs(rs); closeSt(st); closeConn(conn); } public static void release(Connection conn , Statement st){ closeSt(st); closeConn(conn); } private static void closeRs(ResultSet rs){ try { if(rs != null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ rs = null; } } private static void closeSt(Statement st){ try { if(st != null){ st.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ st = null; } } private static void closeConn(Connection conn){ try { if(conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ conn = null; } } }
package com.itheima.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.itheima.dao.StuDao; import com.itheima.dao.UserDao; import com.itheima.dao.impl.StuDaoImpl; import com.itheima.dao.impl.UserDaoImpl; import com.itheima.domain.Student; /** * 這是用於處理登陸的servlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //提交的數據有可能有中文, 怎麼處理。 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); //1. 獲取客戶端提交的信息 String userName = request.getParameter("username"); String password = request.getParameter("password"); //2. 去訪問dao , 看看是否知足登陸。 UserDao dao = new UserDaoImpl(); boolean isSuccess = dao.login(userName, password); //3. 針對dao的返回結果,作出響應 if(isSuccess){ //response.getWriter().write("登陸成功."); //1. 查詢出來全部的學生信息。 StuDao stuDao = new StuDaoImpl(); List<Student> list = stuDao.findAll(); //2. 先把這個集合存到做用域中。 request.getSession().setAttribute("list", list); //2. 重定向 response.sendRedirect("stu_list.jsp"); }else{ response.getWriter().write("用戶名或者密碼錯誤!"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.itheima.dao; import java.util.List; import com.itheima.domain.Student; public interface StuDao { /** * 查詢出來全部的學生信息 * @return List集合 */ List<Student> findAll(); }
package com.itheima.dao; /** * 該dao定義了對用戶表的訪問規則 */ public interface UserDao { /** * 這裏簡單就返回一個Boolean類型, 成功或者失敗便可。 * * 可是開發的時候,登陸的方法,一旦成功。這裏應該返回該用戶的我的信息 * @param userName * @param password * * @return true : 登陸成功, false : 登陸失敗。 */ boolean login(String userName , String password); }
package com.itheima.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.itheima.dao.StuDao; import com.itheima.domain.Student; import com.itheima.util.JDBCUtil; public class StuDaoImpl implements StuDao { @Override public List<Student> findAll() { List<Student> list = new ArrayList<Student>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 獲得鏈接對象 conn = JDBCUtil.getConn(); String sql = "select * from t_stu"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); //數據多了,用對象裝, 對象也多了呢? 用集合裝。 while(rs.next()){ //10 次 ,10個學生 Student stu = new Student(); stu.setId(rs.getInt("id")); stu.setAge(rs.getInt("age")); stu.setName(rs.getString("name")); stu.setGender(rs.getString("gender")); stu.setAddress(rs.getString("address")); list.add(stu); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return list; } }
package com.itheima.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.itheima.dao.UserDao; import com.itheima.util.JDBCUtil; import com.sun.corba.se.spi.orbutil.fsm.Guard.Result; public class UserDaoImpl implements UserDao { @Override public boolean login(String userName , String password) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //1. 獲得鏈接對象 conn = JDBCUtil.getConn(); String sql = "select * from t_user where username=? and password=?"; //2. 建立ps對象 ps = conn.prepareStatement(sql); ps.setString(1, userName); ps.setString(2, password); //3. 開始執行。 rs = ps.executeQuery(); //若是可以成功移到下一條記錄,那麼代表有這個用戶。 return rs.next(); } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtil.release(conn, ps, rs); } return false; } }
package com.itheima.domain; public class Student { //到底有哪些成員。 想要在頁面上顯示多少。 private int id ; private String name; private int age ; private String gender; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }