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 对象的引用.我们的过滤器实际上并 ...
随机推荐
- CGameMainScene类
#ifndef __GAMEMAIN_SCENE_H__ #define __GAMEMAIN_SCENE_H__ #include "cocos2d.h" #include &q ...
- CXAnimation.h动画类
/**************************************************************************** 使用一个CCAnimation对象可以CCS ...
- c语言中struct的内存对齐
为了让CPU能够更舒服地访问到变量,struct中的各成员变量的存储地址有一套对齐的机制.这个机制概括起来有两点:第一,每个成员变量的首地址,必须是它的类型的对齐值的整数倍,如果不满足,它与前一个成员 ...
- [转]__cdecl与__stdcall
来自Programming Windows 5th Edition The WinMain function is given a type of WINAPI (as is every Window ...
- 同一个String在使用不同的charset编码的时候equals仍然是返回true吗
1.对于ASCII字符,是的(只要该charset涵盖了ASCII编码),使用任何charset编码都不会影响equals的判断 2.对于非ASCII字符,不一定.例如同中文字符串"你好&q ...
- 读取SD卡中的图片
Touxiang=(ImageView)view.findViewById(R.id.Touxiang); //头像Bitmap bm = BitmapFactory.decodeFile(" ...
- FreeRTOS 定时器组
以下转载自安富莱电子: http://forum.armfly.com/forum.php 本章节为大家讲解 FreeRTOS 支持的定时器组,或者叫软件定时器,又或者叫用户定时器均可.软件定时器的功 ...
- FreeRTOS 系统时钟节拍和时间管理
以下转载自安富莱电子: http://forum.armfly.com/forum.php FreeRTOS 的时钟节拍任何操作系统都需要提供一个时钟节拍,以供系统处理诸如延时. 超时等与时间相关的事 ...
- FreeRtos——多任务
官方资料整理测试: 多任务和单任务几乎没有差别.只用多创建一个或多个任务,其他地方和单任务时相同. static void AppTaskCreate(void) { xTaskCreate(vTas ...
- Java Spring Boot: Unable to determine jdbc url from datasource
如果你和我一样从github或码云上下载了一个几年前别人写的demo代码,想用来做学习用.编译的时候遇到下面这样的错误,然后死命上网查各种方案,百试不灵.试尽了各种方案,就是还连接不上数据库.你可以试 ...