展示页面
首先我贴上前端代码
点击验证码就进行更换验证码
更换验证的js代码
function refresh() {
document.getElementById('captcha_img').src="/yan/getVerify?"+Math.random();
}
然后是jquery的ajax提交到后端
$(function(){
$("#login").bind("click",function(){
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
var yan=document.getElementById("yan").value;
$.ajax({
type:'Get',
url:comm.ServerUrl+"admins/login",
data:{
username:username,
password:password,
yan:yan
},
contentType:'application/json',
dataType : 'json',
success:function(data){
console.log(data);
if(data.status == 200){
window.location.href=comm.ServerUrl+"admin/index";
}else{
alert(data.msg);
}
}
});
});
});
前端整体就到这里
思路就是
获取username、password、yan输入框为id的内容 然后传给后端进行校验
验证码的思路
生成验证码
然后存放到session
然后取出验证码,和前端传过来的进行校验
先贴上验证码工具代码 这个验证码我也忘了在哪里找的
/**
* 验证码生成工机
* @author binglian
*
*/
public class RandomValidateCodeUtil {
public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//放到session中的key
private String randString = "0123456789";//随机产生只有数字的字符串 如果要其他字母数字 自己在里面加
private int width = 95;// 图片宽
private int height = 25;// 图片高
private int lineSize = 40;// 干扰线数量
private int stringNum = 4;// 随机产生字符数量
private static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.class);
private Random random = new Random();
/**
* 获取字体
*/
private Font getFont() {
return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
}
/**
* 获得颜色
*/
private Color getRandColor(int fc,int bc){
if(fc>255){
fc=255;
}
if(bc>255){
bc=255;
}
int r=fc+random.nextInt(bc-fc-16);
int g=fc+random.nextInt(bc-fc-14);
int b=fc+random.nextInt(bc-fc-18);
return new Color(r, g, b);
}
/**
* 生成随机图片
*/
public void getRandcode(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(); // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
g.fillRect(0, 0, width, height);//图片大小
g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小
g.setColor(getRandColor(110, 133));//字体颜色
//绘制干扰线
for (int i = 0; i <= lineSize; i++) {
drowLine(g);
}
// 绘制随机字符
String randomString = "";
for (int i = 1; i <= stringNum; i++) {
randomString = drowString(g, randomString, i);
}
logger.info(randomString); //将生成的随机字符串保存到session中
session.removeAttribute(RANDOMCODEKEY);
session.setAttribute(RANDOMCODEKEY, randomString);
g.dispose();
try {
// 将内存中的图片通过流动形式输出到客户端
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception e) {
logger.error("将内存中的图片通过流动形式输出到客户端失败>>>> ", e);
}
}
/**
* 绘制字符串
*/
private String drowString(Graphics g, String randomString, int i) {
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random .nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(randString .length())));
randomString += rand; g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(rand, 13 * i, 16); return randomString;
}
/**
* 绘制干扰线
*/
private void drowLine(Graphics g) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x, y, x + xl, y + yl);
}
/**
* 获取随机的字符
*/
public String getRandomString(int num) {
return String.valueOf(randString.charAt(num));
}
}
生成验证码controller CodeController.java
@RestController
@RequestMapping("/yan")
@Slf4j
public class CodeController {
private static final Logger logger=LoggerFactory.getLogger(CodeController.class);
@RequestMapping(value="/getVerify")
public void getVerif(HttpServletRequest request,HttpServletResponse response){
try {
response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
randomValidateCode.getRandcode(request, response);//输出验证码图片方法
} catch (Exception e) {
logger.error("获取验证码失败>>>> ", e);
}
}
}
然后我们现在接下来该实现账户的登录 验证码这些校验了
我们先实现登录的业务实现
AdminService接口
public interface AdminService {
/**
* 判断用户名是否存在
* @param username
* @return
*/
public boolean queryUsernameIsExist(String username);
/**
* 查询用户是否匹配成功
* @param username
* @param pwd
* @return
*/
public Admin queryUserForLogin(String username,String password);
}
AdminServiceImpl实现接口
@Service
public class AdminServiceImpl implements AdminService{
@Autowired
private AdminMapper AdminMapper;
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public boolean queryUsernameIsExist(String username) {
Admin user=new Admin();
user.setUsername(username);
Admin result=AdminMapper.selectOne(user);
return result !=null ? true:false;
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public Admin queryUserForLogin(String username, String password) {
Example example=new Example(Admin.class);
Criteria criteria=example.createCriteria();
criteria.andEqualTo("username", username);
criteria.andEqualTo("password", password);
Admin result=AdminMapper.selectOneByExample(example);
return result;
}
}
然后也就是最后的控制层 api 这里的api路由地址就是jQuery提交的地址
AdminUserController
@RestController
@RequestMapping("admins")
public class AdminUserController {
@Autowired
private AdminService adminService;
@GetMapping("/login")
public BinglianJSONResult login(@RequestParam(name="yan") String yan,
@RequestParam(name="username") String username,
@RequestParam(name="password") String password,
HttpSession session) throws Exception{
//1.判断用户密码是否为空
if(StringUtils.isBlank(username)
|| StringUtils.isBlank(password)){
return BinglianJSONResult.errorMsg("用户名和密码不能为空");
}
//判断验证码不能为空
if(StringUtils.isBlank(yan)){
return BinglianJSONResult.errorMsg("验证码不能为空");
}
//从session中获取随机数
String random=(String) session.getAttribute("RANDOMVALIDATECODEKEY");
if(!yan.equalsIgnoreCase(random)){
return BinglianJSONResult.errorMsg("验证码错误");
}
boolean usernameIsExist=adminService.queryUsernameIsExist(username);
Admin Result=null;
if(usernameIsExist){
Result=adminService.queryUserForLogin(username,
MD5Utils.getMD5Str(password));
if(Result ==null){
return BinglianJSONResult.errorMsg("用户名或密码不正确...");
}
}
AdminVO adminVO=new AdminVO();
BeanUtils.copyProperties(Result, adminVO);
return BinglianJSONResult.ok(adminVO);
}
}