Servlet(3)

HttpServletRequest

该类的对象封装了所以客户端提交过来的数据

获取所有请求头数据

public java.util.Enumeration<E> getHeaderNames()
返回此请求包含的所有头名称的枚举。如果该请求没有头,则此方法返回一个空枚举。

实例

	Enumeration<String> heards = request.getHeaderNames();
while (heards.hasMoreElements()) {
String heard = (String) heards.nextElement();
String value = request.getHeader(heard);
System.out.println(heard + "=" + value);
}

输出

accept=image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*
referer=http://localhost:8080/HttpservletrequestDemo/login.html
accept-language=zh-CN
ua-cpu=AMD64
accept-encoding=gzip, deflate
user-agent=Mozilla/5.0 (Windows NT 6.2; Win64; x64; Trident/7.0; rv:11.0) like Gecko
host=localhost:8080
connection=Keep-Alive

获取客户端提交过来的数据

1.通过对应name得到值

String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + "==" +password);

2.通过request.getParameterMap()得到一个所有数据的map集合,再从中提取数据

		Map<String, String[]> map = request.getParameterMap();
Set<String> keySet = map.keySet();
System.out.println(keySet.size());
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String key = (String) it.next();
String[] values = map.get(key);
System.out.println(key);
for(int i =0;i<values.length;i++) {
System.out.println(key + "=" + values[i]);
} }

请求中中文乱码问题

即由客户端(浏览器)提交给服务器端的数据,如果带有中文则会出现乱码问题。可通过以下方法解决

对于get请求

1.代码转码

get请求过来的数据,会拼接到url地址栏,所以在url地址栏上就已经经过编码了,所以我们取到的就是乱码,tomcat收到了这批数据。而getParameter 默认使用ISO-8859-1去解码。

解决方法:先让文字回到ISO-8859-1对应的字节数组 , 然后再按utf-8组拼字符串

String username = request.getParameter("username");
String password = request.getParameter("password");
username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
System.out.println("userName="+username+"==password="+password);
2.直接在tomcat里面做配置,以后get请求过来的数据永远都是用UTF-8编码。

可以在tomcat里面做设置处理 conf/server.xml 加上URIEncoding=“utf-8”

对于post请求

对于post请求来说,该请求的所有数据都在 请求体中,所以直接设置请求体中的文字编码。

request.setCharacterEncoding("utf-8");

这行设置一定要写在getParameter之前。

HttpServletResponse

负责返回数据给客户端

输出数据到页面
	//以字符流的方式写数据
//response.getWriter().write("<h1>hello response...</h1>"); //以字节流的方式写数据
response.getOutputStream().write("hello response2222...".getBytes());

解决数据中的中文乱码问题

以字符流输出

解决方式:

response.getWriter()

	//1. 指定输出到客户端的时候,这些文字使用UTF-8编码
response.setCharacterEncoding("UTF-8"); response.getWriter().write("人间不值得...");
	//2. 直接规定浏览器看这份数据的时候,使用什么编码来看。
response.setHeader("Content-Type", "text/html; charset=UTF-8"); response.getWriter().write("人间不值得...");

以字节流输出

response.getOutputStream()

  1. 指定浏览器看这份数据使用的码表
response.setHeader("Content-Type", "text/html;charset=UTF-8");
  1. 指定输出的中文用的码表,也可以不指定因为String的getBytes()方法的默认编码格式为utf-8
response.getOutputStream().write("人间不值得..".getBytes("UTF-8"));
不管是字节流还是字符流,直接使用一行代码就可以了。
response.setContentType("text/html;charset=UTF-8");

然后在后面进行写入数据即可。

实现简单的资源下载

1.先写一个简单的index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
让tomcat的默认servlet提供下载:<br>
<a href="download/aa.jpg" >aa.jpg</a><br>
<a href="download/bb.txt" >bb.txt</a><br>
<a href="download/cc.rar" >cc.rar</a><br> 手动下载:<br>
<a href="t1?filename=aa.jpg" >aa.jpg</a><br>
<a href="t1?filename=bb.txt" >bb.txt</a><br>
<a href="t1?filename=cc.rar" >cc.rar</a><br>
</body>
</html>

2.然后再写一个servlet实现浏览器下载

