SSM整合

文章详细介绍了如何搭建一个基于Spring的Web应用程序,包括创建Maven模块,配置web.xml,设置编码过滤器和请求处理过滤器,配置SpringMVC的DispatcherServlet,以及配置Spring的ContextLoaderListener。同时,文章还涵盖了MyBatis的环境配置,如创建属性文件,核心配置,Mapper接口和映射文件。此外,还提到了日志配置,Thymeleaf视图解析器的配置,以及测试组件和页面的创建。
摘要由CSDN通过智能技术生成

一、ContextLoaderListener

Spring提供了监听器ContextLoaderListener,实现ServletContextListener接口,可监听 ServletContext的状态,在web服务器的启动,读取Spring的配置文件,创建Spring的IOC容器。web 应用中必须在web.xml中配置

    <!--
        配置Spring的监听器,在服务器启动时加载Spring的配置文件
        Spring配置文件默认位置和名称:/WEB-INF/applicationContext.xml
        可通过上下文参数自定义Spring配置文件的位置和名称
    -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 设置Spring的配置文件的位置和名称 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

 

 

二、准备工作

① 创建Maven Module

② 导入依赖

    <packaging>war</packaging>

    <properties>
        <spring.version>5.3.1</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--springmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--mybatis和spring的整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <!-- log4j日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- ServletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- Spring5和Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
    </dependencies>

③ 创建表

CREATE TABLE `t_emp` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

 

 

三、配置web.xml

    <!-- 配置Spring的编码过滤器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置处理请求方式PUT和DELETE的过滤器 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置SpringMVC的前端控制器 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 设置SpringMVC的配置文件的位置和名称 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 设置Spring的配置文件的位置和名称 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

    <!-- 配置Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

 

 

四、创建SpringMVC的配置文件并配置

 <!-- 扫描控制层组件 -->
    <context:component-scan base-package="com.ssm.controller"/>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--
        处理静态资源,例如html、js、css、jpg
        若只设置该标签,则只能访问静态资源,其他请求则无法访问此时必须设置<mvc:annotation-driven/>解决问题
    -->
    <mvc:default-servlet-handler />

    <!-- 开启mvc注解驱动 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 处理响应中文内容乱码 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8" />
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--
        配置访问首页的视图控制
        path:设置处理的请求地址
        view-name:设置请求地址所对应的视图名称
    -->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>

    <!--必须通过文件上传解析器的解析才能将文件转换为MultipartFile对象-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>

