本文主要是介绍Servlet基础(续集2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
HttpServletResponse
web服务器接收到客户端的http的请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
简单分类:
负责向浏览器发送数据的方法:
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法:
响应的状态码:
下载文件:
- 向浏览器输出消息
- 下载文件
- 要获取下载文件的路径
- 下载的文件名是什么
- 设置想办法浏览器能够支持下载我们需要的文件
- 获取下载文件的输入流
- 创建缓冲区
- 获取OujtputStream对象
- 将FileOujtputStream流写入到buffer缓冲区
- 使用OujtputStream将缓冲区中的数据输出到客户端!
public class FileServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.要获取下载文件的路径String realPath = "E:\\java project\\untitled\\note.md";
// 2.下载的文件名是什么String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3.设置想办法浏览器能够支持(Content-Disposition)下载我们需要的文件,让中文文件名URLEncoder.encode编码,否则可能乱码resp.setHeader("Content-Disposition","attachment;filename"+ URLEncoder.encode(fileName, "UTF-8"));
// 下载文件FileInputStream in = new FileInputStream(realPath);
// 4.获取下载文件的输入流int len = 0;
// 5.创建缓冲区byte[] buffer = new byte[1024];
// 6.获取OujtputStream对象ServletOutputStream out = resp.getOutputStream();
// 7.将FileOujtputStream流写入到buffer缓冲区,使用OujtputStream将缓冲区中的数据输出到客户端!while((len=in.read(buffer))>0){out.write(buffer, 0, len);}in.close();out.close();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}
验证码功能 :
验证怎么来的?
- 前端实现
- 后端实现,需要用到java图片类,生成一个图片
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","5");//在内存中创建一个图片BufferedImage image = new BufferedImage(80, 20,BufferedImage.TYPE_3BYTE_BGR);//得到图片Graphics2D g = (Graphics2D) image.getGraphics();//笔//设置图片的背景颜色g.setColor(Color.white);g.fillRect(0, 0,80, 20);//给图片写数据g.setColor(Color.BLUE);g.setFont(new Font(null,Font.BOLD,20));g.drawString(makeNum(),0,20);//告诉浏览器,这个请求用图片的方式打开resp.setContentType("image/jepg");//网站存在缓存,不让浏览器缓存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(9999999)+"";StringBuffer sb = new StringBuffer();for (int i = 0; i < 7-num.length(); i++) {sb.append("0");}num = sb.toString()+num;return num;}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
实现重定向:
B一个web资源收到客户端A请求后,B会通知A客户端去访问另一个web资源C,这个过程叫重定向
常见场景:
- 用户登录
package com.kuang.servlet;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class RedirectServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setHeader("Location", "/r/img");
// resp.setStatus(302);resp.sendRedirect("/r/img");//重定向}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
重定向与转发的区别:
相同点:页面都会实现跳转
不同点:
- 请求转发的时候,url不会发生变化 307
- 重定向的时候,url地址会发生变化 302
package com.kuang.servlet;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class RequestTest 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);//重定向的时候一定要注意路径问题,否则会404resp.sendRedirect("./success.jsp");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
<html>
<body>
<h2>Hello World!</h2><%--这里提交的路径,需要寻找项目的路径--%>
<%--${pageContext.request.contextPath}代表当前项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">用户名:<input type="text" name="username"><br>密码:<input type="password" name="password"><br><input type="submit">
</form></body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<h1>success</h1>
</body>
</html>
HttpServletReques
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
获取前端传递的参数
请求转发
package com.kuang.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 {String username = req.getParameter("username");String password = req.getParameter("password");String[] hobbys = req.getParameterValues("hobbys");System.out.println(username+":"+password+ Arrays.toString(hobbys));//resp.sendRedirect("./success");//通过请求转发req.getRequestDispatcher(req.getContextPath()+"/success.jsp").forward(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>登录</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>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<H1>SUCCESS</H1>
</body>
</html>
这篇关于Servlet基础(续集2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!