目录
- web.xml
- index.jsp
- RequestTest
- login测试
- FileServlet
- 文件下载测试
- 动态图形验证码Servlet
- 动态图形验证码测试
- 总结
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="4.0"
metadata-complete="true">
<!--注册Servlet-->
<servlet>
<servlet-name>file</servlet-name>
<servlet-class>com.zty.servlet.FileServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>file</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>image</servlet-name>
<servlet-class>com.zty.servlet.ImageServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/img</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RedirectServlet</servlet-name>
<servlet-class>com.zty.servlet.RedirectServlet</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>RedirectServlet</servlet-name>
<url-pattern>/rs</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>requset</servlet-name>
<servlet-class>com.zty.servlet.RequestTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>requset</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<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>
- pageContext.request.contextPath这里就是提交路径,填完姓名和密码后,它会通过get方式提交到login的Servlet处,我们再看看loginServlet如何处理
RequestTest
package com.zty.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
//重定向时候一定要注意,路径问题,否则404;
// resp.sendRedirect("/success.jsp");
resp.sendRedirect("success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
- 这里通过getParameter方法获取姓名和密码,在后台打印出来,然后重定向到success.jsp,注意重定向的url会跳转,我们试一下!
login测试
- 说的没错吧!
FileServlet
package com.zty.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 要获取下载文件的路径
// String realPath = "C:\\Users\\Irving\\Desktop\\csLearning\\java\\JavaWeb\\javaweb-servlet\\response\\target\\classes\\张天泳.jpg";
String realPath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "张天泳.jpg";
// System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath()); // WebContent目录下的文件绝对路径
System.out.println("下载文件的路径:"+realPath);
// 2. 下载的文件名是啥?
String fileName = realPath.substring(realPath.lastIndexOf("/") + 1);
System.out.println(fileName);
// 3. 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
// 4. 获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
// 5. 创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
// 6. 获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
// 7. 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端!
while ((len=in.read(buffer))>0){
System.out.println(len);
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
- 如果不想写绝对路径的话,Thread.currentThread().getContextClassLoader().getResource(“”).getPath()可以直接定位到target/classes目录
- resp要设置setHeader,这里选择content-disposition,选择附件的形式,记得要utf-8解决中文乱码!
- 来一个FilteInputStream读入文件
- 来一个buffer将文件流搞到resp.getOutputStream输出流中
- 注意(len=in.read(buffer))>0的写法,每次取后面的1024长度,相当于一个指针一直后移,直到到达结尾,体现了分片的思想!
- 最后记录close两个流!
文件下载测试
- 我们发现,down并不是一个jsp,他只是一个下载资源的请求,下载完附件后,还是会留在之前的success.jsp
动态图形验证码Servlet
package com.zty.servlet;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//如何让浏览器3秒自动刷新一次;
resp.setHeader("refresh","2");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(100, 20, BufferedImage.TYPE_INT_BGR);
//得到图片
Graphics2D g = (Graphics2D) image.getGraphics();
//设置图片背景颜色
g.setColor(Color.white);
g.fillRect(0,0,100,20);
//给图片写数据
g.setColor(Color.blue);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器。这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//网站存在缓存,不然浏览器缓存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.setUseCache(false); // 用内存缓存, 若用文件缓存可能会报错cannot create cache file
ImageIO.write(image, "jpg", resp.getOutputStream());
}
//生成随机数
private String makeNum(){
// test2
Random random = new Random();
String num = random.nextInt(99999999)+"";
StringBuffer buffer = new StringBuffer();
for (int i=0;i<=7-num.length();i++){
buffer.append("0");
}
num = buffer.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
- resp的setHeader的refresh来控制浏览器多少秒刷新一次!
- BufferedImage在内存创一个图片!
- Graphic2D可以得到图片
- 设置图片背景色setColor,用长方形填充fillRect!
- 设置字体setFont,写字drawString!
- 给resp进行setContetType作为图片!
- 不让网站缓存,expires,cache-control和pragma修改
- ImageIO直接write给resp的getOutputStream!
- 注意用内存缓存!setUserCache(false)
动态图形验证码测试
- 看到了吧,我都说他一直在更新!!
总结
- servlet中resp的玩法
- 重定向!
- 设置resp的类型等,刷新时间之类的
- 获取前端传来的参数,用getParameter!