生成图片(VerfiyCode类)
import org.junit.Test;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*动态生成图片*/
public class Image {
@Test
public void fun1() throws FileNotFoundException, IOException {
/*创建图片缓冲区;
* 设置其宽高;
* 得到这个图片的绘制环境;
* 保存起来;*/
BufferedImage bi = new BufferedImage(70,35,BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();/*得到绘制环境*/
g.setColor(Color.white);/*把环境设置成白色*/
g.fillRect(0,0,70,35);/*填充矩形,从0,0点开始,宽70,高30,即整个图片,即为设置环境背景色*/
g.setColor(Color.RED);/*把环境设置为白色*/
g.drawString("hello",2,35-2);/*向图片上写入字符串,其中2,33表示x.y轴坐标*/
ImageIO.write(bi,"JHDF",new FileOutputStream("G:/xxx.jpg"));
}
@Test
public void fun2() throws FileNotFoundException, IOException{
VerifyCode vc = new VerifyCode();
BufferedImage bi = vc.getImage();
VerifyCode.output(bi,new FileOutputStream("G:/sss.jpg"));
System.out.println(vc.getText());
}
}
package baoming;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifyCode {
private int w = 70;
private int h = 35;
private Random r = new Random();
// 定义有那些字体
private String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312" };
// 定义有那些验证码的随机字符
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
// 生成背景色
private Color bgColor = new Color(250, 250, 250);
// 用于gettext 方法 获得生成的验证码文本
private String text;
// 生成随机颜色
private Color randomColor() {
int red = r.nextInt(150);
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red, green, blue);
}
// 生成随机字体
private Font randomFont() {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4);
int size = r.nextInt(5) + 24;
return new Font(fontName, style, size);
}
// 画干扰线
private void drawLine(BufferedImage image) {
int num = 3;
Graphics2D g2 = (Graphics2D) image.getGraphics();
for (int i = 0; i < num; i++) {
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));// 不知道
g2.setColor(Color.blue);
g2.drawLine(x1, y1, x2, y2);
}
}
// 得到codes的长度内的随机数 并使用charAt 取得随机数位置上的codes中的字符
private char randomChar() {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}
// 创建一张验证码的图片
public BufferedImage getImage() {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
StringBuilder sb = new StringBuilder();
// 向图中画四个字符
for (int i = 0; i < 4; i++) {
String s = randomChar() + "";
sb.append(s);
float x = i * 1.0F * w / 4;
g2.setFont(randomFont());
g2.setColor(randomColor());
g2.drawString(s, x, h - 5);
}
this.text = sb.toString();
drawLine(image);
// 返回图片
return image;
}
// 得到验证码的文本 后面是用来和用户输入的验证码 检测用
public String getText() {
return text;
}
// 定义输出的对象和输出的方向
public static void output(BufferedImage bi, OutputStream fos)
throws FileNotFoundException, IOException {
ImageIO.write(bi, "JPEG", fos);
}
}
image.png
登录功能之添加验证码
image.png
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basepath = request.getScheme()+":"+"//"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<script type="text/javascript">
function _change() {
/*得到img元素
* 修改其src为/day11_2/VerifyCodeServlet*/
var imgEle = document.getElementById("img");
imgEle.src = "/day11_2/VerifyCodeServlet?a="+new Date().getTime();
}
</script>
<head>
<title>$Title$</title>
</head>
<body>
<h1>登录</h1>
<%
/*读取名为uname的Cookie
* 如果为空,显示“”
* 如果不为空,显示它的值*/
String uname = "";
Cookie[] cs = request.getCookies();//获取请求中的所有Cookie
if(cs!=null){//如果存在Cookie
for(Cookie c : cs){//循环遍历所有的Cookie
if("uname".equals(c.getName())){//查找名为uname的Cookie
uname = c.getValue();//获取这个Cookie的值,给uname这个变量
}
}
}
%>
<%
String message = "";
String msg = (String)request.getAttribute("msg");//获取request域中名为msg的属性
if(msg!=null){
message=msg;
}
%>
<font color="red"></font>
<form action="/day11_2_war_exploded/LoginServlet" method="post"><%=message%>
<%--把Cookie中的用户名显示到用户名文本框中--%>
用户名:<input type="text" name="username" value="<%=uname%>"><br/>
密 码:<input type="text" name="password"><br/>
验证码:<input type="text" name="verifyCode" size="3"/>
<img id="img" src="VerifyCodeServlet">
<a href="javascript:_change">换一张</a>
</br>
<input type="submit" value="登录">
</form>
</body>
</html>
package baoming;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet(name = "LoginServlet",urlPatterns = "{/day11_2_war_exploded/LoginServlet}")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*校验验证码
* 1、从session中获取正确的验证码
* 2、从表单中获取用户填写的验证码
* 3、进行比较
* 4、如果相同,进行比较,否则保存错误信息到request域,转发到login.jsp*/
String sessionCode = (String) request.getSession().getAttribute("session_vcode");
String paramCode = request.getParameter("verifyCode");
if(!paramCode.equalsIgnoreCase(sessionCode)){
request.setAttribute("msg","验证码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
return;
}
/*1、获取表单信息
* 处理中文问题
* 获取*/
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
/*2、校验用户名和密码是否正确*/
if(!"itcast".equals("username")){//登录成功
/*附加项:把用户名保存到Cookie中,发送给客户端浏览器
* 当再次打开login.jsp时,login.jsp会读取request中的Cookie,把它显示到用户名文本框中*/
Cookie cookie = new Cookie("uname","username");
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
/*3、如果成功
* 保存用户信息到session中
* 重定向到succ1.jsp中*/
HttpSession session = request.getSession();//获取session,从session类中拿到session
session.setAttribute("username",username);//向session域中保存用户名
response.sendRedirect("/day11_2_war_exploded/succ1.jsp");
}
else{/*登录失败*/
/*4、保存失败信息到request域中
* 转发到login.jsp*/
request.setAttribute("msg","您输入的用户名或密码有误,请重新输入");//保存失败信息数据到request域中,
RequestDispatcher qr = request.getRequestDispatcher("/login.jsp");//得到转发器
qr.forward(request,response);//转发
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
package baoming;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
@WebServlet(name = "VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*生成图片
* 保存图片的文本到session域中
* 把图片相应给客户端*/
VerifyCode vc = new VerifyCode();
BufferedImage image = vc.getImage();
request.getSession().setAttribute("session",vc.getText());/*保存图片上的文本到session域*/
VerifyCode.output(image,response.getOutputStream());
}
}
package baoming;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifyCode {
private int w = 70;
private int h = 35;
private Random r = new Random();
// 定义有那些字体
private String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312" };
// 定义有那些验证码的随机字符
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
// 生成背景色
private Color bgColor = new Color(250, 250, 250);
// 用于gettext 方法 获得生成的验证码文本
private String text;
// 生成随机颜色
private Color randomColor() {
int red = r.nextInt(150);
int green = r.nextInt(150);
int blue = r.nextInt(150);
return new Color(red, green, blue);
}
// 生成随机字体
private Font randomFont() {
int index = r.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = r.nextInt(4);
int size = r.nextInt(5) + 24;
return new Font(fontName, style, size);
}
// 画干扰线
private void drawLine(BufferedImage image) {
int num = 3;
Graphics2D g2 = (Graphics2D) image.getGraphics();
for (int i = 0; i < num; i++) {
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));// 不知道
g2.setColor(Color.blue);
g2.drawLine(x1, y1, x2, y2);
}
}
// 得到codes的长度内的随机数 并使用charAt 取得随机数位置上的codes中的字符
private char randomChar() {
int index = r.nextInt(codes.length());
return codes.charAt(index);
}
// 创建一张验证码的图片
public BufferedImage getImage() {
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
StringBuilder sb = new StringBuilder();
// 向图中画四个字符
for (int i = 0; i < 4; i++) {
String s = randomChar() + "";
sb.append(s);
float x = i * 1.0F * w / 4;
g2.setFont(randomFont());
g2.setColor(randomColor());
g2.drawString(s, x, h - 5);
}
this.text = sb.toString();
drawLine(image);
// 返回图片
return image;
}
// 得到验证码的文本 后面是用来和用户输入的验证码 检测用
public String getText() {
return text;
}
// 定义输出的对象和输出的方向
public static void output(BufferedImage bi, OutputStream fos)
throws FileNotFoundException, IOException {
ImageIO.write(bi, "JPEG", fos);
}
}
<?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"
metadata-complete="true"
version="4.0">
<servlet>
<servlet-name>loginjsp</servlet-name>
<jsp-file>/login.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>loginjsp</servlet-name>
<url-pattern>/login.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>succ1jsp</servlet-name>
<jsp-file>/succ1.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>succ1jsp</servlet-name>
<url-pattern>/succ1.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>succ2jsp</servlet-name>
<jsp-file>/succ2.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>succ2jsp</servlet-name>
<url-pattern>/succ2.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>baoming.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>VerifyCodeServlet</servlet-name>
<servlet-class>baoming.VerifyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VerifyCodeServlet</servlet-name>
<url-pattern>/VerifyCodeServlet</url-pattern>
</servlet-mapping>
</web-app>
网友评论