5.Servlet类实现图片验证码和重定向

本文介绍了如何使用Servlet生成图片验证码,并讲解了重定向的概念及其与请求转发的区别。在验证码部分,详细阐述了设置响应头、创建BufferedImage对象以及生成随机数的方法。在重定向部分,对比了重定向和请求转发的异同,并给出具体操作示例,包括在web.xml中的配置和JSP页面的交互。此外,还提供了一个简单的请求处理示例,演示了登录验证和请求转发的过程。
摘要由CSDN通过智能技术生成

1.图片验证码

代码

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.让浏览器3秒刷新一次
        resp.setHeader("refresh","3");

        //2.在内存中创建一个图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);

        //3.得到图片,并设置画笔
        Graphics2D g = (Graphics2D)image.getGraphics();

        //4.设置图片的背景颜色
        g.setColor(Color.white);
        g.fillRect(0,0,80,20);//填充图片

        //5.给图片写数据
        g.setColor(Color.blue);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0,20);

        //6.告诉浏览器,这个请求用图片方式打开
        resp.setContentType("image/jpeg");

        //7.网站存在缓存,不让浏览器缓存
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma","no-cache");

        //8.把图片写给浏览器
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    //生成随机数
    private String makeNum(){
        String str = new Random().nextInt(9999999) + "";
        System.out.print(str+" ");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < (7 - str.length()); i++) {
            sb.append("0");
        }
        str  = sb.toString() + str;
        return str;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

1.resp.setHeader 设置浏览器的响应头文件内的一些参数,除了能设置刷新时间以外,还能设置状态码、是否连接、编码方式等等

2.TYPE_INT_RGB 表示具有8位RGB颜色分量的整数像素的图像

3.BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY)

其中width表示图像的宽度,height表示图像的高度,最后一个参数表示图像字节灰度图像

4.public int nextInt(int n)

该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n。

5.response.setHeader强制清空缓存和强制过期 resp.setDateHeader(“expires”,-1);
resp.setHeader(“Cache-Control”,“no-cache”);
resp.setHeader(“Pragma”,“no-cache”);

2. 重定向

2.1.重定向

resp.sendRedirect("/response_war/img");

2.2.请求转发

ServletContext context = this.getServletContext();
context.getRequestDispatcher("/gp").forward(req,resp);

面试题:请你聊聊重定向和转发的区别?

相同点

  • 页面都会实现跳转

不同点

  • 请求转发的时候,url不会产生变化 307
  • 重定向时候,url地址栏会发生变化; 302

2.3 具体操作

在pom.xml文件中配置相关jsp依赖

<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>

index.jsp页面代码

<html>
<body>
<h2>Hello</h2>
<form method="get" action="${pageContext.request.contextPath}/login">
    USERNAME <input type="text" name="username"><br>
    PASSWORD <input type="password" name="password"><br>
    <input type="submit">
</form>
</body>
</html>

${pageContext.request.contextPath} 获取绝对路径

表单提交后访问login

login为在web.xml文件中配置的servlet注册和映射

<servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.nslt.servlet.RequestTest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

对login的具体操作在RequestTest类中

@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);
        resp.sendRedirect("/response_war/main.jsp");

    }

在控制台输出用户输入的用户名和密码,并且跳转到main.jsp页面

main.jsp页面代码


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Successs</h1>
</body>
</html>

3.简单的请求demo

新建一个request module

配置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">

</web-app>

删除掉自带的index.jsp ,自己创建一个新的index.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="${pageContext.request.contextPath}/login">
        USERNAME<input type="text" name="username"><br>
        PASSWORD<input type="password" name="password"><br>
        HOBBY
        <input type="checkbox" name="hobby" value="游戏">游戏
        <input type="checkbox" name="hobby" value="代码">代码
        <input type="checkbox" name="hobby" value="旅游">旅游
        <input type="checkbox" name="hobby" value="健身">健身
        <br>
        <input type="submit">
    </form>
</body>
</html>

新建一个success.jsp作为登录成功的跳转页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Login Success</h1>
</body>
</html>

创建Login类,用来处理客户端的请求

在控制台打印输出用户名和密码

请求转发到success.jsp页面

package com.nslt.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 Login 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("hobby");
        System.out.println("=========================================");
        System.out.println(username+" "+password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("=========================================");

        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

在web.xml中进行login类的注册和映射

<servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.nslt.servlet.Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

4.参考

内容来自我看下面视频所做笔记

https://www.bilibili.com/video/av68833391

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值