是啾咪呀。

又惘又怠

人脸识别员工考勤系统

Java课设

成员 博客园链接
苏雅琴 https://www.cnblogs.com/-sushi/p/14342837.html 组长
王奕 https://www.cnblogs.com/w60-06/p/14342832.html
黄嘉欣 https://www.cnblogs.com/springxinxin/p/14342442.html

git链接
https://gitee.com/smyn77/javatest.git
环境

MYSQL

Tomcat9

Maven

框架

MVC:模型(dao、service) 视图(jsp) 控制层(Servlet)

Model2时代

Model2吧一个项目分成三部分,包括视图,控制,模型

  • 用户发请求

  • Servlet接受请求,并调用对应的业务逻辑方法。

  • 业务处理王弼,返回更新后的数据给Servlet

  • servlet转向JSP,由JSP来渲染页面

职责分析:

Controller

  • 取得表单数据
  • 调用业务逻辑(Service)
  • 转向指定页面

Model:模型

  • 业务逻辑
  • 保存数据的状态

View视图

Model2这样不仅提高代码的复用率与项目的扩张性,且大大降低了了项目的维护成本。

SpringMVC——做后台服务

SpringMVC是Spring Framework的一部分,是基于java实现MVC的轻量级Web框架

特点:

  • 轻量级,简单易学,不用导入很多jar包

  • 高校,基于请求响应的MVC框架

  • 与Spring兼容性好,无缝结合

  • 约定优于配置

  • 功能强大:RESTful(体现在url)、数据验证、格式化、本地化、主题

  • 简洁灵活

Spring:容器,可以将SpringMVC中所有要用到的bean,注册到Spring中

Spring(容器)的web框架围绕DispatcherServlet设计,DispatcherServlet的作用是将请求分发到不同的处理器上,DispatcherServlet本质也是Servlet,所以里面也会由基本的doPost,doGet方法,只是我们不用再写了,它帮我处理好了,所以在代码的管理上,更加方便。

SpringMvc原理:

当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图结果,将结果返回给中心控制器,再将结果返回给请求者。

  • 配置文件

  • 编写操作业务的Controller,要么实现Controller接口,要么增加注解

  • 需要放回一个ModelAndView,模型负责装数据,封视图(视图负责转到哪里页面)

pubic class HelloController inplements Controller{
	public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception{
	//ModelAndView模型和视图
	ModelAndView mv=new ModelAndView();
	//封装对象,放在ModelAndView中
	mv.addObject("msg","Hello!");
	//封装要跳转的视图,放在ModelAndView中
	mv.setViewName("hello");//:/WEB-INF/jsp/hello.jsp
	}
}

请求指定/hello->web-xml->springmvc-servlet配置文件

MyBatis——做数据库连接Mysql

它能干什么?

MyBatis能帮助我们快速开发基于Java + 数据库的程序,能帮助我们快速映射POJO对象和数据库中的数据 同时支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。

项目搭建

web.xml

<?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"
         version="4.0">
    <!--    驻车DispatcherServlet-->
<!--    所有的请求都要经过下面-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 加载/WEB-INF/[servlet1-name]-servlet.xml -->
        <!--        关联一个springmvc的配置文件[servlet1-name]-servlet.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
