欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

验证码及文件上传

程序员文章站 2022-05-28 23:39:52
...

servlet 验证码及文件上传案例

下面的代码块是生成验证码的工具类

package com.example.homework0525; /**
 * @author 杨忠荣
 * @create 2021-05-25-14:31
 */

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkServlet")
public class CheckServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //服务器通知浏览器不要缓存
        response.setHeader("pragma","no-cache");
        response.setHeader("cache-control","no-cache");
        response.setHeader("expires","0");

        //在内存中创建一个长80,宽30的图片,默认黑色背景
        //参数一:长
        //参数二:宽
        //参数三:颜色
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //获取画笔
        Graphics g = image.getGraphics();
        //设置画笔颜色为灰色7
        g.setColor(Color.GRAY);
        //填充图片
        g.fillRect(0,0, width,height);

        //产生4个随机验证码,12Ey
        String checkCode = getCheckCode();
        //将验证码放入HttpSession中
        request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);

        //设置画笔颜色为黄色
        g.setColor(Color.YELLOW);
        //设置字体的小大
        g.setFont(new Font("黑体", Font.BOLD,24));
        //向图片上写入验证码
        g.drawString(checkCode,15,25);

        //将内存中的图片输出到浏览器
        //参数一:图片对象
        //参数二:图片的格式,如PNG,JPG,GIF
        //参数三:图片输出到哪里去
        ImageIO.write(image,"PNG",response.getOutputStream());

    }
    private String getCheckCode() {
        String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwxyz";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

前端页面调用servlet实现验证码

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>注册</title>
</head>
<script>
    window.onload=function (){
        let elementById = document.getElementById("imgs");
        elementById.onclick=function (){
            elementById.src="${pageContext.request.contextPath}/checkServlet?time="+new Date().getTime();
            //加一个时间戳来改变src与上一次访问的servlet来区别
            //post提交方式
        }
    }
</script>
    //enctype="multipart/form-data"enctype="multipart/form-data"文件上传是以二进制转换进行传输,所有需要声明,
    //后面userRegServlet用request.getParameter("");是获取不到文本框中的值的
   // ${pageContext.request.contextPath} 获取项目的一个根目录
<body>
    <form action="${pageContext.request.contextPath}/userRegServlet" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>账号</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="pwd"></td>
            </tr>
            <tr>
                <td>验证码</td>
                <td><input type="text" name="yzm"></td>
               <td><img src="checkServlet" id="imgs"></td><%-- 只要用户访问servlet就可以生成验证码--%>
            </tr>
            <tr>
                <td>照片</td>
                <td><input type="file" name="file"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="注册"></td>

            </tr>
        </table>
    </form>
        ${msg}
</body>
</html>

文件上传

导jar包

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xzyezfyl-1623238909112)(C:\Users\Administrator\Pictures\servlet\5.jpg)]

package com.example.homework0525; /**
 * @author 杨忠荣
 * @create 2021-05-25-18:27
 */

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/userRegServlet")
public class UserRegServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.setCharacterEncoding("utf8");
        //获取生成验证码
        String checkcode_server = request.getSession().getAttribute("CHECKCODE_SERVER").toString();
        //获取完成之后马上销毁验证码,以免对后面用户传递过来的验证码进行干扰
        request.getSession().removeAttribute("CHECKCODE_SERVER");
       //调用文件上传的jar包里面封装好的对象
        DiskFileItemFactory disfilef=new DiskFileItemFactory();
        //设置临时目录的值
        disfilef.setRepository(new File("d:/"));
        //设置临时文件的大小 4kb
        disfilef.setSizeThreshold(4096);
        //创建一个文件上传的对象
        //StringBuffer stringBuffer=new StringBuffer();
        ServletFileUpload servletFileUpload = new ServletFileUpload(disfilef);
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for(int i=0;i<fileItems.size();i++){
                if(fileItems.get(i).isFormField()){
                    //获取文本框用户名
//                    byte[] usernames = fileItems.get(0).getString().getBytes(StandardCharsets.UTF_8);
//                    for(int j=0;j<usernames.length;j++){
//                        stringBuffer.append(usernames[j]);
//
//                    }
                    String username = fileItems.get(0).getString();
                    //String username = stringBuffer.toString();
                    //获取文本框密码
                    String pwd=fileItems.get(1).getString();
                    //获取文本框验证码
                    String yzm = fileItems.get(2).getString();
//                    System.out.println(username);
//                    System.out.println(pwd);
//                    System.out.println(yzm);
                    if(!yzm.equalsIgnoreCase(checkcode_server)){
                        request.getSession().setAttribute("msg","验证码错误");
                        response.sendRedirect("index.jsp");
                        return;
                    }
                    if(username.equals("admin")&&pwd.equals("123456")){
                        //用户名 密码 验证码都正确 就上传文件
                        FileItem fileItem = fileItems.get(3);
                        request.getSession().setAttribute("username",username);
                        request.getSession().setAttribute("yzm",yzm);
                        String name = fileItem.getName();//获取文件的后缀
                        //获取服务器的根目录
                        String realPath = request.getServletContext().getRealPath("/");
                        //随机生成时间
//                        SimpleDateFormat sim=new SimpleDateFormat("yyyyMMddHHmmss");
//                        String format = sim.format(new Date());
                        String format= UUID.randomUUID().toString();
                        //获取文件的后缀名
                        String substring = name.substring(name.lastIndexOf("."));
                        File file=new File(realPath+format+substring);
                        //  String uid = UUID.randomUUID().toString();  或者是用这一行代码也可以生成唯一的标识名称
                        fileItem.write(file);
                        System.out.println("文件上传成功!!!");
                        response.sendRedirect("show.jsp");
                        return;
                    }else {
                        System.out.println(username);
                        System.out.println(pwd);
                        System.out.println(yzm);
                        request.getSession().setAttribute("msg","用户名或者密码错误,文件上传失败!");
                        response.sendRedirect("main.jsp");
                        return;
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

相关标签: 第二阶段 java