一看就懂的Spring+MyBatis项目实战,代码过多,图片过多,但是逻辑简单,一看就懂^_^

好的,今个天气不错,还是没有复试消息,怎么说呢?
招生老师是不是想太多了?
直接线上走个过场不就好了?
本就是多事之秋,线上的话又没有可控的防作弊手段。
那么好了,我这种实力一般,成绩一般,还没有后台的小兄弟咋办?
等着被欺负?
啊看来只能如此了。
望一切顺利,早日入学。世界和平
最可怕的事情是不是在A国已经开始了?   
人民群众的生命健康,高于一切!                                                                                                                                          

人员信息管理系统
前置技能:
MyBatis、Spring、Servlet
Mysql
主要技术:
Servlet、JSP进行用户请求和相应的处理
Spring IOC、Spring AOP
MyBatis把SQL从代码证剥离出去
MyBatis+Spring整合
登录界面–》三部分主界面,各个模块的导航,和显示区还有上部logo
ok,先来看下具体长什么样吧
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
还有具体的效果,回头慢慢看吧。
三层架构
持久层–MyBatis
表现层–Servlet+JSP
Spring–管理对象和切面处理
基于MVC模式
视图–JSP
模型–JavaBean
控制器–Servlet+JavaBean

什么时候用配置什么时候用注解
  关于配置和注解
    配置:
	     非Java代码
		 便于后期维护
	注解:
	     灵活、精简--用于简化配置
		 写在Java文件中
	应用场合
	      一处配置与多处注解---用配置
		  代码精简--用注解
		  注解需要复杂的非Java代码---用配置,MyBatis的注解不好,用配置比较好

数据库设计
部门:编号,名称,位置
员工:编号,账户,密码,状态,所属部门,姓名,性别,身份证号码,入职时间,离职时间,出生日期,备注
日志:操作时间,类型,操作人,模块,操作,结果
建表语句如下

drop database if exists sm;

create database sm;

use sm;


create table department(
	id int primary key auto_increment,
	name varchar(20) not null,
	address varchar(100)
);

create table staff(
	id int primary key auto_increment,
	account varchar(20) not null,
	password varchar(20) not null,
	status varchar(10) not null,
	did int,
	name varchar(20),
	sex char(2),
	id_number char(18),
	work_time datetime,
	leave_time datetime,
	born_date date,
	info varchar(200)
);

create table log(
	opr_time datetime not null,
	type varchar(10) not null,
	operator varchar(20) not null,
	moudle  varchar(20) not null,
	operation  varchar(20) not null,
	result  varchar(100) not null
);

alter table staff add constraint fk_staff_dep foreign key(did) references department(id);

创建项目

 sm
   --父module
   --全局定义和组织
 sm_service
   --持久层、业务层
   --MyBatis依赖、Spring依赖
 sm_web
   --表现层
   --Servlet依赖
Spring全局配置
Spring整合MyBatis
   Spring管理MyBatis的相关对象
声明式事务
全局扫描
工具类
编码过滤器
核心控制器
  Servlet对象由Web容器管理,Service对象由IOC容器管理
  Web容器--》核心控制器--》IOC容器

项目结构如下图:
在这里插入图片描述
注意一共要创建三个maven,当第一个maven项目创建完后,剩下的两个子maven项目在第一个maven项目那里建立。都是空的maven项目,除了最后一个sm_web选择一个web模板,其余都是空的maven项目
包结构如下
在这里插入图片描述
接下来我们需要引入依赖。
对于父module的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jjyu</groupId>
    <artifactId>sm</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>sm_service</module>
        <module>sm_web</module>
    </modules>
<properties>
    <spring.version>4.0.2.RELEASE</spring.version>
</properties>

</project>

sm_service的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>sm</artifactId>
        <groupId>com.jjyu</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sm_service</artifactId>
    <packaging>jar</packaging>
    <dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.0</version>
        </dependency>
        <!--事务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>


</project>

sm_web的pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>sm</artifactId>
        <groupId>com.jjyu</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sm_web</artifactId>
    <packaging>war</packaging>

    <name>sm_web Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.jjyu</groupId>
            <artifactId>sm_service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>sm_web</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

