国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JSP > 正文

Java Servlet 和 JSP教程(4)

2024-09-05 00:20:19
字體:
供稿:網(wǎng)友

  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>");
}
}

  • 本文來源于網(wǎng)頁設(shè)計(jì)愛好者web開發(fā)社區(qū)http://www.html.org.cn收集整理,歡迎訪問。
  • 發(fā)表評論 共有條評論
    用戶名: 密碼:
    驗(yàn)證碼: 匿名發(fā)表
    主站蜘蛛池模板: 彰化县| 莎车县| 莱芜市| 高雄市| 内黄县| 名山县| 新干县| 怀宁县| 博罗县| 临沭县| 武义县| 历史| 湘乡市| 杭锦后旗| 余庆县| 家居| 西宁市| 五原县| 安塞县| 美姑县| 塔城市| 阿克苏市| 太谷县| 吉安市| 盘锦市| 海宁市| 福清市| 曲沃县| 都兰县| 沂水县| 泾川县| 兴山县| 成安县| 光泽县| 英超| 玛曲县| 长阳| 关岭| 北海市| 安徽省| 多伦县|