一、response
response的对象封装了服务器向客户端响应的数据和告诉客户端应该进行什么样的操作,利用response对象可以控制浏览器的缓存、显示、编码等行为。
对response对象的操作主要有:
1、控制浏览器行为
编码:response.setCharacterEncoding("UTF-8");
response.setHeader("content-type","text/html;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8");
缓存:response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
重定向:response.setHeader("location", "/day05/login.html");
response.sendRedirect("/day05/login.html");
浏览器发起两次请求,产生两个request和response对象,浏览器的地址栏会有变化
2、response的细节
* servlet的流由控制关闭,在没有必要的情况下不要在程序中关闭servlet的流,因为这样做有可能导致意想不到的错误。
* 在一个servlet中不要同时打开字节流和字符流
3、向浏览器输出数据
* 图片数据
public void doGet(HttpServletRequest request, HttpServletResponseresponse)
throwsServletException, IOException {
BufferedImage image = newBufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics graphics= image.getGraphics();
setBackGround(graphics);
setBorder(graphics);
drawRandomLine(graphics);
drawRandomNum((Graphics2D)graphics);
response.setDateHeader("Expires",-1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setContentType("image/jpeg");
ImageIO.write(image,"jpg", response.getOutputStream());
}
二、request
服务器封装浏览器请求的对象,利用此对象可以得到请求的主机、ip、参数等信息
1、防盗链
public void doGet(HttpServletRequest request, HttpServletResponseresponse)
throwsServletException, IOException {
BufferedImage image = newBufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics graphics= image.getGraphics();
setBackGround(graphics);
setBorder(graphics);
drawRandomLine(graphics);
drawRandomNum((Graphics2D)graphics);
response.setDateHeader("Expires",-1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setContentType("image/jpeg");
ImageIO.write(image,"jpg", response.getOutputStream());
}
2、请求转发
public void doGet(HttpServletRequest request, HttpServletResponseresponse)
throwsServletException, IOException {
//mvc
String data ="aaaa";
request.setAttribute("data",data);
request.setAttribute("data",data);
RequestDispatcherrd = request.getRequestDispatcher("/view.jsp");
rd.forward(request,response);
}
三、乱码问题
向浏览器写入中文:response.setContentType("text/html;charset=GB2312");
post方式乱码:request.setCharacterEncoding("UTF-8");
post/get方式:username2 = newString(username2.getBytes("iso8859-1"),"UTF-8");还可以在tomcat的配置文件中设置。