包结构做好了,然后引入了依赖
我们接下来需要配置Spring的配置文件了
也就是Spring的xml文件
具体配置如下,我们将MyBatis整合在其中

<?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/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--Spring整合MyBatis-->
    <!--数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/sm?useUnicode=true&amp;charcterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--Session工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.jjyu.sm.entity"/>
    </bean>
    <!--持久化对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.jjyu.sm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
    <!--声明式事务-->
    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="search*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--植入-->
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.jjyu.sm.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
    <!--全局扫描-->
    <context:component-scan base-package="com.jjyu.sm"/>
    <aop:aspectj-autoproxy/>
</beans>

接下来是四个全局过滤器都在sm_web的global包内,自行建立
用于分析URL等操作的
具体代码如下

public class DispatcherServlet extends GenericServlet {
    //加载IOC容器
   private ApplicationContext context;
   public void init() throws ServletException {
       super.init();
       context=new ClassPathXmlApplicationContext("spring.xml");
   }
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
       HttpServletRequest request= (HttpServletRequest)servletRequest;

        HttpServletResponse response=(HttpServletResponse)servletResponse;
        /**
         * /staff/add.do   /login.do
         * staffContoller
         * public void add(HttpServletRequest request,HttpServletResponse response);
         */
        String path=request.getServletPath().substring(1);
        String beanName=null;
        String methodName=null;
        int index=path.indexOf("/");
        if(index!=-1){
            beanName=path.substring(0,index)+"Controller";
            methodName=path.substring(index+1,path.indexOf(".do"));
        }else{
            beanName="selfController";
            methodName=path.substring(0,path.indexOf(".do"));
        }

//        ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
        Object obj=context.getBean(beanName);
        try {
            Method method=obj.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(obj,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
public class EncodingFilter implements Filter {
    private String encoding="UTF-8";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
      if( filterConfig.getInitParameter("ENCODING")!=null)
      {
          encoding=  filterConfig.getInitParameter("ENCODING");
      }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding(encoding);
        servletResponse.setCharacterEncoding(encoding);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        encoding=null;

    }
}
@Component
@Aspect
public class LogAdvice {
    @Autowired
    private LogService logService;
    @AfterReturning("execution(* com.jjyu.sm.controller.*.*(..)) && !execution(* com.jjyu.sm.controller.SelfController.*(..)) && !execution(* com.jjyu.sm.controller.*.to*(..))")
    public void operationLog(JoinPoint joinPoint){
        Log log = new Log();
        log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());
        log.setOperation(joinPoint.getSignature().getName());
        HttpServletRequest request =(HttpServletRequest) joinPoint.getArgs()[0];
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("USER");
        Staff staff =(Staff)obj;
        log.setOperator(staff.getAccount());
        log.setResult("成功");
        logService.addOperationLog(log);
    }
    @AfterThrowing(throwing ="e",pointcut ="execution(* com.jjyu.sm.controller.*.*(..)) && !execution(* com.jjyu.sm.controller.SelfController.*(..))")
    public void systemLog(JoinPoint joinPoint,Throwable e){
        Log log = new Log();
        log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());
        log.setOperation(joinPoint.getSignature().getName());
        HttpServletRequest request =(HttpServletRequest) joinPoint.getArgs()[0];
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("USER");
        Staff staff =(Staff)obj;
        log.setOperator(staff.getAccount());
        log.setResult(e.getClass().getSimpleName());
        logService.addSystemLog(log);
    }
    @After("execution(* com.jjyu.sm.controller.SelfController.login(..))")
    public void loginLog(JoinPoint joinPoint){
        log(joinPoint);
    }
    @Before("execution(* com.jjyu.sm.controller.SelfController.logout(..))")
    public void logoutLog(JoinPoint joinPoint){
        log(joinPoint);
    }
    private void log(JoinPoint joinPoint){
        Log log = new Log();
        log.setMoudle(joinPoint.getTarget().getClass().getSimpleName());
        log.setOperation(joinPoint.getSignature().getName());
        HttpServletRequest request =(HttpServletRequest) joinPoint.getArgs()[0];
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("USER");
        if(obj==null){
            log.setOperator(request.getParameter("account"));
            log.setResult("失败");
        }else {
            Staff staff = (Staff) obj;
            log.setOperator(staff.getAccount());
            log.setResult("成功");
        }
        logService.addLoginLog(log);
    }
}
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String path=request.getServletPath();
        if(path.toLowerCase().indexOf("login")!=-1){
            filterChain.doFilter(request,response);
        }else {
            HttpSession session=request.getSession();
            Object obj=session.getAttribute("USER");
            if(obj!=null){
                filterChain.doFilter(request,response);
            }else{
                response.sendRedirect(request.getContextPath()+"/toLogin.do");
            }
        }
    }

    @Override
    public void destroy() {

    }
}


