基于javaweb+mysql的springboot人脸识别登录系统(java+springboot+maven+mysql)
运行环境
Java≥8、MySQL≥5.7
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SpringBoot人脸识别登录系统(java+springboot+maven+mysql)
实现的功能有:
管理员后台录入人脸信息、前台用户登录时选择人脸识别方式登录。
PS:用到了百度人脸识别的API接口,包括人脸检测、人脸识别对比等。
return Result.error(CodeMsg.ADMIN_USER_ROLE_AUTHORITES_EMPTY);
}
//检查一切符合,可以登录,将用户信息存放至session
request.getSession().setAttribute(SessionConstant.SESSION_USER_LOGIN_KEY, findByUsername);
//销毁session中的验证码
request.getSession().setAttribute("admin_login", null);
//将登陆记录写入日志库
operaterLogService.add("用户【" + user.getUsername() + "】于【" + StringUtil.getFormatterDate(new Date(), "yyyy-MM-dd HH:mm:ss") + "】登录系统!");
log.info("用户成功登录,user = " + findByUsername);
return Result.success(true);
}
/**
* 人脸识别登录
*
* @param username
* @param face
* @return
*/
@RequestMapping(value = "/face_login", method = RequestMethod.POST)
@ResponseBody
public Result<Boolean> faceLogin(@RequestParam(name = "username", required = true) String username, @RequestParam(name = "face", required = true) String face) {
User user = userService.findByUsername(username);
//判断是否为空
if (user == null) {
return Result.error(CodeMsg.ADMIN_USERNAME_NO_EXIST);
}
if (StringUtils.isEmpty(user.getFace())) {
return Result.error(CodeMsg.ADMIN_USER_FACE_EMPTY);
}
//判断用户状态是否可用
if (user.getStatus() == User.ADMIN_USER_STATUS_UNABLE) {
return Result.error(CodeMsg.ADMIN_USER_UNABLE);
}
//检查用户所属角色状态是否可用
if (user.getRole() == null || user.getRole().getStatus() == Role.ADMIN_ROLE_STATUS_UNABLE) {
return Result.error(CodeMsg.ADMIN_USER_ROLE_UNABLE);
}
//检查用户所属角色的权限是否存在
if (user.getRole().getAuthorities() == null || user.getRole().getAuthorities().size() == 0) {
return Result.error(CodeMsg.ADMIN_USER_ROLE_AUTHORITES_EMPTY);
}
//此处调用百度api接口对比两张人脸相似度
String faceMatch = BaiduApi.faceMatch(user.getFace(), face);
log.info(faceMatch);
JSONObject parseObject = JSONObject.parseObject(faceMatch);
if (parseObject.getIntValue("error_code") != 0) {
CodeMsg codeMsg = CodeMsg.DATA_ERROR;
codeMsg.setMsg(parseObject.getString("error_msg"));
return Result.error(codeMsg);
}
//此处判断人脸可信度
}
mac = sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mac.toUpperCase();
}
public static boolean authOrder(String orderSn, String phone) {
//
return true;
}
public static String readFileToString(File file) {
String string = "";
if (file != null) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
string += line;
}
br.close();
} catch (Exception e) {
// TODO: handle exception
}
}
return string;
}
}
package com.yuanlrc.base.controller.admin;
/**
* 获取session
* @return
*/
public static HttpSession getSession(){
HttpServletRequest request = getRequest();
if(request != null){
return request.getSession();
}
return null;
}
/**
* 获取指定键的值
* @param key
* @return
*/
public static Object get(String key){
HttpSession session = getSession();
if(session != null){
return session.getAttribute(key);
}
return null;
}
/**
* 设置session值
* @param key
* @param object
*/
public static void set(String key,Object object){
HttpSession session = getSession();
if(session != null){
session.setAttribute(key,object);
}
}
/**
* 获取当前登录的用户
* @return
*/
/**
* 系统控制器
*
*/
@RequestMapping("/system")
@Controller
public class SystemController {
@Autowired
private OperaterLogService operaterLogService;
@Autowired
private UserService userService;
@Autowired
private OrderAuthService orderAuthService;
private String showTipsText = "";
private String showTipsUrlText = "";
private String showTipsBtnText = "";
*/
public class StringUtil {
/**
* 返回指定格式的日期字符串
*
* @param date
* @param formatter
* @return
*/
public static String getFormatterDate(Date date, String formatter) {
SimpleDateFormat sdf = new SimpleDateFormat(formatter);
return sdf.format(date);
}
/**
* 判断请求是否是ajax
*
* @param request
* @return
*/
public static boolean isAjax(HttpServletRequest request) {
String header = request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(header)) return true;
return false;
}
/**
* 从流读取字符串
*
* @param inputStream
* @return
*/
public static String getStringFromInputStream(InputStream inputStream) {
String string = "";
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GB2312"));
String buf = null;
try {
while ((buf = bufferedReader.readLine()) != null) {
string += buf;
}
} catch (Exception e) {
for (int i = 0; i < hardwareAddress.length; i++) {
//字节转换为整数
int temp = hardwareAddress[i] & 0xff;
String str = Integer.toHexString(temp);
//System.out.println("每8位:"+str);
if (str.length() == 1) {
sb.append("0" + str);
} else {
sb.append(str);
}
}
mac = sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mac.toUpperCase();
}
public static boolean authOrder(String orderSn, String phone) {
//
return true;
}
public static String readFileToString(File file) {
String string = "";
if (file != null) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
string += line;
}
br.close();
} catch (Exception e) {
// TODO: handle exception
}
}
return string;
}
}
package com.yuanlrc.base.controller.admin;
//此处判断人脸可信度
JSONObject result = parseObject.getJSONObject("result");
if(result.getIntValue("face_num") > 1){
return Result.error(CodeMsg.ADMIN_USE_FACE_NUMBER_ERROR);
}
JSONArray faceList = result.getJSONArray("face_list");
JSONObject face = faceList.getJSONObject(0);
if(face.getFloatValue("face_probability") < 0.8){
return Result.error(CodeMsg.ADMIN_USE_FACE_PROB_LOW);
}
existUser.setFace(user.getFace());
//到这说明一切符合条件,进行数据库新增
if(userService.save(existUser) == null){
return Result.error(CodeMsg.ADMIN_USE_DELETE_ERROR);
}
operaterLogService.add("录入用户人脸信息");
return Result.success(true);
}
/**
* 用户添加表单提交处理
* @param user
* @return
*/
@RequestMapping(value="/add",method=RequestMethod.POST)
@ResponseBody
public Result<Boolean> add(User user){
//用统一验证实体方法验证是否合法
CodeMsg validate = ValidateEntityUtil.validate(user);
if(validate.getCode() != CodeMsg.SUCCESS.getCode()){
return Result.error(validate);
}
if(user.getRole() == null || user.getRole().getId() == null){
return Result.error(CodeMsg.ADMIN_USER_ROLE_EMPTY);
}
//判断用户名是否存在
if(userService.isExistUsername(user.getUsername(), 0l)){
return Result.error(CodeMsg.ADMIN_USERNAME_EXIST);
}
//到这说明一切符合条件,进行数据库新增
if(userService.save(user) == null){
return Result.error(CodeMsg.ADMIN_USE_ADD_ERROR);
}
operaterLogService.add("添加用户,用户名:" + user.getUsername());
return Result.success(true);
/**
* 后台角色管理控制器
*
*/
@RequestMapping("/role")
@Controller
public class RoleController {
private Logger log = LoggerFactory.getLogger(RoleController.class);
@Autowired
private MenuService menuService;
@Autowired
private OperaterLogService operaterLogService;
@Autowired
private RoleService roleService;
/**
* 分页搜索角色列表
* @param model
* @param role
* @param pageBean
* @return
//讲提交的用户信息指定字段复制到已存在的user对象中,该方法会覆盖新字段内容
BeanUtils.copyProperties(user, findById, "id","createTime","updateTime");
if(userService.save(findById) == null){
return Result.error(CodeMsg.ADMIN_USE_EDIT_ERROR);
}
operaterLogService.add("编辑用户,用户名:" + user.getUsername());
return Result.success(true);
}
/**
* 删除用户
* @param id
* @return
*/
@RequestMapping(value="/delete",method=RequestMethod.POST)
@ResponseBody
public Result<Boolean> delete(@RequestParam(name="id",required=true)Long id){
try {
userService.delete(id);
} catch (Exception e) {
return Result.error(CodeMsg.ADMIN_USE_DELETE_ERROR);
}
operaterLogService.add("添加用户,用户ID:" + id);
return Result.success(true);
}
}
package com.yuanlrc.base.util;
/**
* 项目通用工具类
return Result.success(true);
}
}
package com.yuanlrc.base.controller.admin;
/**
* 后台角色管理控制器
*
*/
@RequestMapping("/role")
@Controller
public class RoleController {
private Logger log = LoggerFactory.getLogger(RoleController.class);
@Autowired
private MenuService menuService;
@Autowired
private OperaterLogService operaterLogService;
@Autowired
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
String requestURI = request.getRequestURI();
User loginedUser = SessionUtil.getLoginedUser();
log.info("进入权限控制拦截器" + requestURI);
List<Menu> authorities = loginedUser.getRole().getAuthorities();
if(!MenuUtil.isExistUrl(requestURI, authorities)){
//进入这里,表示权限不存在,首先判断是否是ajax请求
if(StringUtil.isAjax(request)){
//表示是ajax请求
try {
log.info("该请求无权限,已ajax方式返回提示,url=" + requestURI);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSON.toJSONString(CodeMsg.ADMIN_NO_RIGHT));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//说明是普通的请求,可直接重定向到无权限提示页面
try {
log.info("该请求无权限,重定向到无权限提示页面,url=" + requestURI);
response.sendRedirect("/system/no_right");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
log.info("该请求符合权限要求,放行" + requestURI);
return true;
}
}
package com.yuanlrc.base.util;
/**
filePath.mkdir();
}
filePath = new File(uploadPhotoPath + "/" + StringUtil.getFormatterDate(new Date(), "yyyyMMdd"));
//判断当天日期的文件夹是否存在,若不存在,则创建
if(!filePath.exists()){
//若不存在文件夹,则创建一个文件夹
filePath.mkdir();
}
String filename = StringUtil.getFormatterDate(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + suffix;
try {
photo.transferTo(new File(uploadPhotoPath+"/"+filename));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info("图片上传成功,保存位置:" + uploadPhotoPath + filename);
return Result.success(filename);
}
}
package com.yuanlrc.base.controller.common;
/**
* 系统验证码公用控制器
*
*/
@Controller
@RequestMapping("/cpacha")
public class CpachaController {
private String showTipsText = "";
private String showTipsUrlText = "";
private String showTipsBtnText = "";
private String showTipsUtl = "";
private Logger log = LoggerFactory.getLogger(SystemController.class);
/**
* 登录页面
*
* @param model
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
return "admin/system/login";
}
/**
* 用户登录提交表单处理方法
*
* @param request
* @param user
* @param cpacha
* @return
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Result<Boolean> login(HttpServletRequest request, User user, String cpacha) {
if (user == null) {
return Result.error(CodeMsg.DATA_ERROR);
}
//用统一验证实体方法验证是否合法
CodeMsg validate = ValidateEntityUtil.validate(user);
if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
return Result.error(validate);
}
//表示实体信息合法,开始验证验证码是否为空
if (StringUtils.isEmpty(cpacha)) {
return Result.error(CodeMsg.CPACHA_EMPTY);
}
//说明验证码不为空,从session里获取验证码
Object attribute = request.getSession().getAttribute("admin_login");
if (attribute == null) {
return Result.error(CodeMsg.SESSION_EXPIRED);
}
//表示session未失效,进一步判断用户填写的验证码是否正确
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GB2312"));
String buf = null;
try {
while ((buf = bufferedReader.readLine()) != null) {
string += buf;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
}
return string;
}
/**
* 获取指定格式时间再指定分钟后的时间字符串
*
* @param date
* @param formatter
* @param minites
* @return
*/
public static String getFormatterDate(String date, String formatter, int minites) {
SimpleDateFormat sdf = new SimpleDateFormat(formatter);
String ret = null;
try {
Date parse = sdf.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse);
calendar.add(Calendar.MINUTE, minites);
ret = sdf.format(calendar.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
/**
* 获取指定分钟前的时间
*
* @param date
* @param model
* @return
*/
@RequestMapping(value="/add",method=RequestMethod.GET)
public String add(Model model){
List<Menu> findAll = menuService.findAll();
model.addAttribute("topMenus",MenuUtil.getTopMenus(findAll));
model.addAttribute("secondMenus",MenuUtil.getSecondMenus(findAll));
model.addAttribute("thirdMenus",MenuUtil.getThirdMenus(findAll));
return "admin/role/add";
}
/**
* 角色添加表单提交处理
* @param role
* @return
*/
@RequestMapping(value="/add",method=RequestMethod.POST)
@ResponseBody
public Result<Boolean> add(Role role){
//用统一验证实体方法验证是否合法
CodeMsg validate = ValidateEntityUtil.validate(role);
if(validate.getCode() != CodeMsg.SUCCESS.getCode()){
return Result.error(validate);
}
if(roleService.save(role) == null){
return Result.error(CodeMsg.ADMIN_ROLE_ADD_ERROR);
}
log.info("添加角色【"+role+"】");
operaterLogService.add("添加角色【"+role.getName()+"】");
return Result.success(true);
}
/**
* 角色编辑页面
* @param id
* @param model
* @return
*/
@RequestMapping(value="/edit",method=RequestMethod.GET)
public String edit(@RequestParam(name="id",required=true)Long id,Model model){
List<Menu> findAll = menuService.findAll();
model.addAttribute("topMenus",MenuUtil.getTopMenus(findAll));
model.addAttribute("secondMenus",MenuUtil.getSecondMenus(findAll));
model.addAttribute("thirdMenus",MenuUtil.getThirdMenus(findAll));
Role role = roleService.find(id);
model.addAttribute("role", role);
model.addAttribute("authorities",JSONArray.toJSON(role.getAuthorities()).toString());
return request.getSession();
}
return null;
}
/**
* 获取指定键的值
* @param key
* @return
*/
public static Object get(String key){
HttpSession session = getSession();
if(session != null){
return session.getAttribute(key);
}
return null;
}
/**
* 设置session值
* @param key
* @param object
*/
public static void set(String key,Object object){
HttpSession session = getSession();
if(session != null){
session.setAttribute(key,object);
}
}
/**
* 获取当前登录的用户
* @return
*/
public static User getLoginedUser(){
HttpSession session = getSession();
if(session != null){
Object attribute = session.getAttribute(SessionConstant.SESSION_USER_LOGIN_KEY);
return attribute == null ? null : (User)attribute;
}
return null;
}
}
package com.yuanlrc.base.controller.common;
/**
* 图片统一查看控制器
*/
e.printStackTrace();
}
return mac.toUpperCase();
}
public static boolean authOrder(String orderSn, String phone) {
//
return true;
}
public static String readFileToString(File file) {
String string = "";
if (file != null) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
string += line;
}
br.close();
} catch (Exception e) {
// TODO: handle exception
}
}
return string;
}
}
package com.yuanlrc.base.controller.admin;
}
if(menu.getId() == null){
Result.error(CodeMsg.ADMIN_MENU_ID_EMPTY);
}
//用统一验证实体方法验证是否合法
CodeMsg validate = ValidateEntityUtil.validate(menu);
if(validate.getCode() != CodeMsg.SUCCESS.getCode()){
return Result.error(validate);
}
if(menu.getParent() != null){
if(menu.getParent().getId() == null){
menu.setParent(null);
}
}
Menu existMenu = menuService.find(menu.getId());
if(existMenu == null){
Result.error(CodeMsg.ADMIN_MENU_ID_ERROR);
}
//表示验证都通过,开始添加数据库
existMenu.setIcon(menu.getIcon());
existMenu.setName(menu.getName());
existMenu.setParent(menu.getParent());
existMenu.setSort(menu.getSort());
existMenu.setUrl(menu.getUrl());
existMenu.setButton(menu.isButton());
existMenu.setShow(menu.isShow());
if(menuService.save(existMenu) == null){
Result.error(CodeMsg.ADMIN_MENU_ADD_ERROR);
}
//数据库添加操作成功,记录日志
operaterLogService.add("编辑菜单信息【" + existMenu + "】");
return Result.success(true);
}
/**
* 删除菜单信息
* @param request
* @param id
* @return
*/
@RequestMapping(value="/delete",method=RequestMethod.POST)
@ResponseBody
public Result<Boolean> delete(@RequestParam(name="id",required=true)Long id){
try {
menuService.delete(id);
} catch (Exception e) {
return Result.error(CodeMsg.ADMIN_MENU_DELETE_ERROR);
}
//数据库添加操作成功,记录日志
operaterLogService.add("删除菜单信息,菜单ID【" + id + "】");
return Result.success(true);
}