JavaWeb commonly used classes, interfaces and methods

Commonly used interfaces, classes and methods in Servlet

      Sun company provides a series of interfaces and classes for   the development of Servlet technology, among which the most important interface is javax.servlet.Servlet.

      1.Servlet interface

     Interface declaration: public abstract interface  Servlet

Method declaration

Function description

void init(ServletConfig config)

After the container has created the Servlet object, it will call this method. This method receives a parameter of type ServletConfig, and the Servlet container passes the initial configuration information to the Servlet through this parameter

ServletConfig getServletConfig ()

Used to obtain the configuration information of the Servlet object, and return the ServletConfig object of the Servlet

String getServletInfo()

Returns a string containing information about the servlet, such as author, version, and copyright

void service (ServletRequest request,ServletResponse response)

Responsible for responding to the user's request, when the container receives the client's request to access the Servlet object, it will call this method.
The container constructs a ServletRequest object representing the client request information and a ServletResponse object used to respond to the client as parameters to the service() method.
In the service() method, you can get the relevant information and request information of the client through the ServletRequest object. After processing the request, call the method of the ServletResponse object to set the response information

void destroy()

Responsible for releasing the resources occupied by the Servlet object. When the server is shut down or the Servlet object is removed, the Servlet object will be destroyed and the container will call this method

     For the Servlet interface, Sun provides two default interface implementation classes: GenericServlet and HttpServlet. Among them, GenericServlet is an abstract class, which provides a partial implementation for the Servlet interface, but it does not implement HTTP request processing.

     public abstract class GenericServlet implements  javax.servlet.Servlet ,       javax.servlet.ServletConfig , java.io.Serializable {      HttpServlet is a subclass of GenericServlet, it inherits all the methods of GenericServlet, and provides for types such as GET and POST in HTTP requests A specific method of operation. Generally, the written Servlet classes are inherited from HttpServlet, and the HttpServlet object is also used in development.      public abstract class HttpServlet extends GenericServlet {

     The HttpServlet class contains two commonly used methods

Method declaration

Function description

protected void doGet (HttpServletRequest req, HttpServletResponse resp)

The method used to handle HTTP requests of GET type

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

The method used to process POST type HTTP requests

E.g:

package com.wangxing.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class TestServlet implements Servlet{

	@Override
	public void destroy() {
		System.out.println("销毁Servlet对象的方法");
		
	}

	@Override
	public ServletConfig getServletConfig() {
		System.out.println("得到ServletConfig对象");
		return null;
	}

	@Override 
	public String getServletInfo() {
		System.out.println("得到包含Servlet信息的字符串");
		return null;
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		System.out.println("Servlet初始化方法");
		
	}

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
		System.out.println("处理请求做出响应的方法");
		
	}

}

Configure web.xml

  <servlet>
  	<servlet-name>test</servlet-name>
  	<servlet-class>com.wangxing.servlet.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>test</servlet-name>
  	<url-pattern>/test</url-pattern>
  </servlet-mapping>

      2.ServletConfig interface

          public  abstract  interface  ServletConfig

          When running a servlet program, some auxiliary information may be required, such as the encoding used by the file, the shared information of the servlet program used, etc. This information can be configured using one or more <init-param> elements in the web.xml file. When Tomcat initializes a Servlet, it will encapsulate the configuration information of the Servlet into the ServletConfig object. At this time, the ServletConfig object can be passed to the Servlet by calling the init (ServletConfig config) method.

          ServletConfig is an interface that encapsulates auxiliary information when Servlet is running.

          A series of methods for obtaining configuration information are defined in the ServletConfig interface.

Method description

Function description

String getInitParameter(String name)

Return the corresponding initialization parameter value according to the initialization parameter name

ServletContext getServletContext()

Return a ServletContext object representing the current Web application

String getServletName()

Returns the name of the servlet, which is the value of the <servlet-name> element in web.xml

          We don't need to manually obtain the ServletConfig interface object, and the init method of the servlet interface has been passed.

          For example: get the initialization parameter value configured in the web.xml file through the ServletConfig interface object, and the configured

package com.wangxing.servlet;


import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ConfigServlet extends HttpServlet{
	//得到initconfig对象的两种方法
//	@Override
//	public void init(ServletConfig config) throws ServletException {
//		//String getInitParameter(String name) 根据初始化参数名返回对应的初始化参数值
//		//参数就是web.xml中param-name标记的值
//		String name = config.getInitParameter("name");
//		String pass = config.getInitParameter("pass");
//		System.out.println("name=="+name+"   "+"pass=="+pass);
//	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//String getInitParameter(String name);根据初始化参数名返回对应的初始化参数值
		//参数就是web.xml中param-name标记的值
		ServletConfig config = this.getServletConfig();
		String name = config.getInitParameter("name");
		String pass = config.getInitParameter("pass");
		System.out.println("name=="+name+"   "+"pass=="+pass);
		//String getServletName(); 返回Servlet的名字,即web.xml中<servlet-name>元素的值
		String servletname = config.getServletName();
		System.out.println("servlet-name=="+servletname);
	}
	
}

