登陆功能,账号密码验证码


1.login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<title>多级分销系统</title>
<meta name="keywords" content="多级分销系统!">
<meta name="description" content="这是一个多级分销系统!">
<link rel="Bookmark" href="H-ui_v2.2.1/favicon.ico" >
<link rel="Shortcut Icon" href="H-ui_v2.2.1/favicon.ico" />
<link href="H-ui_v2.2.1/static/h-ui/css/H-ui.css" rel="stylesheet" type="text/css" />
<link href="H-ui_v2.2.1/lib/Hui-iconfont/1.0.7/iconfont.css" rel="stylesheet" type="text/css" />
</head>
<body style="background-image: url(images/bi3.jpg);">
<div>
<div class="row"><br><br><br><br><br><br><br><br><br><br></div>
<div class="row">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<form action="/web10-7/user/login" method="post" class="form form-horizontal" id="form-login">
<label class="c-white">登录</label>
<c:if test="${ param.error == 'error' }">
<div class="row cl text-c">
<label class="col-xs-12 c-error">用户名或密码错误!</label>
</div>
</c:if>
<c:if test="${ param.error == 'verifyCodeError' }">
<div class="row cl text-c">
<label class="col-xs-12 c-error">验证码错误!</label>
</div>
</c:if>
<div class="row cl">
<label class="col-xs-2 c-white" for="username">用户名:</label>
<div class="formControls col-xs-10">
<input type="text" class="input-text radius" name="username" id="username">
</div>
</div>
<div class="row cl">
<label class="col-xs-2 c-white" for="password">密码:</label>
<div class="formControls col-xs-10">
<input type="password" class="input-text radius" name="password" id="password">
</div>
</div>
<div class="row cl">
<label class="col-xs-2 c-white" for="verifyCode">验证码:</label>
<div class="formControls col-xs-4">
<input type="text" class="input-text radius" name="verifyCode" id="verifyCode">
</div>
<div class="formControls col-xs-6">
<img id="verifyCodeImage" οnclick="change()" src="/web10-7/verifyCode"/>
<a href='#' οnclick="change()" class="c-white">看不清?换一张</a>
</div>
</div>
<div class="row cl">
<div class="col-xs-2"></div>
<div class="col-xs-10">
<input class="btn btn-primary radius" type="submit" value="&nbsp;&nbsp;登录&nbsp;&nbsp;">
<label class="c-red hidden" id="logining">登陆中...</label>
</div>
</div>
</form>
</div>
<div class="col-xs-4"></div>
</div>
</div>

<script type="text/javascript" src="H-ui_v2.2.1/lib/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="H-ui_v2.2.1/static/h-ui/js/H-ui.js"></script>
<script type="text/javascript" src="H-ui_v2.2.1/lib/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="H-ui_v2.2.1/lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="H-ui_v2.2.1/lib/jquery.validation/1.14.0/messages_zh.min.js"></script>
<script type="text/javascript">

function change(){
document.getElementById("verifyCodeImage").src = "/web10-7/verifyCode?" + Math.random();
}

function logining(){
$("#logining").removeClass("hidden");
}

$("#form-login").validate({
rules:{
username:{
required:true
},
password:{
required:true,
minlength:3
},
verifyCode:{
required:true
},
},
messages:{
username:{
required:"请输入用户名"
},
password:{
required:"请输入密码",
minlength:"密码至少3位"
},
verifyCode:{
required:"请输入验证码"
},
},
onkeyup:false,
success:"valid",
submitHandler:function(form){
logining();
$(form).ajaxSubmit();
}
});

</script>
</body>
</html>
2.UserAction.java(登陆的action)
package firmye.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import firmye.pojo.CallbackResult;
import firmye.pojo.Function;
import firmye.pojo.Menu;
import firmye.pojo.RoleFunction;
import firmye.pojo.User;
import firmye.pojo.UserRole;
import firmye.service.FunctionServcie;
import firmye.service.MenuService;
import firmye.service.RoleFunctionService;
import firmye.service.UserRoleService;
import firmye.service.UserService;
import firmye.utils.EncodeUtil;
import firmye.utils.GetTimeUtil;

