转自https://blog.csdn.net/MDreamlove/article/details/78562802
入坑,踩坑,填坑……
今天在Idea写一个简单地基于Servlet的验证码小页面
package com.dream.servlet.response;
import cn.dsna.util.images.ValidateCode;
import javax.imageio.ImageIO;
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;
/**
* Created by Dream on 2017/11/15.
*/
public class IdentifyCode extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException{
// produceCode(request,response);
//使用ValidateCode jar包中现成的验证码类
ValidateCode vc = new ValidateCode(110,25,4,9);
vc.write(response.getOutputStream());
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException{
doGet(request,response);
}
//自己写方法实现验证码
private void produceCode(HttpServletRequest request,HttpServletResponse response)throws IOException{
int width = 110;
int height = 25;
//创建一个图像对象
BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//创建一个画笔
Graphics g = img.getGraphics();
//填充内部颜色
g.setColor(Color.PINK);
g.fillRect(1,1,width-2,height-2);
//画边框
g.setColor(Color.RED);
g.drawRect(0,0,width-1,height-1);
//设置文本样式
g.setColor(Color.BLUE);
g.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,15));
//写随机数字
Random r = new Random();
int position = 20;
for(int i=0;i<4;i++){
g.drawString(r.nextInt(10)+"",position,20);
position+=20;
}
//画干扰线
g.setColor(Color.CYAN);
for(int i=0;i<5;i++){
g.drawLine(r.nextInt(width),r.nextInt(height),r.nextInt(width),r.nextInt(height));
}
ImageIO.write(img,"jpg",response.getOutputStream());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
其中produceCode()是自己写的方法,ValidateCode是一个可以产生验证码的现成类,但是,就是在我引入该类的jar包准备用这个类的时候,结果报出了如下错误
内心很崩溃,明明引入了该jar包,但是仍然报该类找不到的异常,黑人问号脸….
其实是因为jar包未被部署,那么在进行页面请求的时候,就会找不到jar包,那么就会报错…..
解决方案如下:
Projecture—>Artifacts–>选择打包部署项目—->Output Layout–>Web-INF—->查看下面是否有lib目录(如果没有lib目录,可自行创建)—>右边的jar包添加到lib目录下
以上,即可解决ClassNotFound的异常