import java.io.IOException;
import java.io.InputStream; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class t1
*/
public class t1 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过request.getParameter("filename")得到要下载文件名称
String filename = request.getParameter("filename");
System.out.println(filename);
//设置头信息,实现在浏览器下载文件
response.setHeader("Content-Disposition", "attachment; filename="+filename);
//getServletContext().getResourceAsStream("download/"+filename)得到文件的流对象
InputStream is = getServletContext().getResourceAsStream("download/"+filename);
ServletOutputStream os = response.getOutputStream();
int len=0;
byte[] b = new byte[1024];
//实现数据的写入
while((len=is.read(b))!=-1) {
os.write(b,0,len);
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

实现中文名称文件下载

针对浏览器类型,对文件名字做编码处理 Firefox (Base64) , IE、Chrome … 使用的是URLEncoder

1.html页面编写,和上面区别不大

<body>
让tomcat的默认servlet提供下载:<br>
<a href="download/aa.jpg" >aa.jpg</a><br>
<a href="download/bb.txt" >bb.txt</a><br>
<a href="download/cc.rar" >cc.rar</a><br> 手动下载:<br>
<a href="t1?filename=aa.jpg" >aa.jpg</a><br>
<a href="t1?filename=bb.txt" >bb.txt</a><br>
<a href="t1?filename=cc.rar" >cc.rar</a><br>
<a href="t1?filename=图片.png" >黑马.png</a><br>
</body>

2.servlet代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("filename");
String filename = new String(name.getBytes("ISO-8859-1"),"utf-8");
System.out.println(filename);
//这一步获取流对象提到编码之前,因为想要下载中文名称文件,那么在设置请求头时文件名必须要针对浏览器类型,对文件名字做编码处理。而在处理后文件名就不能找到对应文件
InputStream is = getServletContext().getResourceAsStream("download/"+filename);
//对浏览器类型,对文件名字做编码处理,此处为针对chrome做的处理。
filename = URLEncoder.encode(filename,"UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+filename);
ServletOutputStream os = response.getOutputStream();
int len=0;
byte[] b = new byte[1024];
while((len=is.read(b))!=-1) {
os.write(b,0,len);
}
}

请求转发和重定向

之前的写法

			response.setStatus(302);
response.setHeader("Location", "login_success.html");

重定向

//重定向写法: 重新定位方向 参数即跳转的位置
response.sendRedirect("login_success.html");
  1. 地址上显示的是最后的那个资源的路径地址

  2. 请求次数最少有两次, 服务器在第一次请求后,会返回302 以及一个地址, 浏览器在根据这个地址,执行第二次访问。

  3. 可以跳转到任意路径。 不是自己的工程也可以跳。

  4. 效率稍微低一点, 执行两次请求。

  5. 后续的请求,没法使用上一次的request存储的数据,或者 没法使用上一次的request对象,因为这是两次不同的请求。

请求转发

//请求转发的写法: 参数即跳转的位置
request.getRequestDispatcher("login_success.html").forward(request, response);
  1. 地址上显示的是请求servlet的地址。 返回200 ok

  2. 请求次数只有一次, 因为是服务器内部帮客户端执行了后续的工作。

  3. 只能跳转自己项目的资源路径 。

  4. 效率上稍微高一点,因为只执行一次请求。

  5. 可以使用上一次的request对象。

最新文章

  1. 为什么operator&gt;&gt;(istream&amp;, string&amp;)能够安全地读入长度未知的字符串?
  2. Android开发--adb,SQLite数据库运用
  3. python--自动删除文件
  4. vim 空格 制表符
  5. python socket发送魔法包网络唤醒开机.py
  6. 循环日期的shell
  7. oracle 常用视图和表
  8. FastDFS安装配置
  9. Amoeba相关产品及其介绍
  10. SSM框架+Plupload实现断点续传(Spring+SpringMVC+MyBatis+Plupload)
  11. MOSS母板页制作 学习笔记(一)
  12. 发布WebService到IIS和调用WebService
  13. cf581B Luxurious Houses
  14. HDU5141--LIS again (LIS变形)
  15. Android开发:shape和selector和layer-list的(详细说明)
  16. Java并发编程总结4——ConcurrentHashMap在jdk1.8中的改进(转)
  17. [刷题]算法竞赛入门经典(第2版) 5-15/UVa12333 - Revenge of Fibonacci
  18. plsql和tsql常用函数比较
  19. TP5.0 Redis(单例模式)(原)
  20. 安装rcssmin方法

热门文章

  1. 使用matplotlib.pyplot中plot()绘制折线图
  2. 在Asp.Net或.Net Core中配置使用MarkDown富文本编辑器有开源模板代码(代码是.net core3.0版本)
  3. css盒子布局,浮动布局以及显影与简单的动画
  4. 【C#】学习笔记 Linq相关
  5. 对于写Java的博文
  6. Java-环境搭建(Mac版)
  7. windows下同时安装多个python版本的方法
  8. .deb 包如何安装到指定目录; Ubuntu; Debian like;
  9. Scrapy的下载中间件
  10. Python自动化报错:IndentationError-unindent does not match any outer indentation level