Configure Web.xml

<servlet>
  	<servlet-name>config</servlet-name>
  	<servlet-class>com.wangxing.servlet.ConfigServlet</servlet-class>
        <!--配置初始化参数-->
	<init-param>
		<param-name>name</param-name>
		<param-value>zhangsan</param-value>
	</init-param>
	<init-param>
		<param-name>pass</param-name>
		<param-value>123456</param-value>
	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>config</servlet-name>
  	<url-pattern>/config</url-pattern>
  </servlet-mapping>

      3.ServletContext interface

            When Tomcat starts, Tomcat will create a unique ServletContext object for each Web application to represent the current Web application, which encapsulates all the information of the current Web application. You can use this object to obtain the Servlet version of the Web application, initialize information, read resource files, and so on.

ServletConfig interface

ServletContext getServletContext()

Return a ServletContext object representing the current Web application

Method description

Function description

int getMajorVersion()

Get the major version number of the servlet specification

int getMinorVersion()

Get the minor version number of the servlet specification

String  getInitParameter(String)

Get the specified initialization information <context-param>

Enumeration<String> getInitParameterNames()

Get the Enumeration object containing the names of all initialization information

 

            Read the resource file under the web application

            In actual development, it is sometimes necessary to read some resource files in the Web application, such as configuration files and log files. For this reason, some methods for reading Web resources are defined in the ServletContext interface, and these methods are implemented by the Servlet container. The Servlet container returns the I/O flow of the associated resource file or the absolute path of the resource file in the system according to the path of the resource file relative to the Web application.
            Relevant methods used to obtain the resource path in the ServletContext interface.

Method description

Function description

InputStream getResourceAsStream(String path)

Returns the InputStream input stream object mapped to a certain resource file. The transmission rules of the parameter path are exactly the same as the getResource() method

Configure web.xml

 <context-param>
  	<param-name>info</param-name>
  	<param-value>测试ServletContext得到context-param数据</param-value>
  </context-param>
  <servlet>
  	<servlet-name>context</servlet-name>
  	<servlet-class>com.wangxing.servlet.ContextServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>context</servlet-name>
  	<url-pattern>/context</url-pattern>
  </servlet-mapping>
package com.wangxing.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

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 ContextServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//ServletContext---对象封装了当前web应用的所有信息
		//得到ServletContext
		ServletContext context1 = this.getServletContext();
		ServletContext context2 = this.getServletConfig().getServletContext();
		//得到Servlet版本
		//int getMajorversion(); 得到servlet规范的主版本号
		//int getMinorVersion(); 得到servlet规范的次版本号
		int major = context1.getMajorVersion();
		int minor = context2.getMinorVersion();
		System.out.println("Servlet版本=="+major+"."+minor);
		//String getInitParameter(String name);得到指定的初始化信息<context-param>
		String info = context1.getInitParameter("info");
		
		System.out.println("info=="+ info);
                System.out.println("-------------------------------------");
