Cookie包含一對Key/Value
生成一個Cookie并將它寫到用戶硬盤上的語法:
Cookie theCookie=new Cookie("cookieName","cookieValue");
response.addCookie(the Cookie);
如果服務(wù)器想從用戶硬盤上獲取Cookie,可以用
Cookie cookies[]=request.getCookies();
獲取所有Cookie
然后調(diào)用Cookie的getName方法獲取Cookie的Key,調(diào)用Cookie的getValue方法獲取Cookie的Value
通過Cookie的setMaxAge(int expiry)方法設(shè)置Cookie的有效期。超過參數(shù)expity指定的時間(以秒為單位),Cookie就會失效。
例子:
<html>
<head><title>jspCookie.jsp</title></head>
<body>
<%
Cookie[] cookies=request.getCookies();
//System.out.println("dsfasfdafda");
for(int i=0;i<cookies.length;i++)
{
%>
<p>
<b>Cookie name:</b>
<%=cookies[i].getName()%>
<b>Cookie value:</b>
<%=cookies[i].getValue()%>
</p>
<p>
<b>Old max age in seconds:</b>
<%=cookies[i].getMaxAge()%>
<%
cookies[i].setMaxAge(60);
%>
<b>New max age in seconds:</b>
<%=cookies[i].getMaxAge()%>
<%
}
%>
<%!
int count1=0;
int count2=0;
%>
<%
response.addCookie(new Cookie("cookieName"+count1++,"cookieValue"+count2++));
%>
</body>
</html>
JSP聲明用于聲明JSP代表的Servlet類的成員變量和方法。
語法<%! %>
例如:
<%! int i=0;%>
也可聲明函數(shù):
<!
public String f(int i)
{
if(i<3) return "i<3";
else return "i>=3";
}
>
每個聲明只在當前JSP頁面中有效,如果希望每個JSP頁面中都包含這些聲明,可以把他們寫成單獨的頁面,然后用<%@include%>指令把這個夜明加到其他頁面中。
JAVA程序片段:
JSP文件中,可以在<%和%>標記間直接嵌入任何有效的JAVA語言代碼。這樣嵌入的程序片段稱為Scriptlet。如果在page指令中沒有指定method屬性,則生成代碼默認service方法的主體。
JSP指令用來設(shè)置和整個JSP網(wǎng)頁相關(guān)屬性,如網(wǎng)頁的編碼方式和腳本語言等。
語法:
<%@ 指令名 屬性=“值”%>
常見的3中指令:
page:可以指定所使用的腳本語言、JSP代表的Servlet實現(xiàn)的接口、Servlet擴展的類以及導(dǎo)入的軟件包。
語法:
<%@ page 屬性1=“值1” 屬性2=“值2”%>
例:
<%@ page import="java.util.*" contentType="type/html;charset=GB2312" language="java"%>
page指令的屬性描述:
language:指定文件中所使用的腳本語言目前僅JAVA為有效值和默認值。用作整個文件。
語法:<%@ page language="java"%>
method:指定JAVA程序片段所屬的方法的名稱。JAVA程序片段會成為制動方法的主體。默認的方法是service方法。當多次使用該指令時,只有第一次范圍是有效的,該方法有效值
包括:service、doGet和doPost等。
語法:<%@ page method="doPost"%>
import:指定導(dǎo)入的JAVA軟件包名或類別列表。
語法:<%@page import="java.io.*,java.util.Hashtable"%>
content_type:指定響應(yīng)結(jié)果的MIME類型,默認MIME類型是text/html。默認字符編碼為ISO-8859-1。
語法:<%@ page content_type="text/html;charset=GB2312"%>
session="true|false"
指定JSP頁是否使用Session。默認為TRUE
語法:<%@ page session="true"%>
errorPage="error_url"指定當發(fā)生異常時,客戶請求被重新定向到那個網(wǎng)頁。
語法:
<%@page errorPage="errorpage.jsp"%>
isErrorPage="true|false":表示此JSP網(wǎng)頁是否為處理異常的網(wǎng)頁。
語法:<%@ page isErrorPage="true"%>
include:JSP可以通過include指令來包含其他文件。被調(diào)用的可以是JSP文件、HTML文件或文本文件。
語法:<%@inclue file="relativeURL"%>
開發(fā)網(wǎng)站時,如果多數(shù)JSP網(wǎng)頁都含有相同的內(nèi)容,可以把這部分相同的內(nèi)容單獨放到一個文件中,其他的JSP文件通過include指令將這個文件包含進來,這樣做可以提高開發(fā)網(wǎng)站的效率,而且便于維護網(wǎng)頁。
taglib:自定義JSP標簽
Servlet容器在啟動時會加載Web應(yīng)用,并為每個WEB應(yīng)用創(chuàng)建唯一的ServletContext對象。可以把ServletContext看成是一個WEB應(yīng)用的服務(wù)器端組件的共享內(nèi)存。在ServletContext中可以存放共享數(shù)據(jù),它提供了4個讀取或設(shè)置共享數(shù)據(jù)的方法:
setAttribute(String name,Object object):把一個對象和一個屬性名綁定。將這個對象存儲在ServletContext中。
getAttribute(String name):根據(jù)給定的屬性名返回所綁定的對象;
removeAttribute(String name):根據(jù)給定的屬性名從ServletContext中刪除相應(yīng)的屬性。
getAttribateNames():返回一個Enumeration對象。它包含了存儲在ServletContext對象中的所有屬性名。
package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext extends HttpServlet {
/**
* Constructor of the object.
*/
private static final String CONTEXT_TYPE = "text/html";
private Object Integer;
public ServletContext() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 獲得Context的引用
ServletContext context = (ServletContext) getServletContext();
//response.setContentType("text/html");
PrintWriter out = response.getWriter();
Integer count = (Integer) context.getAttribute("count");
if (count == null) {
count=new Integer(0);
context.setAttribute("count",new Integer(0));
}
response.setContentType(CONTEXT_TYPE);
out.print("<html><head><title>");
out.print(CONTEXT_TYPE+"</title></head><body>");
out.print("<p>This count is:"+count+"</p>");
out.print("</body>");
count=new Integer(count.intValue()+1);
context.setAttribute("count",count);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Put your code here
}
}
創(chuàng)建自己的HttpServlet類,4個步驟:
(1)擴展HttpServlet抽象類。
(2)覆蓋HttpServlet的部分方法,如覆蓋doGet()或doPost方法。
(3)獲取HTTP請求信息,例如通過HttpServletRequest對象來檢索HTML表單所提交的數(shù)據(jù)或URL上的查詢字符串。無論是HTML表單數(shù)據(jù)還是URL上的查詢字符串,在
HttpServletRequest對象中都以參數(shù)名/參數(shù)值的形式存放,可以通過一下方法檢索參數(shù)信息:
getParameterNames():返回一個Enumeration對象,它包含了所有的參數(shù)名信息
getParameter(String name):返回參數(shù)名name對應(yīng)的參數(shù)值
getParameterValues():返回一個Enumeration對象,它包含了所有的參數(shù)值信息HttpServletResponse對象有一個getWriter()方法。該方法返回一個PrintWriter對象。使用
PrintWriter的print()或println()方法可以向客戶端發(fā)送字符串數(shù)據(jù)流。
(4)生成HTTP響應(yīng)結(jié)果。通過HttpServletResponse對象可以生成響應(yīng)結(jié)果。HttpServletResponse對象有一個getWriter()方法,該方法返回一個PrintWriter對象。使用
PrintWriter的print()或println()方法可以向客戶端發(fā)送字符串數(shù)據(jù)流。
例:
package mypack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet//第一步
{
//覆蓋doGet()方法
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
//第三步:獲取HTTP請求中的參數(shù)信息
String clientName=request.getParameter("clientName");
if(clientNme!=null)
clientName=new String(clientName.getBytes("ISO-8859-1"),"GB2312");
else
clientName="我的朋友";
//第四步:生成HTTP響應(yīng)結(jié)果
PrintWriter out;
String title="HelloServlet";
String heading1="This is output from HelloServlet by doGet:";
response.setContentType("text/html;charset=GB2312");/*MIME類型*/
out=response.getWriter();
out.print("<html><head><title>"+title+"<title>");
out.print("</head><body>");
out.print(heading1);
out.print("<h1><p>"+clientName+":您好</h1>");
out.print("</body></html>");
out.close();
}
}
部署Servlet:
在WEB-INF下的Web.xml里增加如下代碼:
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>mypack.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web>
HttpServlet的作用是:
根據(jù)客戶發(fā)出的HTTP請求,生成響應(yīng)的HTTP響應(yīng)結(jié)果。HttpServlet首先必須讀取HTTP請求的內(nèi)容。Servlet容器負責(zé)創(chuàng)建HttpRequest對象,并把HTTP請求信息封裝到HttpRequest對
象中,這大大簡化了HttpServlet解析請求數(shù)據(jù)的工作量。
如果沒有HttpServletRequest,HttpServlet只能直接處理Web客戶發(fā)出的原始的字符串數(shù)據(jù),有了HttpRequest后,只要調(diào)用HttpServletRequest的相關(guān)方法,就可以方便地讀取
HTTP請求中任何部分信息,HttpServletRequest中讀取HTTP請求信息的常用方法如下:
getCookies() 返回HTTP請求的Cookies
getHeader(String name) 返回參數(shù)指定的HTTP請求的Header數(shù)據(jù)
getRequestURI() 返回HTTP請求URI
getQueryString() 返回HTTP請求數(shù)據(jù)中的查詢字符串
getMethod() 返回HTTP請求方法。
Servlet容器向HttpServlet提供了HttpServletResponse對象,HttpServlet可以通過它來生成HTTP響應(yīng)的沒一個部分內(nèi)容。HttpServletResponse提供的生成響應(yīng)數(shù)據(jù)Header的方法
如下:
addCookie(Cookie cookie) 向HTTP響應(yīng)中加入Cookie
setHeader(String name,String value) 設(shè)置HTTP響應(yīng)的Header,如果參數(shù)name對應(yīng)的Header已經(jīng)存在,則覆蓋原來的Header數(shù)據(jù)
addHeader(String name,String value) 向HTTP響應(yīng)加入Header.
HttpServlet的service方法
Servlet容器調(diào)用自身的方法解析HTTP請求信息。
1:Web客戶向Servlet容器發(fā)出HTTP請求;
2:Servlet容器解析Web客戶的HTTP請求;
3:Servlet容器創(chuàng)建一個HttpRequest對象,在這個對象中封裝了HTTP請求信息;
4:Servlet容器創(chuàng)建一個HttpResponse對象;
5:Servlet容器調(diào)用HttpServlet的service方法,把HttpRequest和HttpResponse對象作為service方法的參數(shù)傳給HttpServlet對象;
6:HttpServlet調(diào)用HttpRequest的有關(guān)方法,獲取HTTP請求信息;
7:HttpServlet調(diào)用HttpResponse的有關(guān)方法,生成響應(yīng)數(shù)據(jù);
8:Servlet容器把HttpServlet的響應(yīng)結(jié)果傳給Web客戶。
HTTP是一種基于請求/響應(yīng)模式的協(xié)議。
HTTP請求
HTTP請求有3個部分構(gòu)成,分別是:
請求方法 URI 協(xié)議/版本
請求頭
請求正文
例:
GET/sample.jsp HTTP/1.1
1.請求方法 URI 協(xié)議/版本
請求的第一行是“方法URI 協(xié)議/版本”:
GET/sample.jsp HTTP/1.1
以上代碼中“GET”代表請求方法,“/sample.jsp”表示URI,“HTTP/1.1”代表協(xié)議和協(xié)議的版本。
根據(jù)HTTP標準,HTTP請求可以使用多種請求方法。HTTP1.1支持7中請求方法:GET、POST、HEAD、OPTIONS、PUT、DELETE和TRACE。最常用的:POST和GET。
URI完整地指定了要訪問的網(wǎng)絡(luò)資源,通常只要給出相對于服務(wù)器的根目錄大的相對目錄即可,因此總是以“/”開頭。
協(xié)議版本生命了通信的過程中使用的HTTP的版本。
2.請求頭
請求頭包含許多有關(guān)客戶端環(huán)境和請求正文的有用信息。如:瀏覽器所用的語言,正文的長度等。
Accept:image/gif,image/jpeg,*/*;
3.請求正文
請求頭和請求正文之間時一個空行,這個行非常重要,它表示請求頭已經(jīng)結(jié)束,接下來的是請求正文。請求正文中可以包含客戶提交的查詢字符串信息:
userName=weiqin&password=1234
HTTP 響應(yīng)
由3個部分構(gòu)成:
協(xié)議 狀態(tài)代碼 描述
響應(yīng)頭
響應(yīng)正文
HTTP響應(yīng)例子:
HTTP/1.1 200 OK
1.協(xié)議 狀態(tài)代碼 描述
HTTP 響應(yīng)的第一行類似于HTTP請求的第一行,它表示通信所用的協(xié)議是HTTP1.1,服務(wù)器已經(jīng)成功地處理了客戶端發(fā)出的請求(200 表示成功);
2.響應(yīng)頭
響應(yīng)頭和請求頭一樣包含許多有用的信息,例如服務(wù)器類型,日期時間、內(nèi)容類型和長度等。
Server:ApacheTomcat/5.0.12
3.響應(yīng)正文
響應(yīng)正文就是服務(wù)器返回的HTML頁面:
<html>
<head></head>
...
<body></body>
</html>
分為三個階段:初始化階段、響應(yīng)客戶請求階段和終止階段。
javax.servlet.Servlet接口定義了3個方法:
init()、service()、destroy().
初始化階段:
在下列情況下Servlet容器裝載Servlet:
Servlet容器啟動時自動裝在某些Servlet.
Servlet容器啟動后,客戶首次向Servlet發(fā)出請求。
Servlet的類文件被更新后,重新裝載Servlet.
//Servlet容器是否在啟動時自動裝載Servlet,這是由在web.xml中為Servlet設(shè)置的<load-on-startup>屬性決定的
Servlet被裝載后,Servlet容器創(chuàng)建一個Servlet實例并且調(diào)用Servlet的init()方法進行初始化。在Servlet的整個生命周期中,init方法只會被調(diào)用一次。
重載方式:
public void init(ServletConfig config) throws ServletException;
public void init()throws ServletException;
用第一個方法應(yīng)該先調(diào)用super.init(config)方法確保參數(shù)config應(yīng)用ServletConfig對象;
用第二個方法可以不用調(diào)用super.init()方法,如果要在init方法中訪問ServletConfig對象,可以調(diào)用Servlet類的getServletConfig()方法。
響應(yīng)客戶請求階段
Servlet容器創(chuàng)建特定于這個請求的ServletRequest對象和ServletResponse對象,然后調(diào)用Servlet的service方法從ServletRequest對象獲得客戶請求信息并處理該請求,通過
ServletResponse對象向客戶返回響應(yīng)結(jié)果。
終止階段
當Web應(yīng)用被終止,或Servlet容器終止運行,或Servlet容器重新裝載Servlet的新實例時,Servlet容器會先調(diào)用Servlet的destroy()方法。在destroy方法中,可以釋放Servlet所
占用的資源。
SerletResponse接口:
getOutputStream:返回可以向客戶端發(fā)送二進制數(shù)據(jù)的輸出流對象ServletOutputStream
getWriter:返回可以向客戶端發(fā)送字符數(shù)據(jù)的PrintWriter對象
getCharacterEncoding:返回Servlet發(fā)送的響應(yīng)數(shù)據(jù)的字符編碼。
getContentType:返回Servlet發(fā)送的響應(yīng)數(shù)據(jù)的MIME類型。
setCharacterEncoding:設(shè)置Servlet發(fā)送的響應(yīng)數(shù)據(jù)的字符編碼
setContentType:設(shè)置Servlet發(fā)送的響應(yīng)數(shù)據(jù)的MIME類型。
getAttribute 根據(jù)參數(shù)給定的屬性名返回屬性值。
getContentType:返回客戶請求數(shù)據(jù)MIME類型。
getInputStream:返回以二進制數(shù)方式直接讀取客戶請求數(shù)據(jù)的輸入流.
getParameter:根據(jù)給定的參數(shù)名返回參數(shù)值。
getRemoteAddr:返回遠程客戶主機的IP地址。
getRemoteHost:返回遠程客戶主機名。
getRemotePost:返回遠程主機端口。
setAtrribute:在ServletRequest中設(shè)置屬性。