@Controller
@RequestMapping("/user")
public class UserAction {

@Resource
private UserService userService;
@Resource
private UserRoleService userRoleService;
@Resource
private RoleFunctionService roleFunctionService;
@Resource
private FunctionServcie functionServcie;
@Resource
private MenuService menuService;

/**
* @author Firmye
* @date 2016年10月20日 下午3:49:13
*
* 登陆
*/
@RequestMapping("/login")
public ModelAndView login(HttpSession session, String username, String password, String verifyCode) {
//后台生成的验证码
String vc = (String) session.getAttribute("verifyCode");
//前台验证码与后台验证码是否相等,相等就开始登陆
if (vc.toUpperCase().equals(verifyCode.toUpperCase())) {

User temp = new User();
temp.setName(username);
password += password.substring(0, 3);
temp.setPassword(EncodeUtil.getInstance().encode(password));

//用户登陆,返回一个用户
User user = userService.login(temp);
//如果用户不为空
if (user != null) {
//创建一个角色,根据用户的id返回一个用户角色 (用户id,用户角色id)
UserRole userRole = userRoleService.query(user);
//根据用户角色id,返回所有的角色功能的集合(用户角色id 角色功能id)
List<RoleFunction> roleFunctions = roleFunctionService.query(userRole);

//创建一个功能的集合
List<Function> functions = new ArrayList<Function>();
//遍历所有的角色功能
for (RoleFunction roleFunction : roleFunctions) {
//得到每一个角色所拥有的功能(角色功能id 功能的名字)
Function function = functionServcie.query(roleFunction);
//把每个功能添加进功能列表
functions.add(function);
}

/**
* 1.创建一个装菜单的list
* */
List<Menu> menus_nd = new ArrayList<Menu>();
/**
* 把每一个功能放进foreach,得到每一个菜单,装到menus_nd中
* */
for (Function function : functions) {
//根据功能的id得到所对应的菜单 的到功能所拥有的菜单(一个功能id对应一个菜单)
Menu menu = menuService.queryByFunction(function);
System.out.println("0.1"+menu);
//把每一个菜单添加进菜单集合(遍历出来所有的菜单了)
menus_nd.add(menu);
System.out.println("0.2"+menus_nd);
}
//System.out.println(menus_nd);
/**
* 2.创建一个菜单的集合list
* */
List<Menu> menus_st = new ArrayList<Menu>();
System.out.println("1.menus_st是"+menus_st);
/**
* 遍历所有的菜单
* */
for (Menu menu : menus_nd) {
//根据每一个菜单的父id的返回所属于父id的子菜单
Menu m = menuService.queryByMenu(menu);
System.out.println("2.m"+m.getName());
System.out.println("2.1menus_st是"+menus_st);
/**
* 过滤
* */
boolean flag = true;
//遍历
for (Menu tmp : menus_st) {
System.out.println("tmp是"+tmp.getName());
System.out.println("3.menus_st是"+menus_st);
if (tmp.getId().equals(m.getId())) {
flag = false;
System.out.println("如果flag是false是"+m.getName());
continue;
}
}
if (flag)
System.out.println("如果flag是true是"+m.getName());
menus_st.add(m);
}
//System.out.println(menus_st);
user.setLast_login(GetTimeUtil.getInstance().getNow());
userService.updatelast_login(user);

session.setAttribute("menus_st", menus_st);
session.setAttribute("menus_nd", menus_nd);
session.setAttribute("functions", functions);
session.setAttribute("userRole", userRole);
session.setAttribute("user", user);
session.setAttribute("logined", "yes");
return new ModelAndView("redirect:/main.jsp");

} else {
return new ModelAndView("redirect:/login.jsp?error=error");
}
} else {
return new ModelAndView("redirect:/login.jsp?error=verifyCodeError");
}
}
}
3.VerifyCodeAction.java
package firmye.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import firmye.utils.VerifyCodeUtil;

@Controller
public class VerifyCodeAction {

@RequestMapping("/verifyCode")
protected void verifyCode(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");

// 生成随机字串
String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
// 存入会话session,后台生成的验证码存进session域
HttpSession session = request.getSession(true);
session.setAttribute("verifyCode", verifyCode.toLowerCase());
// 生成图片,显示到前台
int w = 80, h = 30;
VerifyCodeUtil.outputImage(w, h, response.getOutputStream(), verifyCode);
}

}
4. VerifyCodeUtil.java
package firmye.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCodeUtil {

// 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写
public static final String VERIFY_CODES = "0123456789ABCDEFGHIJKLMNPOPQRSTUVWXYZ";
private static Random random = new Random();

public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, VERIFY_CODES);
}

public static String generateVerifyCode(int verifySize, String sources) {
if (sources == null || sources.length() == 0) {
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}

public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}

public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}

public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
if (outputFile == null) {
return;
}
File dir = outputFile.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
try {
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch (IOException e) {
throw e;
}
}

public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
Color.ORANGE, Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);

g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);

Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h - 4);

// 绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}

// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}

shear(g2, w, h, c);// 使图片扭曲

g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
(w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}

g2.dispose();
ImageIO.write(image, "jpg", os);
}

private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}

private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}

private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}

private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}

private static void shearX(Graphics g, int w1, int h1, Color color) {

int period = random.nextInt(2);

boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);

for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}

}

private static void shearY(Graphics g, int w1, int h1, Color color) {

int period = random.nextInt(40) + 10; // 50;

boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}

}

}

public static void main(String[] args) throws IOException {
File dir = new File("F:/verifies");
int w = 200, h = 80;
for (int i = 0; i < 50; i++) {
String verifyCode = generateVerifyCode(4);
File file = new File(dir, verifyCode + ".jpg");
outputImage(w, h, file, verifyCode);
}
}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值