Servlet------>response
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();
不能同时调用
Servlet------>response的更多相关文章
- JavaWeb基础:Servlet Response
ServletResponse简介 ServletResponse代表浏览器输出,它提供所有HttpResponse的设置接口,可以设置HttpResponse的响应状态,响应头和响应内容. 生命周期 ...
- Servlet(Response,Request)
1.response控制码表的3种方法:输出1; 2,文件下载 3.控制浏览器定时刷新网页(REFRESH) 4.控制浏览器缓存当前文档内容 5. 通过response实现请求重定向. 6.setHe ...
- servlet response 中文乱码
先,response返回有两种,一种是字节流outputstream,一种是字符流printwrite. 申明:这里为了方便起见,所有输出都统一用UTF-8编码. 先说字节流,要输出“中国" ...
- Servlet response原理
首先web服务器 接受到http请求后转交给相应的servlet进行处理这个过程可以他通过配置web.xml来进行确定,然后web服务器将相应的信息封装到request和response对象,由相应的 ...
- Servlet Response 重定向
重定向 response.sendRedirect("index.jsp"); //登录用户名不存在,重定向到index.jsp 1重定向在客户端发挥作用,通过浏览器重 ...
- java map转json servlet response
1.手写一个map转json的类 1.1 调用方式 //给前端放回json数据 Map<String, Object> map = new HashMap<>(); map.p ...
- Java EE之servlet实现用户登录
1.在连接数据库的JAVA类中添加查询功能: 在这之前有一个连接数据库的方法: Connection conn=null; PreparedStatement stat=null; ...
- Java EE之servlet处理表单提交的请求
1.在源包下新建一个Servlet页,取名为LoginServlet: package weinidingServlet; //该Servlet所 ...
- Java中前台JSP请求Servlet实例(http+Servlet)
1.前台jsp代码 himily.jsp,定义了用户名和密码两个输入框,使用post方式提交:/order-web/HimilyServlet其中order-web为站点名称,HimilyServle ...
- chain.doFilter(request,response)含义
过滤器的生命周期一般都要经过下面三个阶段: 初始化 当容器第一次加载该过滤器时,init() 方法将被调用.该类在这个方法中包含了一个指向 Filter Config 对象的引用.我们的过滤器实际上并 ...
随机推荐
- python内置函数之vars()
vars([object]) 返回__dict__属性的值.当不传入参数时,和locals()等效.当函数接收一个参数时,参数可以是模块.类.类实例,或者定义了__dict__属性的对象. >& ...
- haproxy+keepalived实现高可用负载均衡(转)
软件负载均衡一般通过两种方式来实现:基于操作系统的软负载实现和基于第三方应用的软负载实现.LVS就是基于Linux操作系统实现的一种软负载,HAProxy就是开源的并且基于第三应用实现的软负载. ...
- sama5d3 环境检测 gpio--yx测试
说明: yx0--pioA0 yx1--pioA2 yx2--pioA4 yx3--pioA10 yx4--pioA14 yx5--pioA16 yx6--pioA12 yx7--pioA20 ...
- js跨域问题(2)
前两天碰到一个跨域问题的处理,使用jsonp可以解决.(http://www.cnblogs.com/xtechnet/p/4123210.html) 最近再整理了一下: 非CORS 1.jsonp. ...
- HDOJ 4010 Query on The Trees LCT
LCT: 分割.合并子树,路径上全部点的点权添加一个值,查询路径上点权的最大值 Query on The Trees Time Limit: 10000/5000 MS (Java/Others) ...
- 深度剖析java编码,彻底解决java乱码问题_1
理解: 1,Java编译器(即编译成class文件时) 用的是unicode字符集. 2,乱码主要是由于不同的字符集相互转换导致的,理论上各个字符的编码规则是不同的,是不能相互转换的,所以根本解决乱码 ...
- git提交空文件夹目录结构
find . -name ".git" | xargs rm -Rf 在git 目录下执行find . -type d -empty -exec touch {}/.gitigno ...
- Easyui Datagrid相同连续列合并扩展(二)
JS: //合并相同数据的单元格 function MergeCells(seletor, rows, fields) { if(rows == null || rows.length == 0 || ...
- 我为什么喜欢Go语言123123
从2000年至今,也写了11年代码了,期间用过VB.Delphi.C#.C++.Ruby.Python,一直在寻找一门符合自己心意和理念的语言.我很在意写代码时的手感和执行的效率,所以在Go出现之前一 ...
- 我们把Mybatis的功能架构分为三层:
我们把Mybatis的功能架构分为三层: (1)API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库.接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理. (2) ...