功能实现

具体的页面代码不在此展示,不然太多了。都在评论区
冗余,这都很影响阅读体验了
能看到这里说明你还是可以的,加油!
就剩最后一丢丢了
接下来所有文件的存放位置都不说了
都在图里
在这里插入图片描述
在这里插入图片描述

部门管理
部门信息的增删改查
为啥先做这块?因为简单,部门就三个属性,简单上手。
步骤:
-实体类

public class Department {
    private Integer id;
    private String name;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

	   -Dao接口和Sql映射文件
@Repository("departmentDao")
public interface DepartmentDao {
    void insert(Department department);
    void delete(Integer id);
    void update(Department department);
    Department selectById(Integer id);
    List<Department> selectAll();

}
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jjyu.sm.dao.DepartmentDao">
    <resultMap id="resultMap" type="Department">
        <id property="id" column="id" javaType="Integer"/>
        <result property="name" column="name" javaType="String"/>
        <result property="address" column="address" javaType="String"/>
    </resultMap>

    <insert id="insert" parameterType="Department" useGeneratedKeys="true">
        insert into department(name,address) values(#{name},#{address})
    </insert>
    <delete id="delete" parameterType="Integer">
        delete from department where id=#{id}
    </delete>
    <update id="update" parameterType="Department">
        update department set name=#{name},address=#{address} where id=#{id}
    </update>
    <select id="selectById" parameterType="Integer" resultMap="resultMap">
        select * from department where id=#{id}
    </select>
    <select id="selectAll" resultMap="resultMap">
        select * from department
    </select>
</mapper>
	   -Service接口及其实现类		   
public interface DepartmentService {
    void add(Department department);
    void remove(Integer id);
    void edit(Department department);
    Department get(Integer id);
    List<Department> getAll();
}
@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentDao departmentDao;
    public void add(Department department) {
        departmentDao.insert(department);
    }

    public void remove(Integer id) {
        departmentDao.delete(id);
    }

    public void edit(Department department) {
        departmentDao.update(department);
    }

    public Department get(Integer id) {
        return departmentDao.selectById(id);
    }

    public List<Department> getAll() {
        return departmentDao.selectAll();
    }
}

	   -控制器		
@Controller("departmentController")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    // /department/list.do     /department_list.jsp
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Department> list=departmentService.getAll();
        request.setAttribute("LIST",list);
        request.getRequestDispatcher("../department_list.jsp").forward(request,response);
    }
    public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("../department_add.jsp").forward(request,response);
    }
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       String name=request.getParameter("name");
        String address=request.getParameter("address");
        Department department=new Department();
        department.setAddress(address);
        department.setName(name);

        departmentService.add(department);
        System.out.println("sucess");
        //重定向
        response.sendRedirect("list.do");
    }
    public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      Integer id=Integer.parseInt(request.getParameter("id"));
        Department department=departmentService.get(id);
        request.setAttribute("OBJ",department);
        request.getRequestDispatcher("../department_edit.jsp").forward(request,response);
    }
    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id=Integer.parseInt(request.getParameter("id"));
        String name=request.getParameter("name");
        String address=request.getParameter("address");
        Department department=new Department();
        department.setId(id);
        department.setAddress(address);
        department.setName(name);

        departmentService.edit(department);
        System.out.println("sucess");
        //重定向
        response.sendRedirect("list.do");
    }
    public void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id=Integer.parseInt(request.getParameter("id"));
        departmentService.remove(id);
        response.sendRedirect("list.do");
    }


}

-页面
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

员工管理
员工信息的增删改查
关注点:
–员工与部门的关联关系
–默认登录密码
步骤:
-实体类

