3.3 輸出html的servlet
大多數(shù)servlet都輸出html,而不象上例一樣輸出純文本。要輸出html還有兩個(gè)額外的步驟要做:告訴瀏覽器接下來發(fā)送的是html;修改println語句構(gòu)造出合法的html頁面。
第一步通過設(shè)置content-type(內(nèi)容類型)應(yīng)答頭完成。一般地,應(yīng)答頭可以通過httpservletresponse的setheader方法設(shè)置,但由于設(shè)置內(nèi)容類型是一個(gè)很頻繁的操作,因此servlet api提供了一個(gè)專用的方法setcontenttype。注意設(shè)置應(yīng)答頭應(yīng)該在通過printwriter發(fā)送內(nèi)容之前進(jìn)行。下面是一個(gè)實(shí)例:
hellowww .java
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class hellowww extends httpservlet {
public void doget(httpservletrequest request,
httpservletresponse response)
throws servletexception, ioexception {
response.setcontenttype("text/html");
printwriter out = response.getwriter();
out.println("<!doctype html public /"-//w3c//dtd html 4.0 " +
"transitional//en/">/n" +
"<html>/n" +
&nb sp; "<head><title>hello www</title></head>/n" +
"<body>/n" +
"<h1>hello www</h1>/n" +
"</body></html>");
}
}
3.4 幾個(gè)html工具函數(shù)
通過println語句輸出html并不方便,根本的解決方法是使用javaserver pages(jsp)。然而,對于標(biāo)準(zhǔn)的servlet來說,由于web頁面中有兩個(gè)部分(doctype和head)一般不會改變,因此可以用工具函數(shù)來封裝生成這些內(nèi)容的代碼。
雖然大多數(shù)主流瀏覽器都會忽略doctype行,但嚴(yán)格地說html規(guī)范是要求有doctype行的,它有助于html語法檢查器根據(jù)所聲明的 html版本檢查html文檔合法性。在許多web頁面中,head部分只包含<title>。雖然許多有經(jīng)驗(yàn)的編寫者都會在head中包含許多meta標(biāo)記和樣式聲明,但這里只考慮最簡單的情況。
下面的java方法只接受頁面標(biāo)題為參數(shù),然后輸出頁面的doctype、head、title部分。清單如下:
servletutilities.java
package hall;
public class servletutilities {
public static final string doctype =
"<!doctype html public /"-//w3c//dtd html 4.0 transitional//en/">";
public static string headwithtitle(string title) {
return(doctype + "/n" + "<html>/n" +
"<head><title>" + title + "</title ></head>/n");
}
// 其他工具函數(shù)的代碼在本文后面介紹
}
hellowww2.java
下面是應(yīng)用了servletutilities之后重寫hellowww類得到的hellowww2:
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class hellowww2 extends httpservlet {
public void doget(httpservletrequest request,
httpservletresponse response)
throws servletexception, ioexception {
response.setcontenttype("text/html");
printwriter out = response.getwriter();
out.println(servletutilities.headwithtitle("hello www") +
"<body>/n" +
"<h1>hello www</h1> ;/n" +
"</body></html>");
}
}
新聞熱點(diǎn)
疑難解答
圖片精選