request代表了请求
response代表响应
HttpServletResponse
setStatus();----->发送状态码
setHeader();---->发送响应头
getWriter();和getOutputStream();------>发送数据
addHeader();---->添加一个头
containsHeader();--->包含几个头
HttpServletResponse细节一-------》码表的对应设置charset=UTF-8
ResponseDemo1
如果不加:
response.setHeader("Content-type","text/html;charset=UTF-8");
浏览器读出涓球,默认国标读,不是utf-8
package cn.itcaste.web.servlet; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ResponseDemo1") public class ResponseDemo1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // test2(response); //test1(response); } private void test2(HttpServletResponse response) throws IOException, UnsupportedEncodingException { //用html技术中的meta标签模拟http响应头,来控制浏览器的行为 String data="中国"; OutputStream out=response.getOutputStream(); out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes()); out.write(data.getBytes("UTF-8")); } private void test1(HttpServletResponse response) throws IOException, UnsupportedEncodingException { //以什么编码发就用什么编码读 response.setHeader("Content-type","text/html;charset=UTF-8"); String data="中国"; OutputStream out=response.getOutputStream(); out.write(data.getBytes("UTF-8")); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
如下demo字符流输出:浏览器显示??---------理由在下张图
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data="中国"; PrintWriter out=response.getWriter(); out.write(data); }
先把中国写入respone,因为respone是外国人发明的,查找的是iso8859这个码表,查找不到所以显示??
如下代码可以改变所查码表和浏览器所读取时查询码表:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setCharacterEncoding("UTF-8");//控制写入response时所查询的码表 // response.setHeader("content-type", "text/html;charset=UTF-8");//控制浏览器输出时时所查询的码表 response.setContentType("text/html;charset=UTF-8");//这句话可以代替上两句话 String data="中国"; PrintWriter out=response.getWriter(); out.write(data);//writer流只能写字符串! }
HttpServletResponse细节二-------》response实现(中文)文件下载
ResponseDemo3:
package cn.itcaste.web.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.stream.FileCacheImageInputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.taglibs.standard.tag.common.core.OutSupport; /** * 文件下载案例 */ @WebServlet("/ResponseDemo3") public class ResponseDemo3 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path=this.getServletContext().getRealPath("/download/1.jpg");//获取绝对路径 String filename=path.substring(path.lastIndexOf("\")+1);//获取文件名称 response.setHeader("content-disposition", "attachment;filename="+filename );//设置成按下载方式读取的响应头 InputStream in=null; OutputStream out=null; try { in=new FileInputStream(path); int len=0; byte buffer[]=new byte[1024]; out=response.getOutputStream(); while((len=in.read(buffer))>0){//读取到缓冲区的总字节数,如果没有更多的数据,因为文件的结尾已经到达,则为-1 out.write(buffer,0,len);//将该输入流中的len个字节数据读入一个字节数组 } } finally { if (in!=null) { try { in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
发布服务后浏览器显示:
下面我们来尝试中文:美女.jpg
demo
package cn.itcaste.web.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLDecoder; import java.net.URLEncoder; import javax.imageio.stream.FileCacheImageInputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.taglibs.standard.tag.common.core.OutSupport; /** * 文件下载案例 */ @WebServlet("/ResponseDemo3") public class ResponseDemo3 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //如果下载名是中文,要经过url编码 String path=this.getServletContext().getRealPath("/download/美女.jpg");//获取绝对路径 String filename=path.substring(path.lastIndexOf("/")+1);//获取文件名称 filename=URLEncoder.encode(filename, "UTF-8");//按理说这样就不会中文乱码,但是只有谷歌生效了,safari不行,我还在寻找办法 System.out.println(filename); System.out.println(URLDecoder.decode(filename, "UTF-8")); // response.setHeader("content-type", "charset=UTF-8");//控制浏览器输出时时所查询的码表 response.setHeader("content-disposition", "attachment;filename=" +filename ); //设置成按下载方式读取的响应头 InputStream in=null; OutputStream out=null; try { in=new FileInputStream(path); int len=0; byte buffer[]=new byte[1024]; out=response.getOutputStream(); while((len=in.read(buffer))>0){//读取到缓冲区的总字节数,如果没有更多的数据,因为文件的结尾已经到达,则为-1 out.write(buffer,0,len);//将该输入流中的len个字节数据读入一个字节数组 } } finally { if (in!=null) { try { in.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
浏览器显示:
HttpServletResponse细节三-------》response实现输出随机图片
先来看效果:------》目的在于防止恶意注册
demo:
package cn.itcaste.web.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ResponseDemo4 */ @WebServlet("/ResponseDemo4") public class ResponseDemo4 extends HttpServlet { public static final int WIDTH=120; public static final int HEIGHT=35; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //BufferedImage.TYPE_INT_RGB图像类型 BufferedImage image=new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);//在内存中构建出一幅图像 Graphics g=image.getGraphics();//得到图形!Graphics类是所有图形上下文的抽象基类,允许应用程序绘制在各种设备上实现的组件以及屏幕外图像。 //1.设置背景色 setBackGround(g); //2.设置边框 setBorder(g); //3.画干扰线 drawRandomLine(g); //4.画随机数 drawRandomNum((Graphics2D)g); //5.图形写给随机数 response.setContentType("image/jpeg"); //发头控制浏览器不要缓存 response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma ","no-cache" ); ImageIO.write(image, "jpg", response.getOutputStream()); } /** * @param g * 设置背景色 */ private void setBackGround(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); } /** * @param g * 设置边框 */ private void setBorder(Graphics g) { g.setColor(Color.RED); g.drawRect(0, 0, WIDTH-2, HEIGHT-2); } /** * @param g * 画干扰线 */ private void drawRandomLine(Graphics g) { g.setColor(Color.GREEN); for(int i=0;i<5;i++){ int x1=new Random().nextInt(WIDTH); int y1=new Random().nextInt(HEIGHT); int x2=new Random().nextInt(WIDTH); int y2=new Random().nextInt(HEIGHT); g.drawLine(x1, y1, x2, y2); } } /** * @param g * 画随机数 */ private void drawRandomNum(Graphics2D g) { g.setColor(Color.BLACK); String c1 = null; g.setFont(new Font("宋体", Font.BOLD, 18)); for(int i=0;i<4;i++){ int d=new Random().nextInt()%30; char c=(char) (0x4e00+(int)(Math.random()*(0x9fa5-0x4e00+1))); c1 = String.valueOf(c); g.rotate((d*3.14)/180,( WIDTH-(30*i)-30),(HEIGHT-20)); g.drawString(c1,( WIDTH-(30*i)-30), (HEIGHT-15)); g.rotate((-1*d*3.14)/180,( WIDTH-(30*i)-30),(HEIGHT-20)); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
点击图片换一张js:
HttpServletResponse细节二-------》response实现 refresh定时刷新页面以及特定情景
/** * Servlet implementation class ResponseDemo5 */ @WebServlet("/ResponseDemo5") public class ResponseDemo5 extends HttpServlet { //控制浏览器定时刷新 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //假设这是一个用于处理登录的servlet //假设程序运行到此,用户等录成功 //test1(response); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8 "); response.getWriter().write("登录成功,三秒后将跳转到首页,如果没有,请点击<a href='/day04/ResponseDemo4'>超链接</a>"); response.setHeader("refresh", "3;url='/day04/ResponseDemo4'");//每隔三秒拿一次数据 } private void test1(HttpServletResponse response) throws IOException { response.setHeader("refresh", "3");//每隔三秒拿一次数据 String data=new Random().nextInt(10000)+""; response.getWriter().write(data); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
浏览器先看到如下,不点击超链接则3秒后自动跳转,点击则立刻跳转:
HttpServletResponse细节三-------》控制浏览器要缓存
/** * 控制浏览器要缓存 */ @WebServlet("/ResponsDemo6") public class ResponseDemo6 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setDateHeader("expires", System.currentTimeMillis()+1000*3600);//设置缓存时间,当前时间加一秒乘3600=一天 String data="aaaaaaaaa"; response.getWriter().write(data); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
HttpServletResponse细节四-------》重定向
/** * 实现请求重定向 * 地址栏会发生变化:适用于登录跳转首页,购物 */ @WebServlet("/ResponseDemo7") public class ResponseDemo7 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setStatus(302); // response.setHeader("location", "/day04/1.jsp"); response.sendRedirect("/day04/1.jsp");//这句可以代替上面两句,重定向等于发送两次请求 } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
HttpServletResponse细节五-------》
response.getOutputStream();
response.getWriter();
不能同时调用