<!--    <mvc:interceptors>-->
<!--        <bean class="com.ssm.interceptor.FirstInterceptor"></bean>-->
<!--        <ref  bean="firstInterceptor"></ref>-->
<!--        &lt;!&ndash; 以上两种配置方式都是对DispatcherServlet所处理的所有的请求进行拦截 &ndash;&gt;-->
<!--        <mvc:interceptor>-->
<!--            &lt;!&ndash;配置需要栏截的请求的请求路径,/**表示所有请求&ndash;&gt;-->
<!--            <mvc:mapping path="/**"/>-->
<!--            &lt;!&ndash;配置需要排除拦截的请求的请求路径&ndash;&gt;-->
<!--            <mvc:exclude-mapping path="/testRequestEntity"/>-->
<!--            &lt;!&ndash;配置拦截器&ndash;&gt;-->
<!--            <ref bean="firstInterceptor"></ref>-->
<!--        </mvc:interceptor>-->
<!--        &lt;!&ndash;-->
<!--        以上配置方式可以通过ref或bean标签设置拦截器,通过mvc:mapping设置需要拦截的请求,通过-->
<!--        mvc:exclude-mapping设置需要排除的请求,即不需要拦截的请求-->
<!--        &ndash;&gt;-->
<!--    </mvc:interceptors>-->

<!--    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">-->
<!--        <property name="exceptionMappings">-->
<!--            <props>-->
<!--                &lt;!&ndash;-->
<!--                properties的键表示处理器方法执行过程中出现的异常-->
<!--                properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面-->
<!--                &ndash;&gt;-->
<!--                <prop key="java.lang.ArithmeticException">error</prop>-->
<!--            </props>-->
<!--        </property>-->
<!--        &lt;!&ndash;-->
<!--        exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享-->
<!--        &ndash;&gt;-->
<!--        <property name="exceptionAttribute" value="ex"></property>-->
<!--    </bean>-->

 

 

五、搭建MyBatis环境

① 创建属性文件jdbc.properties

② 创建MyBatis的核心配置文件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>
    <!--
        MyBatis核心配置文件中,标签的顺序:
        properties?,settings?,typeAliases?,typeHandlers?,
        objectFactory?,objectWrapperFactory?,reflectorFactory?,
        plugins?,environments?,databaseIdProvider?,mappers?
    -->

    <settings>
        <!--将下划线映射为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <plugins>
        <!--配置分页插件-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
    
</configuration>

③ 创建Mapper接口和映射文件

public interface EmployeeMapper {
    List<Employee> getEmployeeList();
}
<?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="com.ssm.mapper.EmployeeMapper">

    <!--getEmployeeList()-->
    <select id="getEmployeeList" resultType="EmployeeList">
        select * from t_emp;
    </select>

</mapper>

④ 创建日志文件log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>

    

 

六、创建Spring的配置文件并配置

<?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:component-scan base-package="com.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 引入jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- 配置Druid数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" value="dataSource"></property>
    </bean>

    <!--开启事务的注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- 配置用于创建SqlSessionFactory的工厂bean -->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 设置MyBatis配置文件的路径(可以不设置) -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 设置类型别名所对应的包 -->
        <property name="typeAliasesPackage" value="com.ssm.pojo"></property>
        <!--
            设置映射文件的路径
            若映射文件所在路径和mapper接口所在路径一致,则不需要设置
        -->
        <!--
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
        -->
    </bean>

    <!--
        配置mapper接口的扫描配置
        由mybatis-spring提供,可以将指定包下所有的mapper接口创建动态代理
        并将这些动态代理作为IOC容器的bean管理
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.mapper"></property>
    </bean>

</beans>

 

 

七、测试功能

① 创建组件

实体类Employee

package com.ssm.pojo;

/**
 * Author:wy
 * Date:2023/4/3
 */

public class Employee {
    private Integer empId;
    private String empName;
    private Integer age;
    private String gender;
    private String email;

    public Employee() {
    }

    public Employee(Integer empId, String empName, Integer age, String gender, String email) {
        this.empId = empId;
        this.empName = empName;
        this.age = age;
        this.gender = gender;
        this.email = email;
    }

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empId=" + empId +
                ", empName='" + empName + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

创建控制层组件EmployeeController

package com.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.pojo.Employee;
import com.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import sun.security.provider.MD2;

import java.util.List;

/**
 * Author:wy
 * Date:2023/4/3
 * 查询所有员工信息 -->/employee --> get
 * 查询所有员工的分页信息 -->/employee/page/1 --> get
 * 根据id查询员工信息 -->/employee/1 --> get
 * 跳转到添加页面 -->/to/add --> get
 * 添加员工信息 -->/employee --> post
 * 修改员工信息 -->/employee --> put
 * 删除员工信息 -->/employee/1 --> delete
 */

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //跳转到添加员工信息页面
    @RequestMapping(value = "/to/add", method = RequestMethod.GET)
    public String toInsertEmployee() {
        //跳转到添加员工页面
        return "employee_add";
    }

    //添加员工
    @RequestMapping(value = "/employee", method = RequestMethod.POST)
    public String insertEmployee(Employee employee) {
        employeeService.insertEmployee(employee);
        //重定向跳转
        return "redirect:/employee/page/1";
    }

    //根据id删除员工信息
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id") Integer id,
                                 @RequestParam(value = "pn",defaultValue = "1") Integer pn) {
        employeeService.deleteEmployeeById(id);

        //拼接跳转地址,删除后跳转回当前页
        String re =  "redirect:/employee/page/" + pn.toString();

        //重定向跳转
        return re;
    }

    //根据id修改员工信息
    @RequestMapping(value = "/employee", method = RequestMethod.PUT)
    public String updateEmployee(Employee employee) {
        System.out.println(employee);
        employeeService.updateEmployeeById(employee);
        //重定向跳转
        return "redirect:/employee/page/1";
    }

    //跳转到修改员工信息页面
    @RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
    public String toUpdateEmployee(Model model, @PathVariable("id") Integer id) {
        //获取id获取员工信息
        Employee employee = employeeService.getEmployeeById(id);
        //将员工信息在请求域中共享
        model.addAttribute("employee", employee);
        //跳转到修改页面
        return "employee_update";
    }

    //员工的分页信息
    @RequestMapping(value = "/employee/page/{pageNum}", method = RequestMethod.GET)
    public String getEmployeePage(Model model, @PathVariable("pageNum") Integer pageNum) {
        //获取员工的分页信息
        PageInfo<Employee> page = employeeService.getEmployeePage(pageNum);

        //将员工分页信息在请求域中共享
        model.addAttribute("page", page);
        return "employee_list";
    }

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public String getAllEmployee(Model model) {
        //查询所有的员工信息
        List<Employee> list = employeeService.getAllEmployee();
        //将员工信息在请求域中共享
        model.addAttribute("list", list);
        return "employee_list";
    }
}