//		//读取Web应用下的资源文件
//		//InputStream getResourceAsStream(String path);返回映射到某个资源文件的InputStream输入流对象
//		
		BufferedReader read = new BufferedReader(new InputStreamReader(context1.getResourceAsStream("/WEB-INF/classes/test.properties"),"utf-8"));
		
		String msg = null;
		while((msg = read.readLine()) != null){
			System.out.println(msg);
		}
		read.close();
		
		//返回映射到某个资源文件的 InputStream 输入流对象。
		InputStream in = context1.getResourceAsStream("/WEB-INF/classes/test.properties");
		//Properties继承于Hashtable
		Properties pros = new Properties();
		//void load(InputStream in);会将输入流对象中的文件自动读取
	    pros.load(in);
	    String name = pros.getProperty("name");
	    String age = pros.getProperty("age");
	    String address = pros.getProperty("address");
	    System.out.println("name=="+name+" "+"age=="+age+" "+"address=="+address);
	    in.close();
	    
	}
	
}

     4.HttpServletRequest 接口

          ServletRequest与HttpServletRequest的关系

          HttpServletRequest 接口继承自 ServletRequest 接口。

          主要作用是封装 HTTP 请求消息,所以我们也将HttpServletRequest称之为请求对象。

          由于 HTTP 请求消息分为请求行、请求消息头和请求消息体三部分。

          因此,在HttpServletRequest 接口中定义了获取请求行、请求头和请求消息体的相关方法。

     1.获取请求行信息的相关方法

     当访问 Servlet 时,所有请求消息将被封装到 HttpServletRequest 对象中,请求消息的请求行中包含请求方法、请求资源名、请求路径等信息,为了获取这些信息,HttpServletRequest 接口定义了一系列方法。

方法声明

功能描述

String getMethod()

该方法用于获取 HTTP 请求消息中的请求方式(如 GET、POST 等)

String getRequestURI()

该方法用于获取请求行中的资源名称部分即位于 URL 的主机和端门之后、参数部分之前的部分

String getQueryString()

该方法用于获取请求行中的参数部分,也就是资源路径后问号(?)以后的所有内容

String getContextPath()

该方法用于获取请求 URL 中属于 Web 应用程序的路径,这个路径以 / 开头,表示相对于整个 Web 站点的根目录,路径结尾不含 /。如果请求 URL 属于 Web 站点的根目录,那么返回结果为空字符串("")

String getServletPath()

该方法用于获取 Servlet 的名称或 Servlet 所映射的路径

String getRemoteAddr()

该方法用于获取请求客户端的 IP 地址,其格式类似于 192.168.0.3

String getRemoteHost()

该方法用于获取请求客户端的完整主机名,其格式类似于 pcl.mengma.com。需要注意的是,如果无法解析出客户机的完整主机名,那么该方法将会返回客户端的 IP 地址

int getRemotePort()

该方法用于获取请求客户端网络连接的端口号

String getLocaIAddr()

该方法用于获取 Web 服务器上接收当前请求网络连接的 IP 地址

String getLocalName()


该方法用于获取 Web 服务器上接收当前网络连接 IP 所对应的主机名

int getLocalPort()

该方法用于获取 Web 服务器上接收当前网络连接的端口号

String getServerName()

该方法用于获取当前请求所指向的主机名,即 HTTP 请求消息中 Host 头字段所对应的主机名部分

int gctServcrPort()

该方法用于获取当前请求所连接的服务器端口号,即 HTTP 请求消息中 Host 头字段所对应的端口号部分

StringBuffcr getRequestURL()

该方法用于获取客户端发出请求时的完整 URL,包括协议、服务器名、端口号、 资源路径等信息,但不包括后面的査询参数部分。注意,getRequcstURL() 方法返冋的结果是 StringBuffer 类型,而不是 String 类型,这样更便于对结果进行修改