public class Staff {
    private Integer id;
    private String account;
    private String password;
    private String status;
    private Integer did;
    private String name;
    private String sex;
    private String idNumber;
    private Date workTime;
    private Date LeaveTime;
    private Date bornDate;
    private String info;
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Integer getDid() {
        return did;
    }

    public void setDid(Integer did) {
        this.did = did;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    public Date getWorkTime() {
        return workTime;
    }

    public void setWorkTime(Date workTime) {
        this.workTime = workTime;
    }

    public Date getLeaveTime() {
        return LeaveTime;
    }

    public void setLeaveTime(Date leaveTime) {
        LeaveTime = leaveTime;
    }

    public Date getBornDate() {
        return bornDate;
    }

    public void setBornDate(Date bornDate) {
        this.bornDate = bornDate;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

-Dao接口和Sql映射文件

@Repository("staffDao")
public interface StaffDao {
    void insert(Staff staff);
    void delete(Integer id);
    void update(Staff staff);
    Staff selectById(Integer id);
    List<Staff> selectAll();

}
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jjyu.sm.dao.StaffDao">
    <resultMap id="resultMap" type="Staff">
        <id property="id" column="id" javaType="Integer"/>
        <result property="account" column="account" javaType="String"/>
        <result property="password" column="password" javaType="String"/>
        <result property="status" column="status" javaType="String"/>
        <result property="did" column="did" javaType="Integer"/>
        <result property="name" column="name" javaType="String"/>
        <result property="sex" column="sex" javaType="String"/>
        <result property="idNumber" column="id_number" javaType="String"/>
        <result property="workTime" column="work_time" javaType="java.util.Date"/>
        <result property="leaveTime" column="leave_time" javaType="java.util.Date"/>
        <result property="bornDate" column="born_date" javaType="java.util.Date"/>
        <result property="info" column="info" javaType="String"/>
        <association property="department" column="did" javaType="Department" select="com.jjyu.sm.dao.DepartmentDao.selectById"/>
    </resultMap>

    <insert id="insert" parameterType="Staff" useGeneratedKeys="true">
        insert into staff(account,password,status,did,name,sex,id_number,work_time,leave_time,born_date,info)
        VALUES ( #{account},#{password},#{status},#{did},#{name},#{sex},#{idNumber}, #{workTime},#{leaveTime},#{bornDate}, #{info})
    </insert>
    <delete id="delete" parameterType="Integer">
        delete from staff where id=#{id}
    </delete>
    <update id="update" parameterType="Staff">
        update staff
        set account=#{account},password=#{password},status=#{status},
        did=#{did},name=#{name},sex=#{sex},id_number=#{idNumber},
        work_time=#{workTime},leave_time=#{leaveTime},born_date=#{bornDate},
        info=#{info}
        where id=#{id}
    </update>
    <select id="selectById" parameterType="Integer" resultMap="resultMap">
        select * from staff where id=#{id}
    </select>
    <select id="selectAll" resultMap="resultMap">
        select * from staff
    </select>
</mapper>
	   -Service接口及其实现类
public interface StaffService {
    void add(Staff staff);
    void remove(Integer id);
    void edit(Staff staff);
    Staff get(Integer id);
    List<Staff> getAll();
}
@Service("staffService")
public class StaffServiceImpl implements StaffService {
     @Autowired
    private StaffDao staffDao;
    public void add(Staff staff) {
        //默认密码
        staff.setPassword("123456");
        staff.setWorkTime(new Date());
        staff.setStatus("正常");
        staffDao.insert(staff);


    }

    public void remove(Integer id) {
        staffDao.delete(id);

    }

    public void edit(Staff staff) {
     staffDao.update(staff);
    }

    public Staff get(Integer id) {
        return staffDao.selectById(id);
    }

    public List<Staff> getAll() {
        return staffDao.selectAll();
    }
}

	   -控制器
@Controller("staffController")
public class StaffController {
    @Autowired
    private StaffService staffService;
    @Autowired
    private DepartmentService departmentService;
    // /department/list.do     /department_list.jsp
    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Staff> list=staffService.getAll();
        request.setAttribute("LIST",list);
        request.getRequestDispatcher("../staff_list.jsp").forward(request,response);
    }
    public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Department> list=departmentService.getAll();
        request.setAttribute("DLIST", list);
        request.getRequestDispatcher("../staff_add.jsp").forward(request,response);
    }
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        String account=request.getParameter("account");
        String name=request.getParameter("name");
        String sex=request.getParameter("sex");
        String idNumber=request.getParameter("idNumber");
        String info=request.getParameter("info");
        Date bornDate=null;
        try {
            bornDate=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("bornDate"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer did=Integer.parseInt(request.getParameter("did"));
        Staff staff=new Staff();
        staff.setAccount(account);
        staff.setBornDate(bornDate);
        staff.setInfo(info);
        staff.setDid(did);
        staff.setName(name);
        staff.setSex(sex);
        staff.setIdNumber(idNumber);
        staffService.add(staff);

        System.out.println("sucess");
        //重定向
        response.sendRedirect("list.do");
    }
    public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      Integer id=Integer.parseInt(request.getParameter("id"));
       Staff staff=staffService.get(id);
        request.setAttribute("OBJ",staff);
        List<Department> list=departmentService.getAll();
        request.setAttribute("DLIST", list);
        request.getRequestDispatcher("../staff_edit.jsp").forward(request,response);
    }
    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id=Integer.parseInt(request.getParameter("id"));
        String account=request.getParameter("account");
        String name=request.getParameter("name");
        String sex=request.getParameter("sex");
        String idNumber=request.getParameter("idNumber");
        String info=request.getParameter("info");
        Date bornDate=null;
        try {
            bornDate=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("bornDate"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer did=Integer.parseInt(request.getParameter("did"));
        Staff staff=staffService.get(id);
        staff.setAccount(account);
        staff.setBornDate(bornDate);
        staff.setInfo(info);
        staff.setDid(did);
        staff.setName(name);
        staff.setSex(sex);
        staff.setIdNumber(idNumber);
        staffService.edit(staff);

        System.out.println("sucess");
        //重定向
        response.sendRedirect("list.do");
    }
    public void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id=Integer.parseInt(request.getParameter("id"));
        staffService.remove(id);
        response.sendRedirect("list.do");
    }
    public void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id=Integer.parseInt(request.getParameter("id"));
        Staff staff=staffService.get(id);
        request.setAttribute("OBJ",staff);

        request.getRequestDispatcher("../staff_detail.jsp").forward(request,response);
    }

}

-页面
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

登录及个人中心
登录、退出、个人信息、修改密码
关注点
-Session操作
-登录过滤器
步骤:
-实体类
就是上面的staff实体类
-Dao接口和Sql映射文件

@Repository("selfDao")
public interface SelfDao {
    Staff selectByAccount(String account);
}
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jjyu.sm.dao.SelfDao">
  <select id="selectByAccount" parameterType="String" resultMap="com.jjyu.sm.dao.StaffDao.resultMap">
     SELECT  * from staff where account=#{account}
  </select>
</mapper>
	   -Service接口及其实现类
public interface SelfService {
    Staff login(String account,String password);
    void changePassword(Integer id,String password);
}
@Service("selfService")
public class SelfServiceImpl implements SelfService {
    @Autowired
    private SelfDao selfDao;
    @Autowired
    private StaffDao staffDao;
    public Staff login(String account, String password) {
        Staff staff=selfDao.selectByAccount(account);
        if(staff==null){
            return null;
        }
        if(staff.getPassword().equals(password)){
            return staff;
        }
        return null;
    }

