HttpServletResponse
1、简介
web服务器接收到客户端的http请求请求,会针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的HttpServletResponse对象
- 如果要获取客户端的请求参数:找HttpServletRequest
- 如果要给客户端一些相响应的信息:找HttpServletResponse
2、成员简单分类
-
负责向浏览器发送数据的方法
文件流:
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 var1, long var2); void addDateHeader(String var1, long var2); void setHeader(String var1, String var2); void addHeader(String var1, String var2); void setIntHeader(String var1, int var2); void addIntHeader(String var1, int var2);
-
响应的状态码
int SC_OK = 200;//状态ok int SC_NOT_FOUND = 404;//页面找不到 int SC_INTERNAL_SERVER_ERROR = 500;//服务器端错误 int SC_BAD_GATEWAY = 502;//网关出错
3、常见应用
-
向浏览器输出一些信息
-
下载文件
-
要获取下载的路径
-
下载的文件名是什么
-
设置浏览器能够支持下载我们需要的东西
-
获取下载文件的输入流
-
创建缓冲区(buffer)
-
获取OutPutStream对象
-
将FileOutPutStream流写入缓冲区(buffer)
-
使用OutPutStream将缓冲区的数据输出到客户端
代码实现
public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1、要获取下载的路径 String realPath = "D:\\Intellij IDEA_workspace\\webapp\\response\\src\\main\\resources\\image.jpg"; 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 fileInputStream = new FileInputStream(realPath); //5、创建缓冲区(buffer) int len = 0; byte[] buffer = new byte[1024]; //6、获取OutPutStream对象 ServletOutputStream out = resp.getOutputStream(); //7、将fileInputStream流写入缓冲区(buffer),使用OutPutStream将缓冲区的数据输出到客户端 while((len = fileInputStream.read(buffer))!=0){ out.write(buffer,0,len); } fileInputStream.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
-
验证码功能
-
验证码怎么来的
-
前端实现(JS)
-
后端实现(需要用到Java的图片类,产生一个图片响应到前端)
java实现代码
public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //让浏览器3秒刷新一次 resp.setHeader("refresh","3"); //在内存中创建一个图片 BufferedImage image = new BufferedImage(100,40,BufferedImage.TYPE_INT_RGB); //得到图片 Graphics2D g = (Graphics2D)image.getGraphics(); //设置图片的背景颜色 g.setColor(Color.white); g.fillRect(0,0,100,40); //给图片写数据 g.setColor(Color.RED); g.setFont(new Font(null,Font.BOLD,30)); g.drawString(makeNum(),0,30); //告诉浏览器这个请求用图片的方式打开 resp.setContentType("image/jpeg"); //网站存在缓存,不让浏览器缓存 resp.setDateHeader("expires",-1); //resp.setHeader("Cache-Control","no-cache");不让浏览器缓存的拓展方法 //resp.setHeader("Pragma","no-cache");不让浏览器缓存的拓展方法 //把图片写给浏览器 ImageIO.write(image,"jpg",resp.getOutputStream()); } //生成随机数 private String makeNum(){ Random random = new Random(); String num = random.nextInt(999999)+""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < 6-num.length(); i++) { sb.append("0"); } num = sb.toString()+num; return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
-
-
实现重定向
-
定义
一个web资源收到客户端请求后,他会通知客户端去访问另外一个web资源,这个过程就叫做重定向
-
常见场景
- 用户登录
-
测试
public class RedirectServlet extends HttpServlet { /** * 重定向 * */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* 拆分 resp.setHeader("Location","/s4/img");路径 resp.setStatus(302);状态码 */ resp.sendRedirect("/s4/img"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
-
重定向与转发的区别
-
相同点
页面都会实现跳转
-
不同点
请求转发时url地址栏不会产生变化,重定向时url地址栏会发生变化
-
-
登录测试
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <%--这里的路径需要寻找到项目的路径--%> <%--${pageContext.request.contextPath}代表当前的项目--%> <%--${pageContext.request.contextPath}/login把请求发送到RequestTest进行处理--%> <form action="${pageContext.request.contextPath}/login" method="get"> 用户:<input type="text" name="username"></br> 密码:<input type="password" name="password"></br> <input type="submit" name="submit"> </form> </body> </html>
java
public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //处理请求 String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+":"+password); //重定向一定要注意路径问题否则就会404 resp.sendRedirect("/s4/successfully.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
successfully.jsp(重定向页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>success</title> </head> <body> <h2 style="color: aquamarine">successfully</h2> </body> </html>
xml
<servlet> <servlet-name>requesttest</servlet-name> <servlet-class>com.zhang.servlet.RequestTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>requesttest</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
-