Respons_案例_输出字节数据
服务器输出字节数据到浏览器
步骤:
获取字节输出流
输出数据
resp.setCharacterEncoding("text/html;charset=utf-8");
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write("你好".getBytes("utf-8"));
验证码分析
创建一对象,在内存中图(验证码对象)
美化图片
将图片输出到页面
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 100;
int height = 50;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.setColor(Color.PINK);
graphics.fillRect(0,0,width,height);
graphics.setColor(Color.BLUE);
graphics.drawRect(0,0,width-1,height-1);
String str = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
for (int i = 1; i <=4; i++) {
int i1 = random.nextInt(str.length());
char c = str.charAt(i1);
graphics.drawString(c+"",width/5*i,height/2);
}
// graphics.drawString("A",20,25);
// graphics.drawString("B",40,25);
// graphics.drawString("C",60,25);
// graphics.drawString("D",80,25);
graphics.setColor(Color.green);
for (int i = 0; i <10; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
ImageIO.write(image,"jpg",resp.getOutputStream());
}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> window.onload = function () { var img = document.getElementById("checkCode"); img.onclick = function () { var date = new Date().getTime(); img.src = "/checkCodeServlet?"+date; } } </script> </head> <body> <img id="checkCode" src="/checkCodeServlet"/> <a id="change" href="">看不清换一张</a> </body> </html>
浙公网安备 33010602011771号