在Servlet的配置文件中,可以使用一个或多个
实验1:day0800servletConfig
工程架构:
工程下的web.xml文件内容
ServletConfig1
com.heima.servletConfig.ServletConfig1
ServletConfig2
com.heima.servletConfig.ServletConfig2
姓名
张无忌
年龄
20
性别
男
ServletConfig1
/servlet/ServletConfig1
ServletConfig2
/servlet/ServletConfig2
index.jsp
ServletConfig1.java
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;
//演示获取ServletConfig对象
/**
* 方法一:采用init方法获取
* 方法二:采用getServletConfig()方法获取
* @author Administrator
*
*/
public class ServletConfig1 extends HttpServlet {
private ServletConfig config ;
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config ;
super.init(config) ;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
ServletConfig config1 = getServletConfig() ;
System.out.println(config == config1);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在配置完服务器后,在浏览器输入http://localhost:8080/day0800servletConfig/servlet/ServletConfig1
输出结果:
true,证明config和 config1 是同一个对象
当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以得到当前servlet的初始化参数信息。
ServletConfig2.java
import java.io.IOException;
import java.util.Enumeration;
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 ServletConfig2 extends HttpServlet {
private ServletConfig config ;
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config ;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//演示获取单个配置信息
//String name = config.getInitParameter("姓名") ;
//System.out.println(name );
//演示获取所有的配置参数
Enumeration enu = config.getInitParameterNames() ;
while(enu.hasMoreElements()){
String key = enu.nextElement() ;
System.out.println(key+ ":" + config.getInitParameter(key));
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。
实验2:/day0801servletContext
工程架构如下:
工程中的web.xml文件内容如下:
ServletContext1
com.heima.servletcontext.ServletContext1
ServletContext2
one.ServletContext2
ServletContext3
one.ServletContext3
ServletContext4
two.ServletContext4
ServletContext5
three.ServletContext5
ServletContext6
three.ServletContext6
ServletContext7
four.ServletContext7
name
东西方不败
sex
人妖
ServletContext1
/servlet/ServletContext1
ServletContext2
/servlet/ServletContext2
ServletContext3
/servlet/ServletContext3
ServletContext4
/servlet/ServletContext4
ServletContext5
/servlet/ServletContext5
ServletContext6
/servlet/ServletContext6
ServletContext7
/servlet/ServletContext7
index.jsp
ServletContext1.java
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示获取servletContext对象的方法
/**
* 方法一: 采用ServletConfig对象获取
* 方法二: 采用getServletContext()方法
* 方法二: 采用request.getSession().getServletContext() 获取
* @author Administrator
*
*/
public class ServletContext1 extends HttpServlet {
private ServletContext sc ;
@Override
public void init(ServletConfig config) throws ServletException {
sc = config.getServletContext() ;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//方式二
// sc = getServletContext() ;
ServletContext sc1 = request.getSession().getServletContext() ;
System.out.println(sc == sc1);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器里输入:http://localhost:8080/day0801servletContext/servlet/ServletContext1,
得出结果:true,证明sc和sc1是同一个对象。
由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。
多个Servlet通过ServletContext对象实现数据共享。
ServletContext2.java
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示在servletContext对象共享数据
public class ServletContext2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
ServletContext sc = getServletContext();
sc.setAttribute("name", "东方不败");
System.out.println("数据存储完毕");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletContext3.java
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//从servletContext中拿取数据
public class ServletContext3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
ServletContext sc = getServletContext();
String name = (String) sc.getAttribute("name");
System.out.println(name);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
当在浏览器中输入 http://localhost:8080/day0801servletContext/servlet/ServletContext2后观察服务器的结果是:数据存储完毕。然后再在浏览器中输入 http://localhost:8080/day0801servletContext/servlet/ServletContext3,
结果为:东方不败。测试成功。
获取WEB应用的初始化参数。
ServletContext4.java
import java.io.IOException;
import java.util.Enumeration;
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 ServletContext4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
ServletContext sc = getServletContext();
// 演示获取单个配置参数
// String name = sc.getInitParameter("name") ;
// System.out.println(name);
// 演示拿取多个配置参数
Enumeration enu = sc.getInitParameterNames();
while (enu.hasMoreElements()) {
String key = enu.nextElement();
System.out.println(key + " :" + sc.getInitParameter(key));
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器输入:http://localhost:8080/day0801servletContext/servlet/ServletContext4,服务器结果为: sex :人妖 name :东西方不败 测试成功。
实现Servlet的转发。
ServletContext5.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 ServletContext5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 获取全局对象
ServletContext sc = getServletContext();
// 获取请求转发器
RequestDispatcher rd = sc
.getRequestDispatcher("/servlet/ServletContext6");
/**
* URL的写法: 1. 客户端跳转: 由浏览器跳转 :超链,重定向 : 一定要加工程路径 2. 服务器跳转 : 由服务器发出来的跳转 :
* 请求转发 : 不要加工程路径
*/
// 转发
rd.forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ServletContext6.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContext6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("我喜欢芙蓉姐姐");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
当在浏览器中输入 http://localhost:8080/day0801servletContext/servlet/ServletContext5后观察 结果是:
利用ServletContext对象读取资源文件。
.properties文件(属性文件)
得到文件路径(ServletContext.getRealPath(),ServletContext.getReaourceAsStream())
在工程构架中的Properties文件内容如下:
ServletContext7.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示获取不同路径下的资源
/**
* 第一种:采用servletContext获取资源 第二种:采用ResourceBundle类获取 : 不能拿取web环境下的资源
* 第三种:采用类加载器加载资源 :不能拿取web环境下的资源
*
* 比较: 第一种方式获取任意资源,任意路径. 第二种方式 只能获取properties类型的资源,web环境下的资源拿不到
* 第三种方式拿取任意资源,不能拿取web环境下的资源
*/
public class ServletContext7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
ServletContext sc = getServletContext();
try {
// test11(sc) ;
// test12(sc) ;
// test13(sc) ;
// test21() ;
// test22() ;
// test31() ;
// test32() ;
test33();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
// 方式一: 用servletContext对象获取p2的内容
public void test11(ServletContext sc) throws Exception {
// 拿到p2文件的路径
String path = sc.getRealPath("/WEB-INF/classes/p2.properties");
System.out.println(path);
// 创建一个输入字节流对象
FileInputStream fis = new FileInputStream(path);
// 加载文件
Properties pro = new Properties();
pro.load(fis);
// 获取内容
System.out.println(pro.getProperty("k1"));
}
// 方式一: 用servletContext对象获取p1的内容
public void test12(ServletContext sc) throws Exception {
// 拿到p2文件的路径
String path = sc.getRealPath("/WEB-INF/classes/four/p1.properties");
System.out.println(path);
// 创建一个输入字节流对象
FileInputStream fis = new FileInputStream(path);
// 加载文件
Properties pro = new Properties();
pro.load(fis);
// 获取内容
System.out.println(pro.getProperty("k1"));
}
// 方式一: 用servletContext对象获取p3的内容
public void test13(ServletContext sc) throws Exception {
// 拿到p2文件的路径
String path = sc.getRealPath("/WEB-INF/p3.properties");
System.out.println(path);
// 创建一个输入字节流对象
FileInputStream fis = new FileInputStream(path);
// 加载文件
Properties pro = new Properties();
pro.load(fis);
// 获取内容
System.out.println(pro.getProperty("k1"));
}
// 方式二: 对象获取p2的内容
public void test21() {
// 获取resourceBundle对象
ResourceBundle rb = ResourceBundle.getBundle("p2"); // 默认的路径是src,对应服务器上的路径是classes
System.out.println(rb.getString("k1"));
}
// 方式二: 对象获取p1的内容
public void test22() {
// 获取resourceBundle对象
ResourceBundle rb = ResourceBundle.getBundle("four.p1"); // 默认的路径是src,对应服务器上的路径是classes
System.out.println(rb.getString("k1"));
}
// 方法三:采用类加载器获取p2的内容
public void test31() throws Exception {
// ServletContext7.class
// this.getClass() ;
// class.forName("four.ServletContext7") ;
InputStream is = ServletContext7.class.getClassLoader()
.getResourceAsStream("p2.properties"); // 默认的路径是src,对应服务器上的路径是classes
// 加载文件
Properties pro = new Properties();
pro.load(is);
// 获取内容
System.out.println(pro.getProperty("k1"));
}
// 方法三:采用类加载器获取p1的内容
public void test32() throws Exception {
// ServletContext7.class
// this.getClass() ;
// class.forName("four.ServletContext7") ;
InputStream is = ServletContext7.class.getClassLoader()
.getResourceAsStream("four/p1.properties"); // 默认的路径是src,对应服务器上的路径是classes
// 加载文件
Properties pro = new Properties();
pro.load(is);
// 获取内容
System.out.println(pro.getProperty("k1"));
}
// 方法三:采用类加载器获取p1的内容
public void test33() throws Exception {
// ServletContext7.class
// this.getClass() ;
// class.forName("four.ServletContext7") ;
URL url = ServletContext7.class.getClassLoader().getResource(
"four/p1.properties");// 默认的路径是src,对应服务器上的路径是classes
String path = url.getPath();
InputStream is = new FileInputStream(path);
// 加载文件
Properties pro = new Properties();
pro.load(is);
// 获取内容
System.out.println(pro.getProperty("k1"));
}
}
Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象、和代表响应的response对象。
request和response对象即然代表请求和响应,那我们要获取客户机提交过来的数据,只需要找request对象就行了。要向容器输出数据,只需要找response对象就行了。
HttpServletResponse:HttpServletResponse对象代表服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。
用OutputStream(字节流)发送数据:
a、response.getOutputStream().write(“中国”.getBytes());//以默认编码发送数据
b、response.getOutputStream().write("中国".getBytes("UTF-8"));//以UTF-8编码发送数据,浏览器(默认用GB2312)会出现乱码
画图描述出现该问题的原因。
解决办法:
a. 通过更改浏览器的编码方式:IE/”查看”/”编码”/”UTF-8”(不可取)
b. 通过设置响应头告知客户端编码方式:response.setHeader(“Content-type”, “text/html;charset=UTF-8”);//告知浏览器数据类型及编码
c. 通过meta标签模拟请求头:out.write("".getBytes());
d. 通过以下方法:response.setContentType("text/html;charset=UTF-8");
总结:程序以什么编码输出,就需要告知客户端以什么编码显示。
用PrintWriter(字符流)发送数据:
示例:response.getWriter().write(“中国” );有没有乱码?
原因:以默认编码发送数据 ISO-8859-1(没有中国二字编码),此时会发生乱码
解决办法:
setCharacterEncoding(“UTF-8”);//更改编码为UTF-8
response.setHead(“Context-type”,”text/html;charset=UTF-8”);//告诉客户端编码方式
注意:不要忘记告诉客户端的编码方式。
由于经常改动编码,response提供了一种更简单的方式
response. setContentType(“text/html;charset=UTF-8”);其作用相当于以上两条代码。
实验:/day0802httpServletResponse
工程架构如图:
工程中的web.xml文档内容如下:
ServletResponse1
com.heima.response.ServletResponse1
ServletResponse2
com.heima.response.ServletResponse2
ServletResponse3
com.heima.response.ServletResponse3
ServletResponse4
com.heima.response.ServletResponse4
ServletResponse5
com.heima.response.ServletResponse5
ServletResponse6
com.heima.response.ServletResponse6
ServletResponse7
com.heima.response.ServletResponse7
ServletResponse1
/servlet/ServletResponse1
ServletResponse2
/servlet/ServletResponse2
ServletResponse3
/servlet/ServletResponse3
ServletResponse4
/servlet/ServletResponse4
ServletResponse5
/servlet/ServletResponse5
ServletResponse6
/servlet/ServletResponse6
ServletResponse7
/servlet/ServletResponse7
index.jsp
ServletResponse1.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示中文乱码的解决
public class ServletResponse1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Test1(response);
test2(response);
}
//字节流输出中文
private void Test1(HttpServletResponse response) throws IOException,
UnsupportedEncodingException {
//演示字节流输出中文
ServletOutputStream sos = response.getOutputStream() ;
//方法一:告诉用户自己选择编码(不靠谱)
//方法二:通知浏览器采用哪个码表
//response.setHeader("Content-Type", "text/html;charset=UTF-8") ;
//方式三:输出字符串
//sos.write("".getBytes()) ;
//方法四:通知服务器用的编码,同时告诉浏览器用的码表
//response.setCharacterEncoding("UTF-8") ;
//response.setHeader("Content-Type", "text/html;charset=UTF-8") ;
//方法五: (推荐)
response.setContentType("text/html;charset=UTF-8") ; //此句话有两个作用: 1.告诉服务器发送数据的的时候的编码
// 2. 通知浏览器解码的时候所用的码表
sos.write("林志玲3".getBytes("UTF-8")) ;
}
//演示字符流输出中文
public void test2(HttpServletResponse response){
response.setContentType("text/html;charset=UTF-8") ;
try {
response.getWriter().write("陈冠希") ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器输入http://localhost:8080/day0802httpServletResponse/servlet/ServletResponse1
结果:
ServletResponse2.java
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示中文文件名的下载
public class ServletResponse2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//拿到图片的绝对路径
String path = getServletContext().getRealPath("/WEB-INF/classes/美女.jpg") ;
//创建一个输入流
FileInputStream fis = new FileInputStream(path) ;
//创建一个输出流
ServletOutputStream sos = response.getOutputStream() ;
//截取中文文件名
String filename = path.substring(path.lastIndexOf("\\") + 1) ;
//通知浏览器以下载的方式打开
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"UTF-8")) ;
//通知浏览器文件名的MIME类型
response.setHeader("Content-Type", "application/octet-stream") ;
//输送数据
byte[] bs = new byte[1024] ;
int b = 0 ;
while((b = fis.read(bs)) != -1){
sos.write(bs,0,b) ;
}
fis.close() ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0802httpServletResponse/servlet/ServletResponse2
结果如图:
a. 输出随机图片(CAPTCHA图像):Completely Automated Public Turing Test to Tell Computers and Humans Apart (全自动区分计算机和人类的测试)
b. 相关主要类(JDK 查看API)
BufferedImage:内存图像
Graphics:画笔
ImageIO:输出图像
放在html页面上
注意:浏览器默认会缓存图片
控制客户端不要缓存:
response.addHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
c. js刷新图片
MyHtml.html
MyHtml.html
ServletResponse3.java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示验证码的生成
public class ServletResponse3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置图片的宽度,高度
int width = 120 ;
int height = 30 ;
//创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) ;
//拿到图片的画笔
Graphics g = image.getGraphics() ;
//设置边框的颜色
g.setColor(Color.RED) ;
//将图片画出来
g.drawRect(0, 0, width, height) ;
//填充一下背景
g.setColor(Color.yellow) ;
//填充背景
g.fillRect(1, 1, width-2, height-2) ;
//画4个数字
Random r = new Random() ;
g.setColor(Color.red) ;
g.setFont(new Font("幼圆", Font.BOLD + Font.ITALIC, 18)) ;
// for (int i = 0; i < 4; i++) {
// g.drawString(r.nextInt(10) + "", 20 + i*20, 20) ;
// }
//随机画30条干扰线
g.setColor(Color.gray) ;
for (int i = 0; i < 30; i++) {
g.drawLine(r.nextInt(width), r.nextInt(height),r.nextInt(width), r.nextInt(height)) ;
}
//画中文
g.setColor(Color.red) ;
String s = "中国好声音深圳黑鸟训练营Ilovemoney" ;
s = "\u4E2D\u56FD\u597D\u58F0\u97F3\u6DF1\u5733\u9ED1\u9A6C\u8BAD\u7EC3\u8425Ilovemoney" ;
for (int i = 0; i < 4; i++) {
g.drawString(s.charAt(r.nextInt(s.length())) + "", 20 + i*20 + r.nextInt(5), 18 + r.nextInt(5)) ;
}
response.setHeader("Expires", "-1") ;
response.setHeader("Cache-Control", "no-cache") ; //使用1.1协议
response.setHeader("Pragma", "no-cache") ; //使用1.0协议
//创建imageIO对象
ImageIO.write(image, "jpg", response.getOutputStream()) ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0802httpServletResponse/MyHtml.html
输出结果:
ServletResponse4.java
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示刷新
public class ServletResponse4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//定时刷新自己
//response.setHeader("Refresh", "2") ;
//response.getWriter().write("abcd" + new Random().nextInt()) ;
//定时刷新到其他页面
response.setHeader("Refresh", "2;url=/day08_02_httpServletResponse/MyHtml.html") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0802httpServletResponse/servlet/ServletResponse4
输出结果:2秒后刷新到另一个页面中:
ServletResponse5.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//控制浏览器缓存时间
public class ServletResponse5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getOutputStream().write("大家好".getBytes()) ;
response.setDateHeader("Expires", System.currentTimeMillis() + 10000) ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0802httpServletResponse/servlet/ServletResponse5
结果:
ServletResponse6.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示请求重定向
public class ServletResponse6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//第一种方式
//response.setStatus(302) ;
//response.setHeader("Location", "/day08_02_httpServletResponse/servlet/ServletResponse3") ;
//第二种方式
response.sendRedirect("/day08_02_httpServletResponse/servlet/ServletResponse3") ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0802httpServletResponse/servlet/ServletResponse6 结果页面重定向到了http://localhost:8080/day0802httpServletResponse/servlet/ServletResponse3
如图:
a. getOutputStream和getWriter方法分别用于得到输出二进制数据、输出文本数据的ServletOuputStream、Printwriter对象。
b. getOutputStream和getWriter这两个方法互相排斥,调用了其中的任何一个方法后,就不能再调用另一方法。 会抛异常。
c. Servlet程序向ServletOutputStream或PrintWriter对象中写入的数据将被Servlet引擎从response里面获取,Servlet引擎将这些数据当作响应消息的正文,然后再与响应状态行和各响应头组合后输出到客户端。
d. Serlvet的service方法结束后,Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果没有,Servlet引擎将调用close方法关闭该输出流对象。
ServletResponse7.java
package com.heima.response;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//演示response细节
public class ServletResponse7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.getWriter().write("aaaaaaaaaaaaaaaaaaa") ;
//response.getOutputStream().write("大s".getBytes()) ;
response.getOutputStream().write((65+"").getBytes()) ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在浏览器中输入:http://localhost:8080/day0802httpServletResponse/servlet/ServletResponse7
结果:
资料下载