http://localhost:8080/TestServlet7/test7?name=lisi

问号后面的数据就是getQueryString的数据

package com.wangxing.servlet;

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 RequestServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取请求行信息的相关方法
		System.out.println("getMethod : " + req.getMethod());
		System.out.println("getRequestURL : " + req.getRequestURI());
		System.out.println("getQueryString:" + req.getQueryString());
		System.out.println("getContextPath:" + req.getContextPath());
		System.out.println("getServletPath:" + req.getServletPath());
		System.out.println("getRemoteAddr : " + req.getRemoteAddr());
		System.out.println("getRemoteHost : " + req.getRemoteHost());
		System.out.println("getRemotePort : " + req.getRemotePort());
		System.out.println("getLocalAddr : " + req.getLocalAddr());
		System.out.println("getLocalName : " + req.getLocalName());
		System.out.println("getLocalPort : " + req.getLocalPort());
		System.out.println("getServerName : " + req.getServerName());
		System.out.println("getServerPort : " + req.getServerPort());
		System.out.println("getRequestURL : " + req.getRequestURL());
		
	}
}

 

    2.获取请求消息头的相关方法

        浏览器发送 Servlet 请求时,需要通过请求消息头向服务器传递附加信息,例如,客户端可以接收的数据类型、压缩方式、语言等。为此,在 HttpServletRequest 接口中定义了一系列用于获取 HTTP 请求头字段的方法

方法声明

功能描述

String getHeader(String name)

该方法用于获取一个指定头字段的值,如果请求消息中没有包含指定的头字段,则 getHeader() 方法返回 null;如果请求消息中包含多个指定名称的头字段,则 getHeader() 方法返回其中第一个头字段的值

Enumeration getHeaders(String name)


该方法返回一个 Enumeration 集合对象,该集合对象由请求消息中出现的某个指定名称的所有头字段值组成。在多数情况下,一个头字段名在请求消息中只出现一次,但有时可能会出现多次

Enumeration getHeaderNames()

该方法用于获取一个包含所有请求头字段的 Enumeration 对象

int getIntHeader(String name)

该方法用于获取指定名称的头字段,并且将其值转为 int 类型。需要注意的是,如果指定名称的头字段不存在,则返回值为 -1;如果获取到的头字段的值不能转为 int 类型,则将发生 NumberFormatException 异常

long getDateHeader(String name)

该方法用于获取指定头字段的值,并将其按 GMT 时间格式转换为一个代表日期/时间的长整数,该长整数是自 1970 年 1 月 1 日 0 时 0 分 0 秒算起的以毫秒为单位的时间值

String getContentType()

该方法用于获取 Content-Type 头字段的值,结果为 String 类型

int getContentLength()

该方法用于获取 Content-Length 头字段的值,结果为 int 类型

String getCharacterEncoding()

该方法用于返回请求消息的实体部分的字符集编码,通常是从 Content-Type 头字段中进行提取,结果为 String 类型

Void setCharacterEncoding(String charname)

设置请求对象的字符编码

package com.wangxing.servlet;

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 RequestServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取请求消息中的所有头字段
		Enumeration headerNames = req.getHeaderNames();
		//用循环便利所有请求头,并通过getHeader();方法获取一个指定名称的头字段
		while(headerNames.hasMoreElements()){
			//得到请求头的名称
			String headerName = (String) headerNames.nextElement();
			System.out.println(headerName+":"+req.getHeader(headerName));
		}
		

	}
	
}

    3.获取请求参数

    在实际开发中,经常需要获取用户提交的表单数据,例如用户名和密码等,为了方便获取表单中的请求参数,在 HttpServletRequest 接口的父类 ServletRequest 中定义了一系列获取请求参数的方法

方法声明

功能描述

String getParameter(String name)

