1 request對象經常使用API
1)表示web瀏覽器向web服務端的請求
2)url表示訪問web應用的完整路徑:http://localhost:8080/day06/Demo1
uri表示訪問web應用的資源路徑:/day06/Demo1
queryString表示?開頭的參數;name=jack
pathInfo:路徑以外的信息,若是沒有,返回nullhtml
package cn.itcast.web.request; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * http://localhost:8080/day06/Demo1?name=jack回車 */ public class Demo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { /* String url = request.getRequestURL().toString(); String uri = request.getRequestURI(); String query = request.getQueryString(); String pathInfo = request.getPathInfo(); System.out.println("url=" + url); System.out.println("uri=" + uri); System.out.println("query=" + query); System.out.println("pathInfo=" + pathInfo); */ String clientIP = request.getRemoteAddr(); String clientHOST = request.getRemoteHost(); int clientPORT = request.getRemotePort(); String serverIP = request.getLocalAddr(); String serverHOST = request.getLocalName(); int serverPORT = request.getLocalPort(); System.out.println("客戶端:"+clientIP+":"+clientHOST+":"+clientPORT); System.out.println("服務端:"+serverIP+":"+serverHOST+":"+serverPORT); } }
得到客戶機信息java
•getRequestURL方法返回客戶端發出請求時的完整URL。web
•getRequestURI方法返回請求行中的資源名部分。正則表達式
•getQueryString 方法返回請求行中的參數部分。apache
•getPathInfo方法返回請求URL中的額外路徑信息。額外路徑信息是請求URL中的位於Servlet的路徑以後和查詢參數以前的內容,它以「/」開頭。編程
•getRemoteAddr方法返回發出請求的客戶機的IP地址。設計模式
•getRemoteHost方法返回發出請求的客戶機的完整主機名。瀏覽器
•getRemotePort方法返回客戶機所使用的網絡端口號。緩存
•getLocalAddr方法返回WEB服務器的IP地址。安全
•getLocalName方法返回WEB服務器的主機名。
得到客戶機請求頭
•getHeader(string name)方法:String
•getHeaders(String name)方法:Enumeration
•getHeaderNames()方法
得到客戶機請求參數(客戶端提交的數據)
•getParameter(String)方法
•getParameterValues(String name)方法
•getParameterNames方法+BeanUtils框架
取得請求頭相關的信息
*a)request.getHeader(String):String
b)request.getHeaders(String):Enumeration
c)getHeaderNames():Enumeration
*2 獲取請求參數的值
2)取得請求體相關的信息
a)request.getParameter(String):String
b)request.getParameterValues(String):String[]
注意:在GET請求方式下,若是參數不一致,返回null,可能出現空指針異常
c)BeanUtils框架可以自動將String參數設置到JavaBean對象中
1)無需理會參數的類型,個數,可是參數名必定要和JavaBean中的字段一致
2)String->8種基本類型自動轉換,非8種基本類型能夠註冊轉換器
3)String或String[]類型的參數自動感知裝配
package cn.itcast.web.request; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Demo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //一次性取得全部的請求頭信息 Enumeration<String> enums = request.getHeaderNames(); while(enums.hasMoreElements()){ //key表示請求頭 String key = enums.nextElement(); Enumeration<String> enums2 = request.getHeaders(key); while(enums2.hasMoreElements()){ String value = enums2.nextElement(); response.getWriter().write(key+"<->"+value+"<br/>"); } } /* String acceptLanguage = request.getHeader("Accept-Language"); String userAgent = request.getHeader("User-Agent"); String host = request.getHeader("Host"); response.getWriter().write("Accept-Language=" + acceptLanguage + "<br/>"); response.getWriter().write("User-Agent=" + userAgent + "<br/>"); response.getWriter().write("Host=" + host + "<br/>"); */ } }
package cn.itcast.web.request; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import cn.itcast.web.domain.User; /* * http://localhost:8080/day07/Demo2?username=jack&age=30&salary=5000&likes=dance&likes=sing回車 */ public class Demo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //分別取得客戶端提交的信息 //String strUsername = request.getParameter("username"); //String strAge = request.getParameter("age"); //String strSalary = request.getParameter("salary"); //String[] strLikes = request.getParameterValues("likes"); BeanUtils bu = new BeanUtils(); User user = new User(); Enumeration<String> enums = request.getParameterNames(); while(enums.hasMoreElements()){ String key = enums.nextElement(); String[] values = request.getParameterValues(key); try { bu.setProperty(user,key,values); }catch (Exception e) { e.printStackTrace(); } } response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write("用戶名:" + user.getUsername() + "<br/>"); pw.write("年齡:" + user.getAge() + "<br/>"); pw.write("指望薪水:" + user.getSalary() + "<br/>"); pw.write("愛好個數:" + user.getLikes().length + "<br/>"); pw.flush(); pw.close(); } }
*3 request應用
1)防盜鏈
判段某個頁面來自於何方,即referer請求頭
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>index.html</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <a href="/day07/DownServlet">下載</a> </body> </html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>index.html</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> 這是廣告頁面 </body> </html>
package cn.itcast.web.request; 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 Demo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //取得瀏覽器來自於何方 String referer = request.getHeader("referer"); //判段 if(referer!=null && referer.equals("http://localhost:8080/day07/index.html")){ //轉發到download.html頁面 this .getServletContext() .getRequestDispatcher("/download.html") .forward(request,response); }else{ //轉發到ad.html頁面 this .getServletContext() .getRequestDispatcher("/ad.html") .forward(request,response); } } }
2)收集表單數據
a)項目中,用戶請求的參數,最好作null或空串的二次判段
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>index.html</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="/day07/Demo5" method="post"> <table border="1" align="center"> <caption>用戶註冊</caption> <tr> <th>用戶名</th> <td><input type="text" name="username"/></td> </tr> <tr> <th>密碼</th> <td><input type="password" name="password"/></td> </tr> <tr> <th>性別</th> <td> <input checked type="radio" name="gender" value="male"/>男 <input type="radio" name="gender" value="female"/>女 </td> </tr> <tr> <th>愛好</th> <td> <input type="checkbox" name="likes" value="sing"/>唱歌 <input type="checkbox" name="likes" value="dance"/>跳舞 <input type="checkbox" name="likes" value="play"/>打球 <input type="checkbox" name="likes" value="net"/>上網 </td> </tr> <tr> <th>上傳文件</th> <td><input type="file" name="upfile"/></td> </tr> <tr> <th>城市</th> <td> <select name="city"> <option value="bj">北京</option> <option value="sh">上海</option> <option value="gz" selected>廣州</option> <option value="cq">重慶</option> </select> </td> </tr> <tr> <th>留言</th> <td> <textarea name="message" rows="5" cols="20"></textarea> </td> </tr> <tr> <td> <input type="hidden" name="id" value="20111008"/> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交"/> <input type="reset" value="重填"/> </td> </tr> </table> </form> </body> </html>
package cn.itcast.web.request; 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 Demo5 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //將[請求體]的中文以UTF-8方式從新編碼 request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); String gender = request.getParameter("gender"); String[] likes = request.getParameterValues("likes"); String upfile = request.getParameter("upfile"); String city = request.getParameter("city"); String message = request.getParameter("message"); String id = request.getParameter("id"); System.out.println("username="+username); System.out.println("password="+password); System.out.println("gender="+gender); System.out.println("likes="+likes.length); System.out.println("upfile="+upfile); System.out.println("city="+city); System.out.println("message="+message); System.out.println("id="+id); } }
3)中文亂碼
a)POST方式下亂碼產生的緣由:瀏覽器發送的編碼方式與Request對象的編碼方式不一致
解決方案:request.setCharacterEncoding("UTF-8),該方法只能解析請求體中的亂碼方式,除此以外,無力解決
b)若是用戶是post方式提交,在轉發狀況下,依然是post請求,但重定向狀況下,是get請求
c)若是用戶是get方式提交,在轉發和重定向狀況下,都是get請求
d)405:自己請求是get請求,但未在servlet內提供對應的doGet()方法, post也是相似
針對請求頭編碼:
<%@ page language="java" pageEncoding="UTF-8"%> <%@ page import="java.net.*" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'get.jsp' starting page</title> </head> <body> <%-- 對中文編碼 --%> <a href="/day07/Demo7?username=<%=URLEncoder.encode("小王","UTF-8")%>"> get方式傳中文 </a> </body> </html>
package cn.itcast.web.request; 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 Demo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String username = request.getParameter("username"); //中文解碼 byte[] buf = username.getBytes("ISO8859-1"); username = new String(buf,"UTF-8"); if(username!=null || username.trim().length()>0){ response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("用戶名" + username); } } }
//練習獲取ip地址和所屬地
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>用戶登陸</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="/day07/LoginServlet" method="post"> <table border="1" align="center"> <caption>用戶登陸</caption> <tr> <th>用戶名</th> <td><input type="text" name="username"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交"/> <input type="reset" value="重填"/> </td> </tr> </table> </form> </body> </html>
package cn.itcast.web.request; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.web.domain.IpCheckBean; public class LoginServlet extends HttpServlet { //key爲IP,value爲歸屬地 private Map<String,String> map = new HashMap<String,String>(); public void init() throws ServletException { //在用戶第一次訪問前加載IP和歸屬地,不存在多線程安全問題 map.put("192.168.2.222","北京"); map.put("192.168.10.122","上海"); map.put("192.168.10.50","深圳"); map.put("192.168.10.33","佛山"); map.put("192.168.10.44","珠海"); map.put("127.0.0.1","廣州"); } public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //IP String ip = request.getRemoteAddr(); IpCheckBean ipCheckBean = new IpCheckBean(); //歸屬地 String address = ipCheckBean.check(ip,map); //用戶名 String username = request.getParameter("username"); //將信息綁定到ServletContext對象中 ServletContext context = this.getServletContext(); context.setAttribute("username",username); context.setAttribute("ip",ip); context.setAttribute("address",address); /*轉發到ShowServlet context .getRequestDispatcher("/ShowServlet") .forward(request,response); */ //重定向到ShowServlet response.sendRedirect("/day07/ShowServlet"); } }
package cn.itcast.web.request; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletExceppackage cn.itcast.web.request; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ShowServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { ServletContext context = this.getServletContext(); response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write("歡迎:"+context.getAttribute("username")+"光臨<br/>"); pw.write("你的IP是:"+context.getAttribute("ip")+"<br/>"); pw.write("歸屬地:"+context.getAttribute("address")+"<br/>"); } public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { this.doPost(request,response); } }
lrequest對象實現請求轉發:請求轉發指一個web資源收到客戶端請求後,通知服務器去調用另一個web資源進行處理。請求轉發的應用場景:MVC設計模式
*4 再談MVC設計模式
1)若是嚴格按照MVC思想的話,瀏覽器首頁訪問的是控制器,而後再由控制器轉發到視圖
2)位於WEB-INF/目錄下的資源,客戶端沒法直接訪問,只能經過服務端轉發進入
3)request對象也可用於資源的轉發
request
.getRequestDispatcher("/WEB-INF/success.html")
.forward(request,response);
4)經過正則表達式驗證中文:[\u4E00-\uFA29]+
5)對於重定向而言,先後的二個Request域對象不一樣,若是取值不到,返回"null",不會報錯
6)request對象提供了一個getRequestDispatcher方法,該方法返回一個RequestDispatcher對象,調用這個對象的forward方法能夠實現請求轉發。
7)request對象同時也是一個域對象,開發人員經過request對象在實現轉發時,把數據經過request對象帶給其它web資源處理。
•setAttribute方法
•getAttribute方法
•removeAttribute方法
•getAttributeNames方法
package cn.itcast.web.request; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.web.domain.ModelBean; public class Demo8 extends HttpServlet { //NO1 public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //轉發到view.html頁面 RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/view.html"); rd.forward(request,response); } //NO2 public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username"); ModelBean mb = new ModelBean(); boolean flag = mb.validate(username); if(flag){ //將用戶名綁定到Request域對象中 request.setAttribute("USERNAME",username); /*轉發到ListServlet.java request .getRequestDispatcher("/ListServlet") .forward(request,response); */ //重定向到ListServlet.java response.sendRedirect("/day07/ListServlet"); }else{ request .getRequestDispatcher("/WEB-INF/fail.html") .forward(request,response); } } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>用戶登陸</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="/day07/Demo8" method="post"> <table border="1" align="center"> <caption>用戶登陸</caption> <tr> <th>用戶名</th> <td><input type="text" name="username"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交"/> <input type="reset" value="重填"/> </td> </tr> </table> </form> </body> </html>
package cn.itcast.web.request; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ListServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String username = (String) request.getAttribute("USERNAME"); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("歡迎"+username+"光臨"); } public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String username = (String) request.getAttribute("USERNAME"); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("歡迎"+username+"光臨"); } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>用戶登陸</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> 登陸失敗 </body> </html>
package cn.itcast.web.domain; public class ModelBean { public boolean validate(String username){ boolean flag = false; if(username!=null && username.matches("[\u4E00-\uFA29]+")){ flag = true; } return flag; } }
5 request的細節
1)轉發是經過RequestDispatcher對象的forward(request,response)方法完成的
2)forward()方法以前的輸出,若是是輸出到緩衝區,再轉發到其餘Servlet,那麼原緩衝區的數據忽略不計
3)forward()方法以前的輸出,若是真正輸出到瀏覽器,再轉發到其餘Servlet,再轉發到其餘Servlet代碼忽略不計
4)forward()方法以前的輸出,若是是對響應頭的設置,會保留到轉發的其餘Servlet中
請求轉發的細節
•forward方法用於將請求轉發到RequestDispatcher對象封裝的資源。
•若是在調用forward方法以前,在Servlet程序中寫入的部份內容已經被真正地傳送到了客戶端,forward方法將拋出IllegalStateException異常。
•若是在調用forward方法以前向Servlet引擎的緩衝區(response)中寫入了內容,只要寫入到緩衝區中的內容尚未被真正輸出到客戶端,forward方法就能夠被正常執
•行,原來寫入到輸出緩衝區中的內容將被清空,可是,已寫入到HttpServletResponse對象中的響應頭字段信息保持有效
package cn.itcast.web.request; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Demo91 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); //PrintWriter pw = response.getWriter(); //pw.write("Demo91"); //pw.flush(); //pw.close(); //request.getRequestDispatcher("/Demo92").forward(request,response); response.sendRedirect("/day06/success.html"); } }
package cn.itcast.web.request; 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 Demo92 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.getWriter().write("哈哈"); } }
*6 重定向和轉發區別
•一個web資源收到客戶端請求後,通知服務器去調用另一個web資源進行處理,稱之爲請求轉發/307。
•一個web資源收到客戶端請求後,通知瀏覽器去訪問另一個web資源進行處理,稱之爲請求重定向/302。
1)轉發只能相對於當前web應用而言,不能轉發到其它web應用
重定向能夠在當前web應用以外的其它web應用重寫向資源
2)轉發/表示當前web應用
重定向/表示web服務器的根目錄,即webapps目錄
3)轉發時,瀏覽器地址欄不變
重定向時,瀏覽器地址欄改變
4)轉發是服務端的內部行爲,瀏覽器不知
重定向是瀏覽器和服務端的共同行爲,瀏覽器必知
5)轉發時二個Servlet共享request域對象
重定向時二個Servlet獨享request域對象
6)request具備二義性:
a)請求對象
b)域對
7 include包含
1)須要使用Servlet包含相同的頁面輸出時,相似於函數調用
•RequestDispatcher.include方法用於將RequestDispatcher對象封裝的資源內容做爲當前響應內容的一部分包含進來,從而實現可編程的服務器端包含功能。
•被包含的Servlet程序不能改變響應消息的狀態碼和響應頭,若是它裏面存在這樣的語句,這些語句的執行結果將被忽略
package cn.itcast.web.request; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Demo10 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //取得客戶端請求的類型 String method = request.getMethod(); System.out.println("method="+method); //包含head.html(相似於函數調用) request .getRequestDispatcher("/common/head.html") .include(request,response); response.getOutputStream().write("<hr/>".getBytes()); //動態生成 response.getOutputStream().write("login.html".getBytes()); response.getOutputStream().write("<hr/>".getBytes()); //包含foot.html request .getRequestDispatcher("/common/foot.html") .include(request,response); response.getOutputStream().write("<hr/>".getBytes()); } }
會話
1)用戶輸出URL地址,有效訪問某個網站,在該網站上的一系列有效操做,隨後關閉瀏覽器的整個過程,叫一次會話
2)會話主要解決服務端如何保存每一個客戶端對應的私有信息。
3)會話主要有二種:
a)Cookie技術[客戶端技術]
b)Session技術
Cookie
1)Cookie是客戶端的技術
2)每次發送請求時,客戶端都會帶上各自已的不一樣Cookie到服務端,服務端一解析Cookie,就知道是哪一個客戶端發送過來的信息
3)一個Cookie只能存儲一種類型的信息
4)更新某個名的Cookie,即向瀏覽器寫一個相同名的Cookie
5)Cookie必定要設置一個有效時間,若是不設置的話,默認該請求訪問結束後,該Cookie自動銷燬,用專業名詞來說,
Cookie的默認有效期時一個有效會話結束
package cn.itcast.web.cookie; 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; public class Demo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { /* //服務端產生Cookie Cookie cookie = new Cookie("username","haha"); //設置Cookie存活時間 cookie.setMaxAge(1*24*60*60); //服務端將Cookie寫到客戶端暫存 response.addCookie(cookie); */ //取得客戶端全部的Cookie Cookie[] cookies = request.getCookies(); Cookie usernameCookie = null; if(cookies!=null){ for(Cookie c : cookies){ if(c.getName().equals("username")){ usernameCookie = c; break; } } //若是找到了Cookie if(usernameCookie!=null){ System.out.println("Cookie的名字:" + usernameCookie.getName()); System.out.println("Cookie的值:" + usernameCookie.getValue()); System.out.println("Cookie的生命:" + usernameCookie.getMaxAge()); System.out.println("Cookie的路徑:" + usernameCookie.getPath()); } } } }
package cn.itcast.web.cookie; 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; /* * http://localhost:8080/day07/Demo2?name=jack回車 */ public class Demo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String name = request.getParameter("name"); if(name==null){ name="default"; } //取得客戶端的全部Cookie的值 Cookie[] cookies = request.getCookies(); if(cookies==null){ Cookie cookie = new Cookie("name_"+name,System.currentTimeMillis()+""); cookie.setMaxAge(1*24*60*60); response.addCookie(cookie); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("歡迎"+name+"首次光臨,訪問時間:" + new Date().toLocaleString()); }else{ //查找名爲name的Cookie Cookie nameCookie = null; for(Cookie c : cookies){ if(c.getName().equals("name_"+name)){ nameCookie = c; break; } } //找到了 if(nameCookie!=null){ String strTime = nameCookie.getValue(); response.setContentType("text/html;charset=UTF-8"); long lastTime = Long.parseLong(strTime); response.getWriter().write("歡迎"+name+"再次光臨,你上次訪問時間:" + new Date(lastTime).toLocaleString()); //更新時間 Cookie cookie = new Cookie("name_"+name,System.currentTimeMillis()+""); cookie.setMaxAge(1*24*60*60); response.addCookie(cookie); } } } }
*0 帶用驗證碼功能的用戶登陸
1)驗證碼使用一個CheckCodeSerlvet產生,經過<img src=""/>發送請求,將驗證碼綁定到HttpSession中
2)產生的驗證碼必定要在輸出到瀏覽器以前綁定到HttpSession中
3)設置驗證碼禁止緩存要在輸出到瀏覽器以前
4)全部響應頭的設置放置在最早
package cn.itcast.web.session; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class CheckCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setHeader("expires","-1"); response.setHeader("cache-control","no-cache"); response.setHeader("pragma","no-cache"); String token = Token.getNum(); //將驗證碼綁定到域對象 HttpSession session = request.getSession(); session.setAttribute("checkCodeServer",token); BufferedImage image = new BufferedImage(50,25,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.drawString(token,15,15); //加干擾線 for(int i=0;i<10;i++){ Random r = new Random(); int x1 = r.nextInt(50); int y1 = r.nextInt(25); g.drawLine(x1, y1, x1+4,y1+4); } ImageIO.write(image,"JPG",response.getOutputStream()); } } class Token{ public static String getNum(){ Random r = new Random(); int num = r.nextInt(10000); return num + ""; } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>login.html</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="/day09/LoginServlet" method="post"> <table border="1" align="center"> <tr> <th>用戶名</th> <td><input type="text" name="username"/></td> </tr> <tr> <th>密碼</th> <td><input type="password" name="password"/></td> </tr> <tr> <th>驗證碼</th> <td> <input type="text" name="checkCodeClient"/> </td> <td> <img src="/day09/CheckCodeServlet"/> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交"/> </td> </tr> </table> </form> </body> </html>
package cn.itcast.web.session; 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 { public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //收集客戶端填入的驗證碼 String checkCodeClient = request.getParameter("checkCodeClient"); //取得服務端填入的驗證碼 String checkCodeServer = (String) request.getSession().getAttribute("checkCodeServer"); //判段 response.setContentType("text/html;charset=UTF-8"); if(checkCodeClient!=null && checkCodeClient.trim().length()>0 && checkCodeServer!=null && checkCodeServer.equals(checkCodeClient)){ response.getWriter().write("驗證碼正確"); }else{ response.getWriter().write("驗證碼出錯"); } } }