创建接口EmployeeService

package com.ssm.service;

import com.github.pagehelper.PageInfo;
import com.ssm.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Author:wy
 * Date:2023/4/3
 */

public interface EmployeeService {

    /**
     * 查询所有的员工信息
     * @return
     */
    List<Employee> getAllEmployee();

    /**
     * 获取员工的分页信息
     * @param pageNum
     * @return
     */
    PageInfo<Employee> getEmployeePage(Integer pageNum);


    /**
     * 根据id查询员工信息
     * @return
     */
    Employee getEmployeeById(Integer id);

    /**
     * 根据id修改员工信息
     * @param employee
     */
    void updateEmployeeById(Employee employee);

    /**
     * 根据id删除员工信息
     * @param id
     */
    void deleteEmployeeById(Integer id);

    /**
     * 添加员工
     * @param employee
     */
    void insertEmployee(Employee employee);
}

创建实现类EmployeeServiceImpl

package com.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.mapper.EmployeeMapper;
import com.ssm.pojo.Employee;
import com.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Author:wy
 * Date:2023/4/3
 */
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    public List<Employee> getAllEmployee() {
        return employeeMapper.getAllEmployee();
    }

    public PageInfo<Employee> getEmployeePage(Integer pageNum) {
        //开启分页功能
        PageHelper.startPage(pageNum, 4);
        //查询所有的员工信息
        List<Employee> list = employeeMapper.getAllEmployee();
        //获取分页相关数据
        PageInfo<Employee> page = new PageInfo<Employee>(list, 5);
        return page;
    }

    public Employee getEmployeeById(Integer id) {
        Employee employee = employeeMapper.getEmployeeById(id);
        return employee;
    }

    public void updateEmployeeById(Employee employee) {
        employeeMapper.updateEmployeeById(employee);
    }

    public void deleteEmployeeById(Integer id) {
        employeeMapper.deleteEmployeeById(id);
    }

    public void insertEmployee(Employee employee) {
        employeeMapper.insertEmployee(employee);
    }
}

创建接口EmployeeMapper

package com.ssm.mapper;

import com.ssm.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Author:wy
 * Date:2023/4/3
 */

public interface EmployeeMapper {

    /**
     * 查询全部的员工信息
     * @return
     */
    List<Employee> getAllEmployee();


    /**
     * 根据id查询员工信息
     * @return
     */
    Employee getEmployeeById(@Param("id") Integer id);

    /**
     * 根据id修改员工信息
     * @param employee
     */
    void updateEmployeeById(Employee employee);

    /**
     * 根据id删除员工信息
     * @param id
     */
    void deleteEmployeeById(@Param("id") Integer id);

    /**
     * 添加员工
     * @param employee
     */
    void insertEmployee(Employee employee);
}

创建EmployeeMapper映射文件