    public void changePassword(Integer id, String password) {
        Staff staff=staffDao.selectById(id);
        staff.setPassword(password);
        staffDao.update(staff);

    }
}
	   -控制器
@Controller("selfController")
public class SelfController {
    @Autowired
    private SelfService selfService;
    public void toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("login.jsp").forward(request,response);
    }


    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String account=request.getParameter("account");
        String password=request.getParameter("password");
        Staff staff=selfService.login(account,password);
        if(staff==null)
        {
            response.sendRedirect("toLogin.do");
        }else{
            HttpSession session=request.getSession();
            session.setAttribute("USER",staff);
            response.sendRedirect("main.do");
        }
    }
    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            HttpSession session=request.getSession();
            session.setAttribute("USER",null);
            response.sendRedirect("toLogin.do");
    }
    // /main.do
    public void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }
    // /self/info.do
    public void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("../info.jsp").forward(request,response);
    }
    // /self/toChangePassword.do
    public void toChangePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("../change_password.jsp").forward(request,response);
    }
    // /self/changePassword.do
    public void changePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String password=request.getParameter("password");
        String password1=request.getParameter("password1");
        HttpSession session=request.getSession();
        Staff staff=(Staff)session.getAttribute("USER");
        if(!staff.getPassword().equals(password)){
            response.sendRedirect("toChangePassword.do");
        }
        else {
            selfService.changePassword(staff.getId(), password1);
//            response.sendRedirect("../logout.do");
            response.getWriter().print("<script type=\"text/javascript\">parent.location.href=\"../logout.do\"</script>");
        }
    }
}

