[TOC]
HttpServletResponse
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
简单分类
负责向浏览器发送数据的方法
ServletoutputStream getoutputStream() throws IOException;PrintWriter getWriter() throws IOException;(中文最好用这个)
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);void setContentLength(int var1);void setContentLengthLong(long var1);void setContentType(String var1);void setDateHeader(String name, long date);void addDateHeader(String name, long date);void setHeader(String name, String value);void addHeader(String name, String value);void setIntHeader(String name, int value);void addIntHeader(String name, int value);
常见应用
1.向浏览器输出消息
2.下载文件
1.要获取下载文件的路径
2.下载的文件名是啥?
3.设置想办法让浏览器能够支持下载我们需要的东西
4.获取下载文件的输入流
5.创建缓冲区
6.获取OutputStream对象
7.将FileOutputStream流写入到buffer缓冲区
8.使用OutputStream将缓冲区的数据输出到客户端
通过response.getOutputStream的方式下载文件,为文件设置文件名:
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型response.setContentType("multipart/form-data");//2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");
public class FileServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1.要获取下载文件的路径String realPath = "D:\\\\java_work\\\\javaweb-test\\\\response\\\\src\\\\main\\\\resources\\\\贝贝子.png";System.out.println("下载文件的路径"+realPath);// 2.下载的文件名是啥?String filename = realPath.substring(realPath.lastIndexOf("\\\\") + 1);//3.设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西(中文文件名需要使用:URLEncoder.encode(filename,"UTF-8"),否则可能乱码或出现编码问题)resp.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(filename,"UTF-8"));// 4.获取下校文件的输入流FileInputStream in = new FileInputStream(realPath);// 5.创建缓冲区int len=0;byte[] buffer = new byte[1024];// 6.获取Outputstream对象ServletOutputStream out = resp.getOutputStream();//7.将FiLeoutputstream流写入到buffer缓冲区,使用outputStream将缓冲区中的数擦输出到客户端!while((in.read(buffer))>0){out.write(buffer,0,len);}in.close();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}}
3、验证码功能
验证怎么来的?
- 前端实现
- 后端实现,需要用到Java的图片类,生成一个图片
package com.bbz.servlet;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.awt.*;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;public class ImageServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//如何让浏览器5秒自动刷新一次resp.setHeader("refresh","3");//在内存中创建一个图片BufferedImage bufferedImage = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);//得到图片Graphics2D g=(Graphics2D) bufferedImage.getGraphics();//设置图片背景颜色g.setColor(Color.yellow);g.fillRect(0,0,80,20);//给图片写数据g.setColor(Color.BLUE);g.setFont(new Font(null,1,20));g.drawString(makeNum(),0,20);//告诉浏览器,这个请求用图片的方式打开resp.setContentType("image/png");//网站存在缓存,不让浏览器缓存resp.setDateHeader("expires",-1);resp.setHeader("Cache-Control","no-cache");resp.setHeader("Pragma","no-cache");//把图片写给浏览器boolean write = ImageIO.write(bufferedImage,"png", resp.getOutputStream());}//生成随机数private String makeNum(){Random random=new Random();String num = random.nextInt(9999999) + "";StringBuffer sb = new StringBuffer();for(int i=0;i<7- num.length();i++){sb.append("0");} //保证验证码一定是7位数num = sb.toString() + num;return num;}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}}
4.重定向
一个web资源B收到客户端A请求后,通知客户端A访问另一个web资源C,该过程叫重定向。常见场景:用户登录;
public void sendRedirect(String location) throws IOException;
重定向:
public class RedirectServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/*重定向原理resp.setHeader("Location","/resp/img");resp.setStatus(302);*/resp.sendRedirect("/resp/img");//重定向}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}}
重定向与转发的异同点:
- 相同:页面都会跳转
- 请求转发的时候,URL不会产生变化 307
登录重定向的小demo:创建处理登录重定向的Servlet:
public class RequestTes extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//处理请求String username = req.getParameter("username");String password = req.getParameter("password");System.out.println(username+":"+password);//重定向的时候一定要注意路径问题resp.sendRedirect("/resp/success.jsp");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}}
在index.jsp中添加登录提交:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %><html><body><h2>Hello World!</h2><%-- 这里提交的路径,需要寻找到项目的路径 --%><%-- ${pageContext.request.contextPath}代表当前项目 --%><form action="${pageContext.request.contextPath}/request" method="get">用户名: <input type="text" name="username" /> <br/>密 码: <input type="password" name="password" /> <br/><input type="submit"></form></body></html>
注:在jsp中指定编码格式可以防止中文乱码。
HttpServletRequest
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,可以获取请求的信息
- getContextPath() 获取当前路径
- getHeader() 获取头信息
- getHttpServletMapping() 获取请求的路径
- getRequestURL() 获取请求的URL
获取前端传递的参数及请求转发:
request.getParameter(String s) //取单个值request.getParameterValues(String s) //取多个值
接受登录信息的servlet文件:
package com.bbz.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.Arrays;public class LoginServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 解决后台接受中文乱码问题req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");String username = req.getParameter("username");String password = req.getParameter("password");String[] hobbys = req.getParameterValues("hobbys");System.out.println(username);System.out.println(password);System.out.println(Arrays.toString(hobbys));// 重定向// resp.sendRedirect("/resuest-01/success.jsp");// 通过请求转发, 此处的 / 就是当前web应用,不需要在多写了。req.getRequestDispatcher("/success.jsp").forward(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}}
登录的jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Login</title></head><body><h1>登录</h1><div style="text-align: center"><%-- 这里表单表示的意思:以post方式提交表单,提交到我们的login请求 --%><form action="${pageContext.request.contextPath}/login" method="post">用户名:<input type="text" name="username"> <br/>密码:<input type="password" name="password"> <br/>爱好:<input type="checkbox" name="hobbys" value="女孩">女孩<input type="checkbox" name="hobbys" value="代码">代码<input type="checkbox" name="hobbys" value="唱歌">唱歌<input type="checkbox" name="hobbys" value="电影">电影<br/><input type="submit"></form></div></body></html>