<!--        启动级别:1和服务器一起启动-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--    /匹配所有的请求,不包括.jsp-->
    <!--    /*匹配所有的请求,包括.jsp-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--    过滤器-->
    <filter>
        <filter-name>CharaterEncodingFilter</filter-name>
        <filter-class>cn.com.filter.CharaterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharaterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--    用户登录过滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>cn.com.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/WEB-INF/jsp/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--    web页面-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>cn.com.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>
    <!--    设置欢迎界面-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>cn.com.servlet.LoginoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/jsp/logout.do</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>PwdModifyServlet</servlet-name>
        <servlet-class>cn.com.servlet.PwdModifyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PwdModifyServlet</servlet-name>
        <url-pattern>/jsp/pwdmodify.do</url-pattern>
    </servlet-mapping>

</web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
">


    <!--    import只能导入spring文件-->
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>


</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration >
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
<!--    配置数据源,交给Spring去做-->
    <typeAliases>
        <package name="cn.com.dto"/>
    </typeAliases>
    <mappers>
<!--        <package name="cn.com.dao"/>-->
<!--        <mapper resource="cn.com.dao.EmpMapper.xml"/>-->
<!--        <mapper resource="cn.com.dao.EmpMapper"/>-->
<!--        <mapper resource="cn.com.dao.AskoffMapper"/>-->
<!--        <mapper resource="cn.com.dao.DeptMapper"/>-->
        <mapper resource="cn/com/dao/empMapper.xml"></mapper>
        <mapper resource="cn/com/dao/AskoffMapper.xml"></mapper>
        <mapper resource="cn/com/dao/DeptMapper.xml"></mapper>
    </mappers>


</configuration>

spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
    <!--关联数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
<!--    连接池
-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
<!--            c3p0连接池的私有属性-->
            <property name="maxPoolSize" value="30"/>
            <property name="minPoolSize" value="10"/>
<!--            关闭连接后不自动commit-->
            <property name="autoCommitOnClose" value="false"/>
<!--            获取连接超出时间-->
            <property name="checkoutTimeout" value="10000"/>
<!--            当获取连接失败重试次数-->
            <property name="acquireRetryAttempts" value="4"/>

        </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
<!--    绑定mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>

    </bean>

<!--    配置dao接口扫描包,动态的实现了dao接口可以注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        注入sqlSeesionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--        要扫描的dao接口包-->
        <property name="basePackage" value="cn.com.dao"/>
<!--       -->
    </bean>



</beans>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
<!--    注解驱动-->
    <mvc:annotation-driven />
<!--    静态资源过滤-->
    <mvc:default-servlet-handler/>
<!--    扫描包-->
    <context:component-scan base-package="cn.com.controller"/>
<!---视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

spring-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/aop
   https://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/cache/spring-cache.xsd">

<!--扫描service下的包-->
    <context:component-scan base-package="cn.com.service"/>
<!--    将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
   <bean id="EmpService1Impl" class="cn.com.service.impl.EmpService1Impl">
       <property name="empMapper" ref="empMapper"/>
   </bean>
    <bean id="DeptServiceImpl" class="cn.com.service.impl.DeptServiceImpl">
        <property name="deptMapper" ref="deptMapper"/>
    </bean>
    <bean id="AskoffServiceImpl" class="cn.com.service.impl.AskoffServiceImpl">
        <property name="askoffMapper" ref="askoffMapper"/>
    </bean>
<!--    声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--   注入数据源
-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

        <!--    4.aop事务支持-->
<!--    &lt;!&ndash;    结合AOP实现事务的植入&ndash;&gt;-->
<!--    &lt;!&ndash;    配置事务的通知&ndash;&gt;-->
<!--            <tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!--    &lt;!&ndash;            给那些方法配置事务&ndash;&gt;-->
<!--    &lt;!&ndash;            配置事务的传播特性 new propagetion&ndash;&gt;-->
<!--                <tx:attributes>-->
<!--                    <tx:method name="*" propagation="REQUIRED"/>-->
<!--                </tx:attributes>-->
<!--            </tx:advice>-->
<!--    &lt;!&ndash;    配置事务切入&ndash;&gt;-->
<!--        <aop:config>-->
<!--            <aop:pointcut id="txPointCut" expression="execution(* cn.com.dao.*.*(..))"/>-->
<!--            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>-->
<!--        </aop:config>-->
</beans>

项目框架

项目UML类图


项目目录

WEB项目

类的实现

员工类

package cn.com.service;

import cn.com.dto.Employ;
import cn.com.dto.Employee;

//编写业务层代码
public interface EmpService {
    //用户登录
    public Employ login(String name,String pwd);

    //根据用户id修改密码
    public int updataPwd(int empid,String pwd);

    //



}

类的实现

package cn.com.service.impl;

import cn.com.dao.BaseDao;
import cn.com.dao.EmpDao;
import cn.com.dao.impl.EmpDaoImpl;
import cn.com.dto.Employ;
import cn.com.service.EmpService;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
//业务层代码都会调用到Dao层,所以我们要引入Dao层

@Service
public class EmpServiceImpl implements EmpService {
    private static EmpDao empDao;
    static {
        empDao=new EmpDaoImpl();
    }
    public EmpServiceImpl(){

    }
    @Override
    public Employ login(String name, String pwd) {
        System.out.println("进入serviceimp的login方法"+name+"=="+pwd);
        Connection connection=null;
        Employ emp=null;
        try {
            connection= BaseDao.getConnection();
            //通过业务层调用对应的具体的数据库操作
            emp=empDao.getLoginEmp(connection,name,pwd);
            System.out.println(emp);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }

        return emp;
    }

    @Override
    public int updataPwd(int empid, String pwd) {
        Connection connection=null;
        int flag=0;
        try {
            connection=BaseDao.getConnection();
            if(empDao.updatePwd(connection,empid,pwd)>0){
                flag=1;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }

        return flag;
    }

    @Test
    public void test(){
        EmpServiceImpl empService=new EmpServiceImpl();
        Employ admin=empService.login("admin","123456");

        System.out.println(admin);
    }
}

EmpService

package cn.com.service;

import cn.com.dto.Employ;
import cn.com.dto.Employee;

//编写业务层代码
public interface EmpService {
    //用户登录
    public Employ login(String name,String pwd);

    //根据用户id修改密码
    public int updataPwd(int empid,String pwd);

    //



}

servlet

//登陆类
package cn.com.servlet;

import cn.com.dto.Employ;
import cn.com.service.EmpService;
import cn.com.service.impl.EmpServiceImpl;
import cn.com.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//Servlet:控制层:调用业务层代码
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("name");
        String password=req.getParameter("pwd");
        System.out.println(username+":"+password);

        //和数据库中的账号和密码进行对比调用业务层
        EmpService empService=new EmpServiceImpl();
        Employ emp=empService.login(username,password);//这里把登录的人查出来
        if(emp!=null){//查有此人
            //将用户信息放到Seesion中
            req.getSession().setAttribute(Constants.USER_SESSION,emp);
            //跳转到主页
            if(emp.getRole().equals("管理部门")){
                System.out.println("能跳的管理员页面");
                 resp.sendRedirect("/jsp/rootframe.jsp");}
            else{
                resp.sendRedirect("/jsp/empframe.jsp");
            }

        }else{//无此人,转发会登录页面,顺带提示用户名或密码错误
            req.setAttribute("error","用户名和密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
//登出类
package cn.com.servlet;

import cn.com.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

使用mybateis+spring框架写的

(以员工类为例,其它一样)

Employee

package cn.com.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

//
//import lombok.AllArgsConstructor;
//import lombok.Data;
//import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {

    private int empID;
    private String name;
    private String sex;
    private int age;
    private String password;
    private String role;
}

EmpMapper

package cn.com.dao;
import cn.com.dto.Employee;


import java.util.List;


public interface EmpMapper {
    //增加一个员工
    int addEmp(Employee employee);

    //删除一个员工
    int deleteEmp(int empId);

    //更新一个员工
    int updataEmp(Employee employee);

    //查询一个员工
    Employee queryEmpById(int empId);

    //查询全部员工
    List<Employee> queryAllEmp();

    //通过名字查员工
    Employee queryEmpByName(String empName);

}

empMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.dao.EmpMapper">
        <insert id="addEmp" parameterType="Employee">
            insert into face_attendance.emp(empID,name,sex,age,role,password)
            values (#{empID},#{name},#{sex},#{age},#{role},#{password});
        </insert>

        <delete id="deleteEmp" parameterType="int">
            delete from face_attendance.emp
            where empID = #{empID}
        </delete>

        <update id="updataEmp" parameterType="Employee">
            update face_attendance.emp
            set empID=#{empID},name=#{name},sex=#{sex},age=#{age},role=#{role},password=#{password}
                where empID = #{empID};
        </update>

        <select id="queryEmpById" resultType="Employee">
            select * from face_attendance.emp
            where empID = #{empID}
        </select>

        <select id="queryAllEmp" resultType="Employee">
            select * from face_attendance.emp
        </select>
        <select id="queryEmpByName" resultType="Employee">
            select * from face_attendance.emp where name=#{empName}
        </select>
</mapper>

EmpService1

package cn.com.service;

import cn.com.dto.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmpService1 {

    //增加一个员工
    int addEmp(Employee employee);

    //删除一个员工
    int deleteEmp(int id);

    //更新一个员工
    int updataEmp(Employee employee);

    //查询一个员工
    Employee queryEmpById(int id);

    //查询全部员工
    List<Employee> queryAllEmp();

    Employee queryEmpByName(String empName);
}

EmpService1Impl

package cn.com.service.impl;

import cn.com.dao.EmpMapper;
import cn.com.dto.Employee;
import cn.com.service.EmpService1;

import java.util.List;

public class EmpService1Impl implements EmpService1 {

    private EmpMapper empMapper;
    public void setEmpMapper(EmpMapper empMapper) {
        this.empMapper=empMapper;
    }
    @Override
    public int addEmp(Employee employee) {
        return empMapper.addEmp(employee);
    }

    @Override
    public int deleteEmp(int id) {
        return empMapper.deleteEmp(id);
    }

    @Override
    public int updataEmp(Employee employee) {
        return empMapper.updataEmp(employee);
    }

    @Override
    public Employee queryEmpById(int id) {
        return empMapper.queryEmpById(id);
    }

    @Override
    public List<Employee> queryAllEmp() {
        return empMapper.queryAllEmp();
    }

    @Override
    public Employee queryEmpByName(String empName) {
        return empMapper.queryEmpByName(empName);
    }

}

Controller

package cn.com.controller;

import cn.com.dto.Department;
import cn.com.dto.Employee;
import cn.com.service.DeptService;
import cn.com.service.EmpService1;
import cn.com.service.impl.EmpService1Impl;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
@RequestMapping("/fun")
public class EmpController {
    @Autowired
    @Qualifier("EmpService1Impl")
    private EmpService1 empService1;


    //查询员工信息
    @RequestMapping("/emp_mg")
    public String list(Model model){
        System.out.println("emp_mg");
        List<Employee>list=empService1.queryAllEmp();
       //往前端显示数据
        model.addAttribute("list",list);
        return "emp_mg";
    }
    //跳转到增加员工页面
    @RequestMapping("/toAddEmp")
    public String toAddEmp(){
        return "addEmp";
    }
    //添加员工的请求
    @RequestMapping("/addEmp")
    public String addEmp(Employee emp){
        empService1.addEmp(emp);
        Department department=new Department();
        return "redirect:/fun/emp_mg";
    }
    //跳转到修改页面
    @RequestMapping("/toUpdate")
    public String toUpdateEmp(Integer empid,Model model){
        Employee emp=empService1.queryEmpById(empid);
        model.addAttribute("Qemp",emp);
        return "updateEmp";
    }
    //修改员工信息
    @RequestMapping("/updateEmp")
    public String updateEmp(Employee emp){
        empService1.updataEmp(emp);
        return "redirect:/fun/emp_mg";
    }
    //删除员工
    @RequestMapping("/delEmp")
    public String deleteEmp(Integer empid){
        empService1.deleteEmp(empid);
        return "redirect:/fun/emp_mg";
    }
    //查询员工
    @RequestMapping("/queryEmp")
    public String queryEmp(String queryEmpname, Model model){
        Employee employee=empService1.queryEmpByName(queryEmpname);
        List<Employee>list=new ArrayList<Employee>();
        list.add(employee);
        if(employee==null){
            list=empService1.queryAllEmp();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list",list);
        return "emp_mg";

    }


}

CharacterEncodingFilter

package cn.com.filter;


import javax.servlet.*;
import java.io.IOException;

public class CharaterEncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}

SysFilter

package cn.com.filter;


import cn.com.dto.Employ;
import cn.com.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //过滤器,从session中获取用户
        Employ emp=(Employ) request.getSession().getAttribute(Constants.USER_SESSION);
        if(emp==null){
            response.sendRedirect("/jsp/error.jsp");
        }else{
            chain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}

人脸识别实现类

package cn.com.dao.impl;

import cn.com.dao.FaceMapper;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;

public class FaceMapperImpl implements FaceMapper {
//    private static AipFace client;
//    private static HashMap<String, String> options=new HashMap<>();
//    private static String GROUP_Id;
//    private static String Image_Type;
//    private static String APP_ID;
//    private static String API_KEY;
//    private static String SECRET_KEY;
//    static {
//
//        //2.参数设置
//        //图片质量
//        options.put("quality_control", "NORMAL");
//        //活体检测
//        options.put("liveness_control", "LOW");
//        Properties pro = new Properties();
//        InputStream in = FaceController.class.getClassLoader().getResourceAsStream("conf.properties");
//        //  pro.load(in);
//        //1.创建java代码和百度云交互的client对象
//        APP_ID=pro.getProperty("appId");
//        API_KEY=pro.getProperty("apiKey");
//        SECRET_KEY=pro.getProperty("secretKey");
//        System.out.println(APP_ID+"=="+API_KEY+"==="+SECRET_KEY);
//        client=new AipFace(APP_ID,API_KEY,SECRET_KEY);
//
//        GROUP_Id=pro.getProperty("groupId");
//        Image_Type=pro.getProperty("imageType");
//    }
@Test
public void test() throws IOException {
        AipFace client=new AipFace("xxx","xxx","xxx");
        HashMap<String,String >options=new HashMap<>();
        options.put("quality_control", "NORMAL");
        //活体检测
        options.put("liveness_control", "LOW");
        String path="D:\\Idealwork\\huge.jpg";
        byte[]bytes= Files.readAllBytes(Paths.get(path));
        System.out.println(bytes);
        String image= Base64Util.encode(bytes);

        JSONObject res=client.addUser(image,"BASE64","face","1010",options);
        System.out.println(res);
}
    @Override
    public String faceRegister(String empId, String image) {
        AipFace client=new AipFace("xxx","xxx","xxx");
        HashMap<String,String >options=new HashMap<>();
        options.put("quality_control", "NORMAL");
        //活体检测
        options.put("liveness_control", "LOW");
        System.out.println(empId+"----和image");
        //3.构造图片
        //String path="";
        //上传的图片  两种格式:url地址,Base64字符串形式
        //byte[]bytes=Files.readAllBytes(Paths.get(path));
        //String image=Base64Util.encode(bytes);
        //4.调用api方法完成人脸注册
        //参数     图片url或base64   图片类型   固定的某个字符串   用户id  hashmap的基本参数
     //   JSONObject res=client.addUser(image, Image_Type, GROUP_Id, empId, options);
        JSONObject res=client.addUser(image,"BASE64","face",empId,options);

        System.out.println("faceRegister"+res.toString());
//        Integer errorCode=res.getInt("error_code");

//        return errorCode==0?true:false;
        //System.out.println(res.toString());
        return "null";
    }

    @Override
    public Boolean faceCheck(String image) {
        //String path="";
        //上传的图片  两种格式:url地址,Base64字符串形式
        //byte[]bytes=Files.readAllBytes(Paths.get(path));
        //String image=Base64Util.encode(bytes);

        //调用人脸检测
        AipFace client=new AipFace("xxx","xxx","xxx");
        HashMap<String,String >options=new HashMap<>();
        options.put("quality_control", "NORMAL");
        //活体检测
        options.put("liveness_control", "LOW");
 //       System.out.println(empId+"----和image");

        JSONObject  res=client.detect(image, "BASE64", null);
        //System.out.println(res.toString(2));
        if(res.has("error_code")&&res.getInt("erroe_code")==0) {
            JSONObject resultObject=res.getJSONObject("result");
            Integer faceNum=resultObject.getInt("face_num");
            return faceNum==1?true:false;
        }else {
            return false;
        }
    }

    @Override
    public String faceSearch(String image) {
        System.out.println("人脸搜索中");
        //String path="";
        //byte[]bytes=Files.readAllBytes(Paths.get(path));
        //String image=Base64Util.encode(bytes);
        //调用人脸搜索
        AipFace client=new AipFace("xxx","xxx","xxx");
        HashMap<String,String >options=new HashMap<>();
        options.put("quality_control", "NORMAL");
        //活体检测
        options.put("liveness_control", "LOW");


        JSONObject  res=client.search(image, "BASE64", "face", null);
        System.out.println(res);

        if(res.has("error_msg")&&res.getInt("error_code")==0) {
            System.out.println("人脸搜索成功");
            JSONObject resultObject=res.getJSONObject("result");
            JSONArray userList=resultObject.getJSONArray("user_list");
            System.out.println(userList);
            if(userList.length()>0) {
                JSONObject user=userList.getJSONObject(0);
                double score=user.getDouble("score");
                if(score>80) {
                    return user.getString("user_id");
                }
            }

        }
        return null;
        //System.out.println(res.toString(2));
    }

    @Override
    public Boolean faceUpdate(String userId, String image) {
        //2.参数设置
        //HashMap<String, String>options=new HashMap<>();
        //图片质量
        //options.put("quality_control", "NORMAL");
        //活体检测
        //options.put("liveness_control", "LOW");
        //3.构造图片
        //String path="";
        //上传的图片  两种格式:url地址,Base64字符串形式
        //byte[]bytes=Files.readAllBytes(Paths.get(path));
        //String image=Base64Util.encode(bytes);
        //4.调用api方法完成人脸注册
        //参数     图片url或base64   图片类型   固定的某个字符串   用户id  hashmap的基本参数
        AipFace client=new AipFace("xxx","xxx","xxx");
        HashMap<String,String >options=new HashMap<>();
        options.put("quality_control", "NORMAL");
        //活体检测
        options.put("liveness_control", "LOW");
//        System.out.println(empId+"----和image");
        JSONObject res = client.updateUser(image, "BASE64", "face", "1000", options);
        //返回结果总error_code=“0”表示成功
        Integer errorCode = res.getInt("error_code");
        return errorCode == 0 ? true : false;
        //System.out.println(res.toString());
    }
}

阿里巴巴代码扫描

已处理

posted @ 2021-01-29 09:01  是啾咪呀。  阅读(613)  评论(1编辑  收藏  举报