-页面
在这里插入图片描述
在这里插入图片描述在这里插入图片描述在这里插入图片描述

日志处理
日志查看、自动记录
关注点
-业务功能设计
-通知处理
步骤:
-实体类

public class Log {
    private Date oprTime;
    private String type;
    private String operator;
    private String moudle;
    private String operation;
    private String result;

    public Date getOprTime() {
        return oprTime;
    }

    public void setOprTime(Date oprTime) {
        this.oprTime = oprTime;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public String getMoudle() {
        return moudle;
    }

    public void setMoudle(String moudle) {
        this.moudle = moudle;
    }

    public String getOperation() {
        return operation;
    }

    public void setOperation(String operation) {
        this.operation = operation;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
}

	   -Dao接口和Sql映射文件
@Repository("logDao")
public interface LogDao {
    void insert(Log log);
    List<Log> selectByType(String type);

}

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jjyu.sm.dao.LogDao">
    <resultMap id="resultMap" type="Log">
        <result property="oprTime" column="opr_time" javaType="java.util.Date"/>
        <result property="type" column="type" javaType="String"/>
        <result property="operator" column="operator" javaType="String"/>
        <result property="moudle" column="moudle" javaType="String"/>
        <result property="operation" column="operation" javaType="String"/>
        <result property="result" column="result" javaType="String"/>
    </resultMap>
    <insert id="insert" parameterType="Log">
        insert into log values(#{oprTime},#{type},#{operator},#{moudle},#{operation},#{result});
    </insert>
    <select id="selectByType" parameterType="String" resultMap="resultMap">
        select * from log where type=#{type} order by opr_time desc
    </select>
</mapper>


	   -Service接口及其实现类
public interface LogService {
    void addSystemLog(Log log);
    void addLoginLog(Log log);
    void addOperationLog(Log log);

    List<Log> getSystemLog();
    List<Log> getLoginLog();
    List<Log> getOperationLog();

}
@Service("logService")
public class LogServiceImpl implements LogService {
    @Autowired
    private LogDao logDao;
    public void addSystemLog(Log log) {
        log.setOprTime(new Date());
        log.setType("system");
        logDao.insert(log);

    }

    public void addLoginLog(Log log) {
        log.setOprTime(new Date());
        log.setType("login");
        logDao.insert(log);
    }

    public void addOperationLog(Log log) {
        log.setOprTime(new Date());
        log.setType("operation");
        logDao.insert(log);
    }

    public List<Log> getSystemLog() {
        return logDao.selectByType("system");
    }

    public List<Log> getLoginLog() {
        return  logDao.selectByType("login");
    }

    public List<Log> getOperationLog() {
        return  logDao.selectByType("operation");
    }
}

	   -控制器
@Controller("logController")
public class LogController {
    @Autowired
    private LogService logService;
    public void operationLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Log> list=logService.getOperationLog();
        request.setAttribute("LIST",list);
        request.setAttribute("TYPE","操作");
        request.getRequestDispatcher("../log_list.jsp").forward(request,response);
    }
    public void loginLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Log> list=logService.getLoginLog();
        request.setAttribute("LIST",list);
        request.setAttribute("TYPE","登录");
        request.getRequestDispatcher("../log_list.jsp").forward(request,response);
    }
    public void systemLog(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Log> list=logService.getSystemLog();
        request.setAttribute("LIST",list);
        request.setAttribute("TYPE","系统");
        request.getRequestDispatcher("../log_list.jsp").forward(request,response);
    }
}

-页面
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值