该方法用于获取某个指定名称的参数值。
如果请求消息中没有包含指定名称的参数,则 getParameter() 方法返回 null。
如果指定名称的参数存在但没有设置值,则返回一个空串。
如果请求消息中包含多个该指定名称的参数,则 getParameter() 方法返回第一个出现的参数值。


String [] getParameterValues (String name)

HTTP 请求消息中可以有多个相同名称的参数(通常由一个包含多个同名的字段元素的 form 表单生成),如果要获得 HTTP 请求消息中的同一个参数名所对应的所有参数值,那么就应该使用 getParameterValues() 方法,该方法用于返回一个 String 类型的数组。

Enumeration getParameterNames()

方法用于返回一个包含请求消息中所有参数名的 Enumeration 对象,在此基础上,可以对请求消息中的所有参数进行遍历处理。

Map getParameterMap()

getParameterMap() 方法用于将请求消息中的所有参数名和值装入一个 Map 对象中返回。

例如:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册页面</title>
</head>
<body>
  <form action="/TestServlet7/test7" method="post">
        用户名:<input type="text" name="username"><br/>
        密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="password"/><br/>
        <br/>
        爱好:
        <input type="checkbox" name="hobby" value="sing"/>唱歌
        <input type="checkbox" name="hobby" value="dance"/>跳舞
        <input type="checkbox" name="hobby" value="game"/>玩游戏
        <br/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>
package com.wangxing.servlet;

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 RequestServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到请求内容
		//String getParameter(String name)---得到指定的请求参数值
		//String name -- 参数--input元素的name属性值
		String name = req.getParameter("username");
		String pass = req.getParameter("password");
		//String [] getParameterValues(String name);
		String hobby[] = req.getParameterValues("hobby");
		System.out.println("name=="+name+"  "+"password=="+pass);
		for(String str: hobby){
			System.out.println("爱好=="+str);
		}
	}
	
}

     5.HttpServletResponse 

        HttpServletResponse 接口继承自 ServletResponse 接口。

        主要用于封装 HTTP 响应消息。

        由于 HTTP 响应消息分为状态行、响应消息头、消息体三部分。因此,在 HttpServletResponse 接口中定义了向客户端发送响应状态码、响应消息头、响应消息体的方法。

        1.发送状态码相关的方法

        当 Servlet 向客户端回送响应消息时,需要在响应消息中设置状态码。

        1)setStatus(int status)方法

           该方法用于设置 HTTP 响应消息的状态码,并生成响应状态行。由于响应状态行中的状态描述信息直接与状态码相关,而 HTTP 版本由服务器确定,因此,只要通过 setStatus(int status)方法设置了状态码,即可实现状态行的发送。需要注意的是,在正常情况下,Web 服务器会默认产生一个状态码为 200 的状态行。

        2)sendError(int sc)方法

           该方法用于发送表示错误信息的状态码。例如,404 状态码表示找不到客户端请求的资源。response 对象提供了两个重载的 sendError(int sc)方法,具体如下:

        public void sendError(int code) throws java.io.IOException
        public void sendError(int code,String message)throws java.io.IOException

        在上面重载的两个方法中,第一个方法只发送错误信息的状态码,而第二个方法除了发送状态码以外,还可以增加一条用于提示说明的文本信息,该文本信息将出现在发送给客户端的正文内容中。

        2.发送响应消息头相关的方法

方法声明

功能描述

void addHeader(String name,String value)

这两个方法都是用于设置 HTTP 协议的响应头字段。其中,参数 name 用于指定响应头字段的名称,参数 value 用于指定响 应头字段的值。不同的是,addHeader() 方法可以增加同名的响应头字段,而 setHeader() 方法则会覆盖同名的头字段

void setHeader (String name,String value)

void addIntHeader(String name,int value)

这两个方法专门用于设置包含整数值的响应头,避免了使用 addHeader() 与 setHeader() 方法时需要将 int 类型的设置值转换为 String 类型的麻烦


void setIntHeader(String name, int value)

void setContentType(String type)

