响应对象: ServletResponse 与 HttpServletResponse
HttpServletResponse继承于ServletResponse
响应:服务器给客户端作出回应
响应对象是由tomcat服务器创建的 内置对象 只管使用
响应包括:响应行 响应头 响应体
运行项目,然后按f12
就是定义网络数据传输的一种规范,必须遵循这种规范才能进行有效的交流
超文本传输协议(Hyper Text Transfer Protocol,HTTP
是一个简单的请求-响应协议,它通常运行在TCP之上
A. http 超文本协议 主要用于来传输文本 也可以传输文件以及音频 视频
B. http 是一个一次性性 请求与响应完事之后 连接就断开了
C. http是一个无状态连接的协议 不能记录每一次连接的记录 相对于比较安全
D. http协议传输数据是不安全的
A.http 0.9 只能用于传输普通内容 局限性比较大
B.http 1.0 是一个一次性协议 是请求与响应的协议 请求与响应完事之后 连接就断开
C.http 1.1 常连接的协议 需要设置 keep_alive存活的时间 在这个时间段中可以进行多次请求与响应
A.https协议=http协议+ssl证书
B.ssl证书主要用于保证数据传输的安全性
1xx :服务器接收到请求,继续执行操作 (断点续传)
2xx:响应成功
3xx:重定向
4xx:请求资源不存在
产生原因:
请求的资源不存在或者请求的路径不正确,访问servlet已经页面的路径不对
项目是否部署成功了 请求的资源是否在out文件夹下是否存在
直接访问web-inf下资源 也会产生404错误
5xx:运行在服务器的java代码出现错误
查找错误方法:
A.查看控制台
B.查看页面的错误
C.断点调试 局部测试 dao =servie =servlet
- try {
- System.out.println(1/0);
- } catch (Exception e) {
- resp.setStatus(500,"代码发生了异常");
- e.printStackTrace();
- }
需求:使用浏览器直接打开服务器图片
分析:
代码:
- package com.qf.servlet;
-
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- @WebServlet(name = "servlet01",urlPatterns = "/servlet01")
- public class Servlet01 extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //通过响应对象设置页面打开文件类型方式
- //resp.setHeader("Content-Tyep","image/png");
- resp.setContentType("image/png");
- //通过请求对象获取输入流
- InputStream is = req.getServletContext().getResourceAsStream("/WEB-INF/upload/bg.png");
- //通过响应对象获取输出流
- ServletOutputStream os = resp.getOutputStream();
- //实例化高效输入流
- BufferedInputStream bis = new BufferedInputStream(is);
- //实例化高效输出流
- BufferedOutputStream bos = new BufferedOutputStream(os);
- //读取
- int leng=-1;
- while ((leng=bis.read())!=-1){
- //写入
- bos.write(leng);
- }
- //关闭资源
- bos.close();
- bis.close();
- os.close();
- is.close();
- }
- }
需求:下载服务器上的图片
分析:
代码:
- package com.qf.servlet;
-
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.io.InputStream;
-
- @WebServlet(name = "servlet02",urlPatterns = "/servlet02")
- public class Servlet02 extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //通过请求对象获取服务器上的文件
- String filename = req.getParameter("filename");
- //通过响应对象设置响应头告诉浏览器下载方式
- resp.setHeader("Content-Disposition","attachment;fileName"+filename);
- //通过请求对象获取输入流
- InputStream is = req.getServletContext().getResourceAsStream("/WEB-INF/upload/bg.png");
- //通过响应对象获取输出流
- ServletOutputStream os = resp.getOutputStream();
- byte [] b = new byte[1024];
- int leng =-1;
- while ((leng=is.read(b))!=-1){
- os.write(b,0,leng);
- }
- os.close();
- is.close();
- }
- }
注意点:
A.addHeader() 同时设置多个相同键的时候 都会设置成功
B.setHeader("","")同时设置多个相同键的时候 会覆盖
需求: 两秒后自动跳转页面
- package com.qf.servlet;
- 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 java.io.IOException;
- @WebServlet(name = "demo01Servlet",urlPatterns = "/demo01Servlet")
- public class Demo01Servlet extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- //设置响应头
- // resp.setHeader("admin","123");
- // resp.setHeader("admin","12");
- // resp.addHeader("ad","12345");
- // resp.addHeader("ad","1234");
- resp.setHeader("refresh","2;login.jsp");
- }
- }
这两个方法只能存在一个 不能两个同时存在
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- // ServletOutputStream os = resp.getOutputStream();
- // os.write(97);
- // os.write("阿超".getBytes());
- // //设置响应的编码格式
- // resp.setContentType("text/html;charset=utf-8");
- // PrintWriter pw = resp.getWriter();
- // pw.write("哈哈哈!今天星期五");
- // pw.flush();
- // pw.close();
请求对象有 ServletRequest 和 HttpServletRequest
请求对象HttpServletRequest 是ServletRequest 的子类
HttpServletRequest 是由tomcat容器创建 只管使用
请求组成:请求行 请求头 请求体
测试:
- package com.qf.servlet;
-
- 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 java.io.IOException;
- @WebServlet(name = "servlet03",urlPatterns = "/servlet03")
- public class Servlet03 extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //获取上下文
- System.out.println(req.getServletContext());
- //获取请求的路径 servlet的路径
- System.out.println(req.getServletPath());
- //获取请求的项目打包的名称
- System.out.println(req.getContextPath());
- //获取请求提交的方法
- System.out.println(req.getMethod());
- //获取请求的参数 就是在URL地址上拼接的参数
- System.out.println(req.getQueryString());
- //获取请求的路径 项目打包名称加上servlet的名称
- System.out.println(req.getRequestURI());
- //获取请求的端口号
- System.out.println(req.getLocalPort());
- //获取请求的主机名
- System.out.println(req.getLocalName());
- //获取协议以及版本号
- System.out.println(req.getProtocol());
- //获取协议
- System.out.println(req.getScheme());
- //获取服务器地址 主机id
- System.out.println(req.getServerName());
- //获取服务器端口号
- System.out.println(req.getServerPort());
-
- }
- }
- package com.qf.servlet;
-
- 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 java.io.IOException;
- import java.util.Enumeration;
-
- @WebServlet(name = "servlet04",urlPatterns = "/servlet04")
- public class Servlet04 extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //获取单个请求头
- System.out.println(req.getHeader("Host"));
- //获取全部请求头 返回的类型与迭代器相像
- Enumeration
headerNames = req.getHeaderNames(); - while (headerNames.hasMoreElements()){
- //获取元素
- String s = headerNames.nextElement();
- System.out.println(s+"\t"+req.getHeader(s));
- }
- }
- }
前端:
- <%--
- Created by IntelliJ IDEA.
- User: 86182
- Date: 2022/9/2
- Time: 10:42
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>$Title$title>
- head>
- <body>
- <a href="servlet02?filename=bg.png">下载a>
- <form action="servlet05" method="post">
- <p>
- 文本:<input type="text" name="tex">
- p>
- <p>
- <input type="password" name="pwd">
- p>
- <p>
- <input type="radio" name="sex" value="男"> 男
- <input type="radio" name="sex" value="女"> 女
- p>
- <p>
- <input type="checkbox" name="hobby" value="打篮球"> 打篮球
- <input type="checkbox" name="hobby" value="跳舞"> 跳舞
- <input type="checkbox" name="hobby" value="唱歌"> 唱歌
- <input type="checkbox" name="hobby" value="rap"> rap
- p>
- <p>
- <input type="submit" value="提交">
- p>
- form>
- body>
- html>
后端:
- package com.qf.servlet;
-
- 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 java.io.IOException;
- import java.util.Enumeration;
-
- @WebServlet(name = "servlet05",urlPatterns ="/servlet05")
- public class Servlet05 extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setCharacterEncoding("utf-8");
- //获取单个name 值
- String tex = req.getParameter("tex");
- System.out.println(tex);
- System.out.println("==========");
- //获取全部name 值
- Enumeration
names = req.getParameterNames(); - //循环遍历
- while (names.hasMoreElements()){
- //获取name值
- String s = names.nextElement();
- //通过name值获取value值
- System.out.println(s+"\t"+req.getParameter(s));
- }
- System.out.println("==========");
- //根据单选框的name值 获取选中的value值
- String[] sexes = req.getParameterValues("sex");
- if (sexes!=null&&sexes.length>0){
- for (String s:sexes){
- System.out.println(s);
- }
- }
- System.out.println("==========");
- //根据复选框name值获取选中的value值
- String[] hobbies = req.getParameterValues("hobby");
- if (hobbies!=null&&hobbies.length>0){
- for (String s:hobbies){
- System.out.println(s);
- }
- }
-
-
- }
- }
需求:文件上传
分析:
代码:
前端:
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Titletitle>
- head>
- <body>
- <form action="servlet06" method="post" enctype="multipart/form-data">
- <p>
- 用户:<input type="text" name="uname">
- p>
- <p>
- 密码:<input type="password" name="upwd">
- p>
- <p>
- 文件上传:<input type="file" name="fileup">
- p>
- <p>
- <input type="submit" value="提交">
- p>
- form>
- body>
- html>
后端:
先导入文件上传的jar包
- package com.qf.servlet;
-
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
-
- 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 java.io.File;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.List;
- import java.util.UUID;
-
- @WebServlet(name = "servlet06",urlPatterns = "/servlet06")
- public class Servlet06 extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //通过请求对象获取保存在服务器上的文件夹路径
- String path = req.getServletContext().getRealPath("/WEB-INF/upload/");
- //将文件夹路径实例化为文件对象
- File file = new File(path);
- //如果文件夹不存在 则创建文件夹
- if (!file.exists()){
- file.mkdirs();
- }
- //判断前端表单的提交方式是否是一文件的形式提交
- boolean flag = ServletFileUpload.isMultipartContent(req);
- //判断 如果是true 则是以文件形式提交
- if (flag){
- //实例化DiskFileItemFactory对象 也就是工厂对象
- DiskFileItemFactory factory = new DiskFileItemFactory();
- //通过工厂对象获取文件上传的核心对象
- ServletFileUpload fileUpload = new ServletFileUpload(factory);
- //获取所有的input标签
- List
list = null; - try {
- list = fileUpload.parseRequest(req);
- } catch (FileUploadException e) {
- e.printStackTrace();
- }
- //将集合转换为迭代器
- Iterator
iterator = list.iterator(); - //遍历迭代器
- while (iterator.hasNext()){
- //获取input标签
- FileItem fileItem = iterator.next();
- //判断input标签的值是普通文本还是文件
- if(fileItem.isFormField()){
- //这是input标签的值是普通文本的操作
- //获取input标签的name值
- String fieldName = fileItem.getFieldName();
- //判断这个name值是哪个标签的值
- if (fieldName.equals("uname")){
- System.out.println(fileItem.getString("utf-8"));
- }else if (fieldName.equals("upwd")){
- System.out.println(fileItem.getString("utf-8"));
- }
- }else {
- //这是input标签的值是文件时的操作
- //也就是文件上传的操作
- //获取文件的名称
- String name = fileItem.getName();
- //判断文件是否是图片 因为这里上传的是图片
- if (!(name.endsWith("jpg")||name.endsWith("jpeg")||name.endsWith("png")||name.endsWith("gif"))){
- System.out.println("该文件不是图片");
- //结束方法
- return;
- }
- //文件是图片时
- //随机生成一个图片名称 防止有重名被覆盖并平均文件名称
- String fileItemName = (UUID.randomUUID()+"").replaceAll("_","")+name;
- //将图片构建为File对象
- File f = new File(path,fileItemName);
- //将图片文件对象写入到服务器
- try {
- fileItem.write(f);
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
- }
- }else {
- System.out.println("提交的类型有误");
- }
- }
- }
ServletConfig是由tomcat容器创建的 用于来获取servlet配置信息
测试:
- package com.qf.servlet;
-
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebInitParam;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.util.Enumeration;
-
- @WebServlet(name = "servlet07",urlPatterns = "/servlet07",
- initParams = {@WebInitParam(name = "name",value = "banzhang")
- ,@WebInitParam(name = "encoding",value = "utf-8")})
- public class Servlet07 extends HttpServlet {
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //获取ServletConfig对象
- ServletConfig servletConfig = this.getServletConfig();
- //获取单个键值
- String name = servletConfig.getInitParameter("name");
- System.out.println(name);
- //获取全部键值
- Enumeration
initParameterNames = servletConfig.getInitParameterNames(); - //遍历
- while (initParameterNames.hasMoreElements()){
- String s = initParameterNames.nextElement();
- //根据键获取值
- System.out.println(s+"\t"+servletConfig.getInitParameter(s));
- }
- }
- }