文章目录
一、请求对象
1.1 请求对象介绍
- 请求:获取资源。在
BS
架构中,就是客户端浏览器向服务器端发出询问。 - 请求对象:就是在项目当中用于发送请求的对象。
1.2 请求对象常用方法-获取各种路径
package com.itjc.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("/servletDemo01")
public class ServletDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取虚拟目录名称 getContextPath();
String contextPath = req.getContextPath();
System.out.println(contextPath); ///request
// 2.获取 Servlet驶射路径 getServletPathO
String servletPath = req.getServletPath();
System.out.println(servletPath); ///servletDemo01
// 3.获取功问者 ip getRemoteAddr();
String remoteAddr = req.getRemoteAddr();
System.out.println(remoteAddr); //0:0:0:0:0:0:0:1
// 4.获取请求消息的数据 getQueryString();
String queryString = req.getQueryString();
System.out.println(queryString); //username=zs&password=123445
// 5.获取统一资源标识符 getRequestURI();
String reqRequestURI = req.getRequestURI();
System.out.println(reqRequestURI); // /request/servletDemo01
//6.获取统一资源定位符 getRequestURL();
StringBuffer requestURL = req.getRequestURL();
System.out.println(requestURL); // http://localhost:8989/request/servletDemo01
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
1.3 请求对象常用方法-获取请求头信息
package com.itjc.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("/servletDemo02")
public class ServletDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、根据请求头名称获取一个值
String connection = req.getHeader("connection");
System.out.println(connection);
System.out.println("---------------");
Enumeration<String> values = req.getHeaders("accept-encoding");
while (values.hasMoreElements()) {
String value = values.nextElement();
System.out.println(value);
}
System.out.println("---------------");
Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = headerNames.nextElement();
String value = req.getHeader(key);
System.out.println(key + ":" + value);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
结果:
keep-alive
---------------
gzip, deflate, br
---------------
host:localhost:8989
connection:keep-alive
cache-control:max-age=0
sec-ch-ua:"Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"
sec-ch-ua-mobile:?0
sec-ch-ua-platform:"Windows"
upgrade-insecure-requests:1
user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-site:none
sec-fetch-mode:navigate
sec-fetch-user:?1
sec-fetch-dest:document
accept-encoding:gzip, deflate, br
accept-language:zh-CN,zh;q=0.9
cookie:JSESSIONID=45DEFFFD715538E0F4418C28F581CB54; Idea-dabf7c28=3e7fed1c-ba39-4eb9-9736-10053c5fbaa1; NMTID=00O_Lsi5php5YeSCEPIq9ZxmJYTwocAAAF4Ul-LUA; Pycharm-7a4e33e8=eb24329e-0d3b-4bde-8757-edb5d72b4c78; _xsrf=2|8b21481f|1aa5c126bd4a2e4985b9d01cdc1210c3|1631281017; username-localhost-8889="2|1:0|10:1631584471|23:username-localhost-8889|44:YWM0NzQ5M2U2MWUxNDA2MWEwMjZkZmU2ODJmYzVhMjM=|d843065fc1dece379b30e411189c5735b73b142823b8d8b9df12d35e5d78d59b"; username-localhost-8888="2|1:0|10:1631672895|23:username-localhost-8888|44:ZDljNDkxYTY0ZTAxNGZlZGJmYmIzOWU4NTFiY2U4ZDk=|1aa9669ee7e920a89795be766023df2b2
1.4 请求对象常用方法-获取请求参数信息
package com.itjc.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;
import java.util.Map;
@WebServlet("/servletDemo03")
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、根据名称获取数据 getParameter()
String username = req.getParameter("username");
System.out.println(username);
String password = req.getParameter("password");
System.out.println(password);
System.out.println("--------------------");
//2、根据名称获取所有数据 getParameterValues()
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
System.out.println("--------------------");
//3、获取所有名称 getParameterNames()
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
System.out.println(name);
}
System.out.println("--------------------");
//4、获取所有参数键值对 getParameterMap()
Map<String, String[]> mp = req.getParameterMap();
for (String key : mp.keySet()) {
String[] values = mp.get(key);
System.out.print(key + ":");
for (String value : values) {
System.out.print(value + " ");
}
System.out.println();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<form action="/request/servletDemo09" method="get" autocomplete="off">
姓名:<input type="text" name="username"> <br>
密码:<input type="password" name="password"> <br>
爱好:<input type="checkbox" name="hobby" value="study">学习
<input type="checkbox" name="hobby" value="game">游戏 <br>
<button type="submit">注册</button>
</form>
zs
123456
--------------------
study
game
--------------------
username
password
hobby
--------------------
username:zs
password:123456
hobby:study game
1.5 获取请求参数并封装对象
- 手动封装方式。
package com.itjc.servlet;
import com.itjc.bean.Student;
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("/servletDemo04")
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、 获取所有数据
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
// 2、封装对象
Student st = new Student(username, password, hobbies);
// 3、输出对象
System.out.println(st); // Student{username='zs', password='123456', hobby=[study, game]}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
- 反射封装方式。
package com.itjc.servlet;
import com.itjc.bean.Student;
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.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
@WebServlet("/servletDemo05")
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取所有数据
Map<String, String[]> mp = req.getParameterMap();
//2、封装学生对象
Student st = new Student();
//2.1、遍历集合
for (String name : mp.keySet()) {
String[] value = mp.get(name);
try {
//2.2 获取student对象属性描述器
PropertyDescriptor pd = new PropertyDescriptor(name, st.getClass());
//2.3 获取对应的setXXX方法
Method writeMethod = pd.getWriteMethod();
//2.4 执行方法
if (value.length > 1) {
writeMethod.invoke(st, (Object) value);
} else {
writeMethod.invoke(st, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//3、输出对象
System.out.println(st);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
entries实现Map的遍历
for (Map.Entry<String, String[]> entry : mp.entrySet()) {
String name = entry.getKey();
String[] value = entry.getValue();
try {
//2.2 获取student对象属性描述器
PropertyDescriptor pd = new PropertyDescriptor(name, st.getClass());
//2.3 获取对应的setXXX方法
Method writeMethod = pd.getWriteMethod();
//2.4 执行方法
if (value.length > 1) {
writeMethod.invoke(st, (Object) value);
} else {
writeMethod.invoke(st, value);
}
} catch (Exception e) {
e.printStackTrace();
}
- 工具类封装方式
package com.itjc.servlet;
import com.itjc.bean.Student;
import org.apache.commons.beanutils.BeanUtils;
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.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
@WebServlet("/servletDemo06")
public class ServletDemo06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1、获取所有数据
Map<String, String[]> mp = req.getParameterMap();
//2、封装学生对象
Student st = new Student();
//3、用工具进行封装
try {
BeanUtils.populate(st, mp);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(st);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
遇到的问题:
解决办法:
1.6 流对象获取请求信息
package com.itjc.servlet;
import com.itjc.bean.Student;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
@WebServlet("/servletDemo07")
public class ServletDemo07 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//字符流(必须是post的提交方式)
// BufferedReader br = req.getReader();
// String line;
// while ((line = br.readLine()) != null) {
// System.out.println(line);
// }
//字节流(必须是post的提交方式) 可以传文件
ServletInputStream is = req.getInputStream();
byte[] arr = new byte[1024];
int len;
while ((len = is.read(arr)) != -1) {
System.out.println(new String(arr, 0, len));
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
中文乱码问题
- GET方式没有乱码问题。
在Tomcat8版本后已经解决 - POST方式有乱码问题。
可以通过setCharacterEncoding()
方法来解决!
package com.itjc.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
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("/servletDemo08")
public class ServletDemo08 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
1.7 请求域
-
请求域(
request
域):可以在一次请求范围内进行共亨数据。 -
一般用于请求转发的多个资源中共亨数据。
-
请求对象操作共享数据方法
1.8 请求转发
- 请求转发:客户端的一次请求到达后,发现需要借助其他
Servlet
来实现功能。
- 特点:
浏览器地址栏不变
域对象中的数据不丢失
负责转发的Servlet
转发前后的响应正文会丢失
由转发的目的地来响应客户端
servlet09
package com.itjc.servlet;
import javax.servlet.RequestDispatcher;
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("/servletDemo09")
public class ServletDemo09 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("code", "test");
RequestDispatcher rd = req.getRequestDispatcher("/servletDemo10");
rd.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
servlet10
package com.itjc.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("/servletDemo10")
public class ServletDemo10 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("This is Servlet10···");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
1.9 请求包含
- 请求包含:可以合并其他Servlet中的功能一起响应给客户端。
- 特点:
1.浏览器地址栏不变
2.域对象中的数据不丢失
3.被包含的Servlet响应头会丢失
servlet11
package com.itjc.servlet;
import javax.servlet.RequestDispatcher;
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("/servletDemo11")
public class ServletDemo11 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Demo11执行了···");
// 获取请求对象
RequestDispatcher rd = req.getRequestDispatcher("/servletDemo12");
// 实现包含功能
rd.include(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
servlet12
package com.itjc.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("/servletDemo12")
public class ServletDemo12 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Demo12执行了···");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
二、响应对象
2.1 响应对象介绍
- 响应:回馈结果。在BS架构中,就是服务器给客户端浏览器反馈结果。
- 响应对象:就是在项目中用于发送响应的对象。
2.2 常见状态码
2.3 字节流响应消息(万能流)
package com.itjc.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;
/*
字节流响应消息
*/
@WebServlet("/servletDemo01")
public class ServletDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 0、设置编码格式
resp.setContentType("text/html;charset=UTF-8");
// 1、 获取字节输出流对象
ServletOutputStream os = resp.getOutputStream();
// 2、定义一个消息
String str = "你好";
// 3、通过字节流对象输出
os.write(str.getBytes("UTF-8"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2.3 字符流响应消息
package com.itjc.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.io.PrintWriter;
@WebServlet("/servletDemo02")
public class ServletDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
// 1、获取字符输出流对象
PrintWriter pw = resp.getWriter();
// 2、准备一个消息
String str = "你好";
// 3、通过字符流输出
pw.write(str);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2.4 响应图片
- 创建字节输入流对象,关联读取的图片路径。
- 通过响应对象获取字节输出流对象。
- 循环读取和写出图片。
package com.itjc.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.*;
@WebServlet("/servletDemo03")
public class ServletDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 通过文件的相对路径 获取绝对路径
String realPath = getServletContext().getRealPath("/img/祖师爷.png");
System.out.println(realPath);
// 1、创建字节输入流对象 关联图片路径
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
// 2、通过响应对象获取字节输出流对象
ServletOutputStream os = resp.getOutputStream();
// 3、循环读写操作
byte[] arr = new byte[1024];
int len;
while ((len = bis.read(arr)) != -1) {
os.write(arr, 0, len);
}
// 4、释放资源
bis.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
遇到的问题:
解决方法:获取发布后的真实路径
String realPath = getServletContext().getRealPath("/img/祖师爷.png");
2.5 设置缓存
- 缓存: 对于不经常变化的数据,我们可以设置合理缓存时间,以避免浏览器频繁请求服务器。以此来提高效率!
package com.itjc.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.FileInputStream;
import java.io.IOException;
@WebServlet("/servletDemo04")
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、设置编码格式
resp.setContentType("text/html;charset=UTF-8");
// 2、设置缓存 1小时缓存时间
resp.setDateHeader("Expires", System.currentTimeMillis() + 1 * 60 * 60 * 1000);
String news = "这是一条很火爆的新闻!";
//写出数据
resp.getWriter().write(news);
System.out.println("abc");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.6 定时刷新
●定时刷新:过了指定时间后,页面自动进行跳转。
package com.itjc.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("/servletDemo05")
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
String str = "您的用户名或密码有误,3s后自动跳转到登录页面";
resp.getWriter().write(str);
//定时刷新
resp.setHeader("Refresh", "3;URL=/response/login.html");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.7 请求重定向
-
请求重定向:客户端的一次请求到达后,发现需要借助其他
Servlet
来实现功能。 -
特点:浏览器地址栏会发生改变,两次请求、请求域对象中不能共享数据,可以重定向到其他服务器。
-
重定向实现原理
设置响应状态码为302。resp.setStatus(302)
设置响应的资源路径(响应到哪里去,通过响应消息头location来指定)resp.setHeader( "location",' /response/responseDemo07");
-
响应对象重定向方法
servlet06
package com.itjc.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("/servletDemo06")
public class ServletDemo06 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Demo06执行了···");
//设置共享数据
req.setAttribute("username", "zhangsan");
//设置重定向
resp.sendRedirect(req.getContextPath() + "/servletDemo07");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
servlet07
package com.itjc.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("/servletDemo07")
public class ServletDemo07 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Demo07执行了···");
//获取共享数据
Object username = req.getAttribute("username");
System.out.println(username); //null
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
使用场景:如果需要共享数据则就是请求转发,否则就是请求重定向。
重定向请求域中的数据不能共享。
2.8 文件下载
- 创建字节输入流,关联读取的文件。
- 设置响应消息头支持的类型。
- 设置响应消息头以下载方式打开资源。
- 通过响应对象获取字节输出流对象。
- 循环读写。
- 释放资源。
package com.itjc.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.FileInputStream;
import java.io.IOException;
@WebServlet("/servletDemo08")
public class ServletDemo08 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 创建字节输入流,关联读取的文件。
String realPath = getServletContext().getRealPath("img/祖师爷.png");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
// 2. 设置响应消息头支持的类型。
/*
Content-Type 消息头名称 支持的类型
application/octet-stream 消息头参数 应用类型为字节流
*/
resp.setHeader("Content-Type", "application/octet-stream");
// 3. 设置响应消息头以下载方式打开资源。
/*
Content-Disposition 消息头名称 处理的形式
attachment;filename=祖师爷.png 消息头参数 附件形式进行处理 指定下载文件的名称
*/
resp.setHeader("Content-Disposition", "attachment;filename=祖师爷.png");
// 4. 通过响应对象获取字节输出流对象。
ServletOutputStream os = resp.getOutputStream();
// 5. 循环读写。
byte[] arr = new byte[1024];
int len;
while ((len = bis.read(arr)) != -1) {
os.write(arr, 0, len);
}
// 6. 释放资源。
bis.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
三、案例学生管理系统
3.1 案例效果
3.2 案例实现-资源准备
- 创建一个
web
项目。 - 在
web
目录下创建一个index.html
,包含两个超链接标签添加学生、查看学生。 - 在
web
目录下创建一个addStudent.html
,用于实现添加功能的表单页面。 - 在
src
下创建一个Student
类,用于封装学生信息。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生管理系统</title>
</head>
<body>
<a href="addStudent.html">添加学生</a>
<a href="/stu/queryStudentServlet">查看学生</a>
</body>
</html>
student
package com.itjc.bean;
public class Student {
private String name;
private String sex;
private String age;
private String id;
private String major;
public Student() {
}
public Student(String name, String sex, String age, String id, String major) {
this.name = name;
this.sex = sex;
this.age = age;
this.id = id;
this.major = major;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age='" + age + '\'' +
", id='" + id + '\'' +
", major='" + major + '\'' +
'}';
}
}
addStudentServlet
package com.itjc.servlet;
import com.itjc.bean.Student;
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.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
@WebServlet("/addStudentServlet")
public class addStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、 通过提交的表单获取数据
String name = req.getParameter("name");
String sex = req.getParameter("sex");
String age = req.getParameter("age");
String id = req.getParameter("id");
String major = req.getParameter("major");
// 2、手动封装对象
Student st = new Student(name, sex, age, id, major);
// 3、保存到文件中
BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\student.txt", true));
bw.write(name + " " + sex + " " + age + " " + id + " " + major);
bw.newLine();
bw.close();
// 4、响应给客户端 保存成功
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("Save Success!\n正在跳转到首页···");
resp.setHeader("Refresh", "3;URL=/stu/index.html");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
工具封装对象
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、 通过提交的表单获取数据
Map<String, String[]> map = req.getParameterMap();
// 2、工具封装对象
Student st = new Student();
try {
BeanUtils.populate(st, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 3、保存到文件中
BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\student.txt", true));
bw.write(st.getName() + " " + st.getSex() + " " + st.getAge() + " " + st.getId() + " " + st.getId());
bw.newLine();
bw.close();
// 4、响应给客户端 保存成功
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("Save Success!\n正在跳转到首页···");
resp.setHeader("Refresh", "3;URL=/stu/index.html");
}
queryStudentServlet
package com.itjc.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.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/queryStudentServlet")
public class queryStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\student.txt"));
ServletOutputStream os = resp.getOutputStream();
byte[] arr = new byte[1024];
int len;
while ((len = bis.read(arr)) != -1) {
os.write(arr, 0, len);
}
bis.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}