该方法用于设置 Servlet 输出内容的 MIME 类型,对于 HTTP 协议来说,就是设置 Content-Type 响应头字段的值。例如,如果发送到客户端的内容是 jpeg 格式的图像数据,就需要将响应头字段的类型设置为 image/jpeg。需要注意的是,如果响应的内容为文本,setContentType() 方法还可以设置字符编码,如 text/html;charset = UTF-8

void setLocale (Locale loc)

该方法用于设置响应消息的本地化信息。对 HTTP 来说,就是设置 Content-Language 响应头字段和 Content-Type 头字段中的字符集编码部分。需要注意的是,如果 HTTP 消息没有设置 Content-Type 头字段,则 setLocale() 方法设置的字符集编码不会出现在 HTTP 消息的响应头中,如果调用 setCharacterEncoding() 或 setContentType() 方法指定了响应内 容的字符集编码,则 setLocale() 方法将不再具有指定字符集编码的功能

void setCharacterEncoding(String charset)

该方法用于设置输出内容使用的字符编码,对 HTTP 协议来说,就是设置 Content-Type 头字段中的字符集编码部分。如果没有设置 Content-Type 头字段,则 setCharacterEncoding 方法设 置的字符集编码不会出现在 HTTP 消息的响应头中。setCharacterEncoding() 方法比 setContentType() 和 setLocale() 方法的优先权高,它的设置结果将覆盖 setContentType() 和 setLocale() 方法所设置的字符码表

需要注意的是,在上表列举的一系列方法中,addHeader()、setHeader()、addIntHeader()、setIntHeader() 方法都用于设置各种头字段,而 setContetType()、setLoacale() 和 setCharacterEncoding() 方法用于设置字符编码,这些设置字符编码的方法可以有效解决乱码问题。

        3.发送响应消息体相关的方法

        由于在 HTTP 响应消息中,大量的数据都是通过响应消息体传递的,因此,ServletResponse 遵循以 I/O 流传递大量数据的设计理念。在发送响应消息体时,定义了两个与输出流相关的方法。

        1)getOutputStream() 方法

        该方法所获取的字节输出流对象为 ServletOutputStream 类型。由于 ServletOutputStream是        OutputStream 的子类,它可以直接输出字节数组中的二进制数据。因此,要想输出二进制格式的响应正文,就需要使用 getOutputStream() 方法。

        2)getWriter() 方法

        该方法所获取的字符输出流对象为 PrintWriter 类型。由于 PrintWriter 类型的对象可以直接输出字符文本内容,因此,要想输出内容全部为字符文本的网页文档,则需要使用 getWriter() 方法。

        例如:通过HttpServletResponse 接口输出一个html文件

package com.wangxing.servlet;

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 ResponseServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();
		out.println("<html><head><meta charset=\"utf-8\"><title>测试HttpServletResponse接口输出一个html文件</title></head><body><h1>这是我的第一个servlet程序</h1></body></html>");
		out.close();
	}
	
}

接口名称

作用

常见方法

 

Servlet

主接口

void init(ServletConfig config)

void service (ServletRequest req,ServletResponse resp)

void destroy()

 

ServletConfig

Servlet的配置对象

String getInitParameter(String name)

ServletContext getServletContext()

有init方法时,不需要获取

没有init方法时,this.getServletConfig();

ServletContext

当前应用对象

int getMajorVersion()

int getMinorVersion()

String  getInitParameter(String)

InputStream getResourceAsStream(String path)

this.getServletContext();

ServletRequest

子接口

HttpServletRequest

 

请求对象

getServerName()

getServerPort()

getContextPath()

void setCharacterEncoding(String charname)

String getParameter(String name)

String [] getParameterValues (String name)

 

ServletResponse

子接口

HttpServletResponse

响应对象

void setCharacterEncoding(String charset)

PrintWriter  getWriter() 

 

Guess you like

Origin blog.csdn.net/m0_49935332/article/details/114996826