<?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="com.ssm.mapper.EmployeeMapper">

    <!--getAllEmployee()-->
    <select id="getAllEmployee" resultType="Employee">
        select * from t_emp
    </select>

    <!--getEmployeeById(@Param("id") int id);-->
    <select id="getEmployeeById" resultType="Employee">
        select * from t_emp where emp_id = #{id}
    </select>

    <!--updateEmployeeById(Employee employee);-->
    <update id="updateEmployeeById">
        update t_emp set emp_name = #{empName},age = #{age},gender = #{gender},email = #{email} where emp_id = #{empId}
    </update>

    <!--deleteEmployeeById(@Param("id") Integer id);-->
    <delete id="deleteEmployeeById">
        delete from t_emp where emp_id = #{id}
    </delete>

    <!--insertEmployee(Employee employee)-->
    <insert id="insertEmployee" >
        insert into t_emp values (null ,#{empName},#{age},#{gender},#{email});
    </insert>

</mapper>

② 创建页面

员工信息分页页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>员工列表</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<div id="app">
    <table>
        <tr>
            <th colspan="6">员工列表</th>
        </tr>
        <tr>
            <th>流水号</th>
            <th>员工姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>邮箱</th>
            <th>操作(<a th:href="@{/to/add}">添加员工</a>)</th>
        </tr>

        <tr th:each="employy,status : ${page.list}">
            <td th:text="${status.count}"></td>
            <td th:text="${employy.empName}"></td>
            <td th:text="${employy.age}"></td>
            <td th:text="${employy.gender}"></td>
            <td th:text="${employy.email}"></td>
            <td>
                <a @click="deleteEmployee"
                   th:href="@{/employee/{id}(id=${employy.empId},pn=${page.pageNum})}">删除</a>
                <a th:href="@{'/employee/' + ${employy.empId}}">修改</a>
            </td>
        </tr>
    </table>
    <form id="delete_form" method="post">
        <input type="hidden" name="_method" value="delete">
    </form>
</div>

<div style="text-align: center;">
    <a th:if="${page.hasPreviousPage}" th:href="@{/employee/page/1}">首页</a>
    <a th:if="${page.hasPreviousPage}" th:href="@{'/employee/page/' + ${page.prePage} }">上一页</a>
    <span th:each="num : ${page.navigatepageNums}">
        <a th:if="${page.pageNum == num}" style="color: red" th:href="@{'/employee/page/' + ${num}}" th:text="'['+ ${num}+']'"></a>
        <a th:if="${page.pageNum != num}" th:href="@{'/employee/page/' + ${num}}" th:text="${num}"></a>
    </span>
    <a th:if="${page.hasNextPage}" th:href="@{'/employee/page/' + ${page.nextPage} }">下一页</a>
    <a th:if="${page.hasNextPage}" th:href="@{'/employee/page/' + ${page.pages} }">尾页</a>
</div>

<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript" >
    var vue = new Vue({
        el:"#app",
        methods:{
            //event表示当前事件
            deleteEmployee:function (event) {
                //通过id获取表单标签
                var delete_form = document.getElementById("delete_form");
                //将触发事件的超链接的href属性为表单的action属性赋值
                delete_form.action = event.target.href;
                //提交表单
                delete_form.submit();
                //阻止超链接的默认跳转行为
                event.preventDefault();
            }
        }
    });
</script>
</body>
</html>

员工信息修改页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改员工信息</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
    <form th:action="@{/employee}" method="post">
        <input type="hidden" name="_method" value="put">
        <input type="hidden" name="empId" th:value="${employee.empId}">
        <table>
            <tr>
                <th colspan="3">修改员工信息</th>
            </tr>
            <tr>
                <td>员工姓名</td>
                <td><input type="text" name="empName" th:value="${employee.empName}"></td>
            </tr>
            <tr>
                <td>年龄</td>
                <td><input type="text" name="age" th:value="${employee.age}"></td>
            </tr>
            <tr>
                <td>gender</td>
                <td>
                    <input type="radio" name="gender" value="男" th:field="${employee.gender}">男
                    <input type="radio" name="gender" value="女" th:field="${employee.gender}">女
                </td>
            </tr>
            <tr>
                <td>邮箱</td>
                <td><input type="text" name="email" th:value="${employee.email}"></td>
            </tr>
            <tr>
                <td colspan="3">
                    <input type="submit" value="修改">
                </td>
            </tr>
        </table>
    </form>

</body>
</html>

 员工信息添加页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加员工</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
    <form th:action="@{/employee}" method="post">
        <table>
            <tr>
                <th colspan="3">添加员工</th>
            </tr>
            <tr>
                <td>员工姓名</td>
                <td><input type="text" name="empName"></td>
            </tr>
            <tr>
                <td>年龄</td>
                <td><input type="text" name="age"></td>
            </tr>
            <tr>
                <td>性别</td>
                <td>
                    <input type="radio" name="gender" value="男">男
                    <input type="radio" name="gender" value="女">女
                </td>
            </tr>
            <tr>
                <td>邮箱</td>
                <td><input type="text" name="email"></td>
            </tr>
            <tr>
                <td colspan="3">
                    <input type="submit" value="添加">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值