3.3 輸出html的servlet
大多數servlet都輸出html,而不象上例一樣輸出純文本。要輸出html還有兩個額外的步驟要做:告訴瀏覽器接下來發送的是html;修改println語句構造出合法的html頁面。
第一步通過設置content-type(內容類型)應答頭完成。一般地,應答頭可以通過httpservletresponse的setheader方法設置,但由于設置內容類型是一個很頻繁的操作,因此servlet api提供了一個專用的方法setcontenttype。注意設置應答頭應該在通過printwriter發送內容之前進行。下面是一個實例:
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 幾個html工具函數
通過println語句輸出html并不方便,根本的解決方法是使用javaserver pages(jsp)。然而,對于標準的servlet來說,由于web頁面中有兩個部分(doctype和head)一般不會改變,因此可以用工具函數來封裝生成這些內容的代碼。
雖然大多數主流瀏覽器都會忽略doctype行,但嚴格地說html規范是要求有doctype行的,它有助于html語法檢查器根據所聲明的 html版本檢查html文檔合法性。在許多web頁面中,head部分只包含<title>。雖然許多有經驗的編寫者都會在head中包含許多meta標記和樣式聲明,但這里只考慮最簡單的情況。
下面的java方法只接受頁面標題為參數,然后輸出頁面的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");
}
// 其他工具函數的代碼在本文后面介紹
}
hellowww2.java
下面是應用了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>");
}
}
新聞熱點
疑難解答