JavaWeb-request和response
web服务器接收到客户端的http请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse。
- 如果要获取客户端请求过来的参数:找HttpServletRequest
- 如果要给客户端响应一些信息:找HttpServletResponse
Response
向浏览器发送数据
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 setBufferSize(int 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);
设置状态码
void setStatus(int var1);
文件下载
Demo1
package com.th0r.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class Demo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取文件信息和文件名
String dir = "E:\\static\\img\\1.jpg";
String fileName = dir.substring(dir.lastIndexOf("\\")+1);
resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//将文件写入流
FileInputStream fis = new FileInputStream(dir);
ServletOutputStream os = resp.getOutputStream();
int len;
byte[] bys = new byte[1024];
while ((len=fis.read(bys)) != -1){
os.write(bys, 0, len);
}
//关闭流
fis.close();
os.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
metadata-complete="true">
<servlet>
<servlet-name>download</servlet-name>
<servlet-class>com.th0r.servlet.Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>download</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
</web-app>
访问 localhost:8080/test3_war/download
验证码生成
Demo2
package com.th0r.servlet;
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 Demo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("refresh", "5");
//创建图片
BufferedImage img = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setColor(Color.blue);
g.fillRect(0,0,40,20);
g.setColor(Color.gray);
g.setFont(new Font(null, Font.BOLD, 18));
g.drawString(getNum(), 0, 20);
//设置响应头 刷新不缓存
resp.setContentType("image/png");
resp.setDateHeader("expires", -1);
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("pragma", "no-cache");
ImageIO.write(img, "png", resp.getOutputStream());
}
//生成随机数
private String getNum(){
Random random1 = new Random();
Random random2 = new Random();
String num1 = random1.nextInt(9999)+"";
String num2 = random2.nextInt(9)+"";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4-num1.length(); i++) {
sb.append(num2);
}
num1 = num1 + sb.toString();
return num1;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
web.xml
<servlet>
<servlet-name>img</servlet-name>
<servlet-class>com.th0r.servlet.Demo2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>img</servlet-name>
<url-pattern>/img</url-pattern>
</servlet-mapping>
重定向
- 请求转发的时候,url不会产生变化
- 重定向时候,url地址栏会发生变化
package com.th0r.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 Demo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/test3_war/img");
/**
resp.setStatus(302);
resp.setHeader("Location", "/test3_war/img");
**/
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
Request
HttpServletRequest代表客户端的请求,用户通过Http协议访问服务器,HTTP请求中的所有信息会被封装到HttpServletRequest,通过这个HttpServletRequest的方法,获得客户端的所有信息。
登录
index.jsp
<%@page pageEncoding="UTF-8" %>
<html>
<body>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:
<input type="checkbox" name="hobbies" value="唱">唱
<input type="checkbox" name="hobbies" value="跳">跳
<input type="checkbox" name="hobbies" value="rap">rap
<input type="checkbox" name="hobbies" value="篮球">篮球
<br>
<input type="submit">
</form>
</body>
</html>
Demo4.java
package com.th0r.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 Demo4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobbies");
if(username.equals("root") && password.equals("123456")){
System.out.println(username + "hobbies: " + Arrays.toString(hobbies));
//请求转发
req.getRequestDispatcher("/success.jsp").forward(req, resp);
}
else {
resp.sendRedirect("/test3_war/index.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}