JavaWeb | 验证码 、 文件的“上传”与“下载”
目录:
- 验证码 和 文件的“上传”与“下载”
- 1.验证码
- 1.1在JSP上开发验证码
- 2.“文件上传” 和 “文件下载”
- 2.1“文件上传 ”
- 2.2“文件下载”
验证码 和 文件的“上传”与“下载”
1.验证码
- 验证码:就是由服务器生成的一串随机数字或符号形成一幅图片,图片应该传给客户端,为了防止客户端用一些程序进行自动识别,在图片中通常需要添加一些干扰因素,由用户用肉眼来识别。
- 验证码在网络投票、交友论坛、网上商城等业务经常用来防止恶意客户侵入、恶意灌水、刷票。
1.1在JSP上开发验证码
loginForm.jsp
<%@ page language="java" pageEncoding="gb2312" %> <html> <head> <title>第十三章 loginForm.jsp</title> </head> <body> 欢迎登录本系统<br> <form action="/com/servlets/ValidateServlet" method="post"> 请输入你的账号: <input type="text" name="account"/><br> 请输入你的密码: <input type="password" name="password"/><br> 验证码: <input type="text" name="code" size="10"/><br> <!-- 当验证码当做图片处理 --> <img src="validate.jsp" border=0> <input type="submit" value="登录"> </form> </body> </html>
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"> <!-- 访问到ValidateServlet.java类 --> <servlet> <servlet-name>validateServlet</servlet-name> <servlet-class>com.servlets.ValidateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>validateServlet</servlet-name> <url-pattern>/com/servlets/ValidateServlet</url-pattern> </servlet-mapping> </web-app>
ValidateServlet.class
/* 验证输入的验证码是否正确 */ public class ValidateServlet extends HttpServlet { //用来验证表单登录的servlet protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到提交的验证码 String code = request.getParameter("code"); //获取session中的验证码 HttpSession session = request.getSession(); String randomStr = (String)session.getAttribute("randomStr"); //获取存储在session中的验证码 response.setCharacterEncoding("gb2312"); PrintWriter out = response.getWriter(); //判断输入的验证码和生成的验证码是否相等 if (!code.equals(randomStr)) { out.println("验证码错误!"); //在页面上显示 } else { out.println("验证码正确!跳转到LoginServlet..."); } } }
validate.jsp
<%@ page import="java.awt.image.BufferedImage" %> <%@ page import="java.awt.*" %> <%@ page import="java.util.Random" %> <%@ page import="javax.imageio.ImageIO" %> <%@ page contentType="text/html;charset=gb2312" language="java" %> <html> <head> <title>第十三章 validate.jsp</title> </head> <body> <% response.setHeader("Cache-Control","no-cache"); int width = 60; int height = 20; //1.实例化cBufferImage 对象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //2.从BufferImage中获取画笔Graphics类对象 Graphics g = image.getGraphics(); //设置画笔的属性 g.setColor(new Color(200,200,200)); //设置颜色 / 设置背景颜色 g.fillRect(0, 0, width, height); //设置生成的图片为长方形 //3.生成随机数(4位数字) Random random = new Random();//这个随机数没有“种子”,用默认种子 int randomNum = random.nextInt(8999) +100; //左闭右开 //转换为字符串 String randomStr = String.valueOf(randomNum); //存入Session中 session.setAttribute("randomStr",randomStr); //将验证码显示在图像中 //用画笔画出干扰线和干扰电 g.setColor(Color.black); g.setFont(new Font("", Font.PLAIN, 20)); g.drawString(randomStr,10,17); //产生干扰点 for (int i = 0; i < 100; i++) { int x = random.nextInt(width); int y = random.nextInt(height); g.drawOval(x,y,1,1);//干扰点为一个一个圆 } //输出图像到页面 response.setContentType("image/jpeg"); ImageIO.write(image, "JPEG", response.getOutputStream()); out.clear(); out = pageContext.pushBody(); %> </body> </html>
loginForm_refresh.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>第十三章: loginForm_refresh.jsp</title> </head> <body> <%-- 具有刷新验证码功能的loginForm页面 --%> <%-- 重新刷新验证码--%> <script> function refresh() { //当点击验证码图片时就重新刷新img标签中的url //让url后面带一个随机数参数,来让每次访问的路径不一样,得到的验证码也不一样 loginForm.imgValidate.src = "validate.jsp?id=" + Math.random() +";" } </script> 欢迎登录本系统<br> <%-- action中访问的为web.xml 中servlet标签中的 url --%> <form name="loginForm" action="/com/servlets/ValidateServlet" method="post"> 请输入你的账号: <input type="text" name="account"/><br> 请输入你的密码: <input type="password" name="password"/><br> 验证码: <input type="text" name="code" size="10"/><br> <!-- 当验证码当做图片处理 ,为该img标签添加"点击事件",让它被点击时,刷牙验证码--> <img name = "imgValidate" src="validate.jsp" οnclick="refresh()" border=0> <input type="submit" value="登录"> </form> </body> </html>
2.“文件上传” 和 “文件下载”
2.1“文件上传 ”
- 在Java Web应用开发中,文件的上传是必不可少的,如上传简历、上传图片、上传资源代码等。
- 要实现文件上传,要导入 : jspsmart文件上传包。
fileTest.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="gb2312" %> <html> <head> <title>第十三章 文件上传: fileTest.jsp</title> </head> <body> <form method="post" name="upload"> 请你选择一个文件进行上传: <input type="file" name="myFile"><br> <input type="submit" value="上传"><br> </form> </body> </html>
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"> <servlet> <servlet-name>uploadServlet</servlet-name> <servlet-class>com.servlets.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>uploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping> </web-app>
UploadServlet.java
public class UploadServlet extends HttpServlet { //关于文件上传的Servlet类 @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //创建SmartUpload对象,其负责文件的上传 SmartUpload smartUpload = new SmartUpload(); //初始化SmartUpload对象 //获得ServletConfig对象 ServletConfig config = this.getServletConfig(); smartUpload.initialize(config, request, response); try { //上传文件--调用.upload()方法上传文件 smartUpload.upload(); //获得上传的文件 File file = smartUpload.getFiles().getFile(0); //保存文件 file.saveAs("/S:/aaa/"+file.getFileName(),smartUpload.SAVE_PHYSICAL); //这个是存储在S盘中(物理路径存储) //file.saveAs("/img/"+file.getFileName(),smartUpload.SAVE_VIRTUAL); } catch (SmartUploadException e) { e.printStackTrace(); } //上传成功了,保存成功上传的信息 String msg = "Upload Success!"; request.setAttribute("msg", msg); RequestDispatcher rd = request.getRequestDispatcher("/upload/第十三章/文件上传/uploadForm.jsp"); //上传完之后又回来点击内容进行上传的页面 rd.forward(request, response); } }
2.2“文件下载”
download2.jsp
<%@ page language="java" pageEncoding="GB2312" import="java.util.*" %> <html> <head> <title>第十三章 文件下载: download2.jsp</title> </head> <body> 文件下载 <hr> <a href="/第十三章/文件下载/download.jsp?filename=java.jpg">下载</a> </body> </html>
download.jsp
<%@ page language="java" pageEncoding="gb2312" import="java.util.*" %> <html> <head> <title>文件下载: download.jsp</title> </head> <body> <% String filename = request.getParameter("filename"); //获得url传参传递过来的参数 //告诉客户端出现下载框,并指定下载框中的文件名 response.setHeader("Content-Disposition","attachment;filename="+filename); //指定文件的类型 response.setContentType("image/jpeg"); //jpeg //指定文件 RequestDispatcher rd = request.getRequestDispatcher("/S:/aaa/"+filename); //rd.forward(request,response); %> </body> </html>
此处给出常见文件对应的contentType类型,主要包括以下几种:
bmp : “application/x-bmp”;
doc: “application/msword”;
exe: “application/x-msdownload" ;
jpg: “image/jpeg" ;
mdb: “application/ msaccess”;
mp3: " audio/mp3”
pdf:”application/pdf";
ppt:”application/ vnd. ms-powerpoint";
rm:”application/vnd. rn- realmedia";
rmvb: “application/vnd. rn-realmedia-vbr”;
swf: “application/ x-shockwave-flash”;
xIs: “application/vnd. ms-excel”。