Maven整合SSM测试

Java基础

浏览数:127

2019-7-25

AD:资源代下载服务

 前面也说到了关于SSM的整合,话不多说直接从创建项目开始CRUD之路(参考前面写过的Mybatis和Spring整合SSM简单整合),这是整个项目的结构

  以及最终的结果。(附上下载地址

一、创建Maven项目

1、在Project中按照下面步骤进行创建一个新的maven项目

2、然后填写项目的坐标信息 

3、最后选择Maven项目本地仓库的路径,然后下一步填写项目名即可

二、配置pom.xml文件,导入相关的jar包

  1、以配置spring-webmvc为例:我们在https://mvnrepository.com/按照下面的方式都说想要导入的jar包

  

  2、然后选择合适的版本之后,赋值Maven配置文件

  

  3、在pom.xml中配置如下,然后在左侧Maven可以发现工程依赖的jar包,如果pom.xml中配置时发现没有提示没有本地库中没有对应的jar包,如下所示  

  

  我们不用理会,Maven会自动下载配置的所需要的jar包,如下所示

  

  4、上述导入的包有spring、springmvc以及mybatis和其他如数据库连接池、驱动和测试包等都导入完毕之后,整个pom。xml就是这样

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <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/maven-v4_0_0.xsd">
  3 
  4   <modelVersion>4.0.0</modelVersion>
  5   <packaging>war</packaging>
  6 
  7   <name>ssm-first</name>
  8   <groupId>cn.test.ssm</groupId>
  9   <artifactId>ssm-first</artifactId>
 10   <version>1.0-SNAPSHOT</version>
 11 
 12   <dependencies>
 13     <dependency>
 14       <groupId>javaee</groupId>
 15       <artifactId>javaee-api</artifactId>
 16       <version>5</version>
 17     </dependency>
 18     <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
 19     <dependency>
 20       <groupId>org.springframework</groupId>
 21       <artifactId>spring-webmvc</artifactId>
 22       <version>4.3.7.RELEASE</version>
 23     </dependency>
 24     <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
 25     <dependency>
 26       <groupId>org.springframework</groupId>
 27       <artifactId>spring-jdbc</artifactId>
 28       <version>4.3.7.RELEASE</version>
 29     </dependency>
 30 
 31     <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
 32     <dependency>
 33       <groupId>org.springframework</groupId>
 34       <artifactId>spring-context</artifactId>
 35       <version>4.3.7.RELEASE</version>
 36     </dependency>
 37 
 38     <!--Spring的测试包-->
 39     <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
 40     <dependency>
 41       <groupId>org.springframework</groupId>
 42       <artifactId>spring-test</artifactId>
 43       <version>4.3.7.RELEASE</version>
 44       <scope>test</scope>
 45     </dependency>
 46     <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
 47     <dependency>
 48       <groupId>aopalliance</groupId>
 49       <artifactId>aopalliance</artifactId>
 50       <version>1.0</version>
 51     </dependency>
 52     <!-- https://mvnrepository.com/artifact/asm/asm -->
 53     <dependency>
 54       <groupId>asm</groupId>
 55       <artifactId>asm</artifactId>
 56       <version>3.3.1</version>
 57     </dependency>
 58 
 59     <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
 60     <dependency>
 61       <groupId>org.aspectj</groupId>
 62       <artifactId>aspectjweaver</artifactId>
 63       <version>1.8.10</version>
 64     </dependency>
 65     <!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
 66     <dependency>
 67       <groupId>org.javassist</groupId>
 68       <artifactId>javassist</artifactId>
 69       <version>3.17.1-GA</version>
 70     </dependency>
 71 
 72     <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
 73     <dependency>
 74       <groupId>org.mybatis</groupId>
 75       <artifactId>mybatis</artifactId>
 76       <version>3.4.2</version>
 77     </dependency>
 78     <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
 79     <dependency>
 80       <groupId>org.mybatis</groupId>
 81       <artifactId>mybatis-spring</artifactId>
 82       <version>1.3.1</version>
 83     </dependency>
 84     <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
 85       <dependency>
 86           <groupId>c3p0</groupId>
 87           <artifactId>c3p0</artifactId>
 88           <version>0.9.1.2</version>
 89       </dependency>
 90     <dependency>
 91       <groupId>com.mchange</groupId>
 92       <artifactId>c3p0</artifactId>
 93       <version>0.9.5.2</version>
 94     </dependency>
 95       <dependency>
 96           <groupId>cglib</groupId>
 97           <artifactId>cglib</artifactId>
 98           <version>2.2.2</version>
 99       </dependency>
100   <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
101     <dependency>
102       <groupId>mysql</groupId>
103       <artifactId>mysql-connector-java</artifactId>
104       <version>5.1.41</version>
105     </dependency>
106     <!-- https://mvnrepository.com/artifact/jstl/jstl -->
107     <dependency>
108       <groupId>jstl</groupId>
109       <artifactId>jstl</artifactId>
110       <version>1.2</version>
111     </dependency>
112     <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
113     <dependency>
114       <groupId>javax.servlet</groupId>
115       <artifactId>servlet-api</artifactId>
116       <version>2.5</version>
117       <scope>provided</scope>
118     </dependency>
119     <!-- https://mvnrepository.com/artifact/junit/junit -->
120     <dependency>
121       <groupId>junit</groupId>
122       <artifactId>junit</artifactId>
123       <version>4.12</version>
124       <scope>test</scope>
125     </dependency>
126     <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
127     <dependency>
128       <groupId>javax.servlet.jsp</groupId>
129       <artifactId>jsp-api</artifactId>
130       <version>2.1</version>
131       <scope>provided</scope>
132     </dependency>
133     <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
134     <dependency>
135       <groupId>org.mybatis.generator</groupId>
136       <artifactId>mybatis-generator-core</artifactId>
137       <version>1.3.5</version>
138     </dependency>
139 
140   </dependencies>
141 
142 </project>

三、配置web.xml

  其中包括Spring容器的配置(Tomcat启动时候加载Spring的有关配置文件)、前端控制器DispatcherServlet的配置和前端控制器拦截请求的配置、编码过滤器的配置、以及实现REST风格的过滤器配置。

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.4"
 3          xmlns="http://java.sun.com/xml/ns/j2ee"
 4          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 6 
 7   <!--配置启动时候加载Spring相关配置文件-->
 8   <context-param>
 9     <param-name>contextConfigLocation</param-name>
10     <param-value>classpath*:spring/applicationContext-*.xml</param-value>
11   </context-param>
12   <!--配置监听器-->
13   <listener>
14     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15   </listener>
16   <!--配置前端控制器-->
17   <!--配置前端控制器-->
18   <servlet>
19     <servlet-name>SpringMvc</servlet-name>
20     <servlet-class>
21       org.springframework.web.servlet.DispatcherServlet
22     </servlet-class>
23     <!--
24         配饰SpringMVC的配置文件(处理器映射器、适配器等)
25         注明需要这样配置的原因:自己配置contextConfigLocation,就不会自己默认加载/WEB-INF/下面的dispatch-servlet.xml
26     -->
27     <init-param>
28       <param-name>contextConfigLocation</param-name>
29       <param-value>classpath:springmvc/springmvc.xml</param-value>
30     </init-param>
31   </servlet>
32   <servlet-mapping>
33     <servlet-name>SpringMvc</servlet-name>
34     <url-pattern>/</url-pattern>
35   </servlet-mapping>
36 <!--编码过滤器-->
37   <filter>
38     <filter-name>CharacterEncodingFilter</filter-name>
39     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
40     <init-param>
41       <param-name>encoding</param-name>
42       <param-value>utf-8</param-value>
43     </init-param>
44   </filter>
45   <filter-mapping>
46     <filter-name>CharacterEncodingFilter</filter-name>
47     <url-pattern>/*</url-pattern>
48   </filter-mapping>
49   <!--使用REST风格的URI-->
50   <filter>
51     <!--将页面上的post请求转为指定的delete或者put请求-->
52     <filter-name>HiddenHttpMethodFilter</filter-name>
53     <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
54   </filter>
55   <filter-mapping>
56     <filter-name>HiddenHttpMethodFilter</filter-name>
57     <url-pattern>/*</url-pattern>
58   </filter-mapping>
59 </web-app>
60         

四、配置SpringMVC的配置文件

   springmvc.xml中的配置主要包括Controller层的扫描配置、处理器映射器、处理器适配器、视图解析器的配置,和一些静态资源请求交由tomcat处理的配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/mvc
 9         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
10         http://www.springframework.org/schema/context
11         http://www.springframework.org/schema/context/spring-context-3.2.xsd
12         http://www.springframework.org/schema/aop
13         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
14         http://www.springframework.org/schema/tx
15         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
16 
17     <!--配置controller的扫描-->
18     <context:component-scan base-package="controller"></context:component-scan>
19 
20     <!--将springmvc不能够处理的请求交给Tomcat-->
21     <mvc:default-servlet-handler></mvc:default-servlet-handler>
22 
23     <!--配置mvc:annotation代替基于注解方式的处理器映射器和适配器的配置-->
24     <mvc:annotation-driven></mvc:annotation-driven>
25 
26     <!--配置视图解析器-->
27     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
28         <property name="prefix" value="/WEB-INF/views"></property>
29         <property name="suffix" value=".jsp"></property>
30     </bean>
31 </beans>

五、配置Spring的配置文件

   其中主要包括的就是数据源、会话工厂、mapper扫描器和事务控制

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:aop="http://www.springframework.org/schema/aop"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans.xsd
10         http://www.springframework.org/schema/aop
11         http://www.springframework.org/schema/aop/spring-aop.xsd
12         http://www.springframework.org/schema/context
13         http://www.springframework.org/schema/context/spring-context.xsd
14         http://www.springframework.org/schema/tx
15         http://www.springframework.org/schema/tx/spring-tx.xsd">
16 
17     <!--加载数据库信息的配置文件-->
18     <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
19 
20     <!--配置数据源-->
21     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
22         <property name="driverClass" value="${jdbc.driver}" />
23         <property name="jdbcUrl" value="${jdbc.url}" />
24         <property name="user" value="${jdbc.username}" />
25         <property name="password" value="${jdbc.password}" />
26     </bean>
27 
28     <!--配置SqlSessionFactory-->
29     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
30         <!--加载Mybatis的配置文件-->
31         <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
32         <!--配置数据源-->
33         <property name="dataSource" ref="dataSource"></property>
34         <!--指定mapper配置文件所在的位置-->
35         <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
36     </bean>
37 
38     <!--配置mapper扫描器-->
39     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
40         <property name="basePackage" value="dao"></property>
41         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
42     </bean>
43 
44     <!--
45     事务控制的配置
46     对数据库操作Mybatis的事务控制使用spring的jdbc事务管理控制类
47     -->
48     <!--事务管理器-->
49     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
50         <!--添加对数据源的控制-->
51         <property name="dataSource" ref="dataSource"></property>
52     </bean>
53 
54     <!--通知-->
55     <tx:advice id="txAdvice">
56         <tx:attributes>
57             <!--配置传播行为-->
58             <!--配置必须进行事务控制的方法-->
59             <tx:method name="*"></tx:method>
60             <tx:method name="save*" propagation="REQUIRED"/>
61             <tx:method name="delete*" propagation="REQUIRED"></tx:method>
62             <tx:method name="insert*" propagation="REQUIRED"></tx:method>
63             <tx:method name="update*" propagation="REQUIRED"></tx:method>
64             <!--配置支持事务的方法-->
65             <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
66         </tx:attributes>
67     </tx:advice>
68     <!--配置aop去调用通知-->
69     <aop:config>
70         <aop:advisor advice-ref="txAdvice" pointcut="execution(* service.*.*(..))"></aop:advisor>
71     </aop:config>
72 
73 </beans>

六、Mybatis逆向工程生成相关代码

   1、首先在数据库中创建我们所需要的两张表user(员工)、department(部门),并且建立两者之间的外键关联关系(sql文件下载

 1 CREATE TABLE `t_user` (
 2   `user_id` INT(11) NOT NULL AUTO_INCREMENT,
 3   `user_name` VARCHAR(20) DEFAULT NULL,
 4   `user_sex` VARCHAR(20) DEFAULT NULL,
 5   `user_email` VARCHAR(40) DEFAULT NULL,
 6   `dep_id` INT(11) DEFAULT NULL,
 7   PRIMARY KEY (`user_id`),
 8   KEY `FK_t_user` (`dep_id`),
 9   CONSTRAINT `FK_t_user` FOREIGN KEY (`dep_id`) REFERENCES `t_department` (`department_id`)
10 ) ENGINE=INNODB DEFAULT CHARSET=utf8
1 CREATE TABLE `t_department` (
2   `department_id` INT(11) NOT NULL AUTO_INCREMENT,
3   `department_name` VARCHAR(255) NOT NULL,
4   PRIMARY KEY (`department_id`)
5 ) ENGINE=INNODB DEFAULT CHARSET=utf8

  2、使用Mybatis逆向工程

  ①打开http://www.mybatis.org/generator/,进入Quick Start Guide

  

  ②然后根据里面的代码实例进行逆向工程配置文件的配置

  

  ③配置mybatis-generator.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration
 3         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 4         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 
 6 <generatorConfiguration>
 7 
 8     <context id="DB2Tables" targetRuntime="MyBatis3">
 9         <!--配置数据库信息-->
10         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
11                         connectionURL="jdbc:mysql:///ssm-crud"
12                         userId="root"
13                         password="123">
14         </jdbcConnection>
15 
16         <javaTypeResolver>
17             <property name="forceBigDecimals" value="false" />
18         </javaTypeResolver>
19 
20         <!--逆向工程生成的bean所在的位置-->
21         <javaModelGenerator targetPackage="cn.test.ssm.bean" targetProject=".\src\main\java">
22             <property name="enableSubPackages" value="true" />
23             <property name="trimStrings" value="true" />
24         </javaModelGenerator>
25 
26         <!--指定sql映射文件的位置-->
27         <sqlMapGenerator targetPackage="mapper"  targetProject=".\src\main\resources">
28             <property name="enableSubPackages" value="true" />
29         </sqlMapGenerator>
30 
31         <!--指定mapper接口的位置-->
32         <javaClientGenerator type="XMLMAPPER" targetPackage="cn.test.ssm.dao"  targetProject=".\src\main\java">
33             <property name="enableSubPackages" value="true" />
34         </javaClientGenerator>
35 
36         <!--指定每个表的生成策略-->
37         <table tableName="t_user" domainObjectName="Employee" ></table>
38         <table tableName="t_department" domainObjectName="Department"></table>
39 
40     </context>
41 </generatorConfiguration>

  ④在刚刚的网站首页中进入下图所示的链接然后根据里面的程序改写运行逆向工程

  

  

  ⑤根据上面的示例程序编写逆向工程测试程序

 1 package cn.test.ssm.utils;
 2 
 3 import org.mybatis.generator.api.MyBatisGenerator;
 4 import org.mybatis.generator.config.Configuration;
 5 import org.mybatis.generator.config.xml.ConfigurationParser;
 6 import org.mybatis.generator.internal.DefaultShellCallback;
 7 
 8 import java.io.File;
 9 import java.util.ArrayList;
10 import java.util.List;
11 
12 public class Generator {
13 
14     public static void main(String[] args) throws Exception {
15         List<String> warnings = new ArrayList<String>();
16         boolean overwrite = true;
17         File configFile = new File("mybatis-generator.xml");
18         ConfigurationParser cp = new ConfigurationParser(warnings);
19         Configuration config = cp.parseConfiguration(configFile);
20         DefaultShellCallback callback = new DefaultShellCallback(overwrite);
21         MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
22         myBatisGenerator.generate(null);
23     }
24 }

  ⑥然后运行程序可以发现根据中的配置文件生成了代码

  

七、Junit测试

  在整合前后端时,我们先使用测试程序测试逆向工程以及自己添加的其他方法的正确性。这里我们使用Spring提供成测试模块进行测试,首先在pom.xml中引入spring-test的jar包

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.7.RELEASE</version>
      <scope>test</scope>
    </dependency>

  2、然后建立测试包,其中使用ContextConfiguration指定spring的配置文件所在位置,以及Runwith指定使用spring的测试模块进行测试,然后就可以使用AutoWried注入我们想要测试的mapper接口了。下面测试的是DepartmentMapper中的insert方法(其余的测试方法可以下载源代码,已放置在github上面,可以参考)

 1 package cn.test.ssm;
 2 
 3 import cn.test.ssm.bean.Department;
 4 import cn.test.ssm.bean.Employee;
 5 import cn.test.ssm.dao.DepartmentMapper;
 6 import cn.test.ssm.dao.EmployeeMapper;
 7 import org.junit.Test;
 8 import org.junit.runner.RunWith;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.test.context.ContextConfiguration;
11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12 
13 /*指定使用spring提供的单元测试模块进行*/
14 @RunWith(SpringJUnit4ClassRunner.class)
15 /*指定使用spring的单元测试进行,配置spring的配置文件路径即可*/
16 @ContextConfiguration(locations = {"classpath*:spring/applicationContext.xml"})
17 public class DaoTest {
18 
19     @Autowired
20     private DepartmentMapper departmentMapper;
21 
22     @Autowired
23     private EmployeeMapper employeeMapper;
24 
25     @Test
26     public void testInsertDept() throws Exception {
27 
28         /*开始进行测试*/
29         //1、insert部门信息
30         Department d = new Department();
31         d.setDepartmentName("管理部");
32         departmentMapper.insertSelective(d);
33     }
34 
35     @Test
36     public void testInsertUser() throws Exception {
37 
38         Employee e = new Employee();
39         e.setUserName("Lucy");
40         e.setUserSex("男");
41         e.setUserEmail("test@qq.com");
42         e.setDepId(1);
43         employeeMapper.insertSelective(e);
44     }
45 }

测试结果: 

 八、实现相应的功能

  1、访问index页面时,显示所有员工列表信息

  a)为了支持后台的分页查询,我们可以使用pagehelper,首先在pom.xml中引入依赖的jar包

    <!--Mybatis的分页插件依赖包-->
    <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.0.0</version>
    </dependency>  

  然后这是引入上述依赖包之后多出了下面这两项jar包内容

  

  b)然后就是在Mybatis的核心配置文件SqlMapConfig.xml中导入插件

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
        </plugin>
    </plugins>

  c)然后在Controller层的方法中使用这个插件

 1     @RequestMapping("/emps")
 2     public String getEmps(@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum, Model model) throws Exception{
 3         //使用分页查询
 4         //使用pageHelper插件,在查询之前只需要调用(传入页码和条目数)
 5         PageHelper.startPage(pageNum, 8);
 6         //startPage后面紧跟的查询就是分页查询
 7         List<Employee> employeeList = employeeService.getAll();
 8 
 9         //使用PageInfo,PageInfo包含了非常全面的分页属性
10         //将查询的结果信息放在pageInfo中,并且指定连续显示8页
11         PageInfo pageInfo = new PageInfo(employeeList, 8);
12 
13         model.addAttribute("pageInfo", pageInfo);
14         return "list";
15     }

  2、实现列表分页查询

  a)我们首先要做的就是访问的时候显示首页信息,我们需要编写对应的方法,

  下面的方法中,接受前台传入的页码参数,然后返回指定条数的信息到页面中

 1 package cn.test.ssm.controller;
 2 
 3 import cn.test.ssm.bean.Employee;
 4 import cn.test.ssm.service.EmployeeService;
 5 import com.github.pagehelper.PageHelper;
 6 import com.github.pagehelper.PageInfo;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.ui.Model;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestParam;
12 import org.springframework.web.servlet.ModelAndView;
13 
14 import java.util.List;
15 
16 @Controller
17 public class EmployeeController {
18 
19     @Autowired
20     EmployeeService employeeService;
21 
22     @RequestMapping("/emps.action")
23     public ModelAndView getEmps(@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum) throws Exception{
24         //使用分页查询
25         //使用pageHelper插件,在查询之前只需要调用(传入页码和条目数)
26         PageHelper.startPage(pageNum, 8);
27         //startPage后面紧跟的查询就是分页查询
28         List<Employee> employeeList = employeeService.getAll();
29 
30         //使用PageInfo,PageInfo包含了非常全面的分页属性
31         //将查询的结果信息放在pageInfo中,并且指定连续显示8页
32         PageInfo pageInfo = new PageInfo(employeeList, 5);
33 
34         ModelAndView modelAndView = new ModelAndView();
35 
36         modelAndView.addObject("pageInfo", pageInfo);
37         modelAndView.setViewName("WEB-INF/views/list.jsp");
38         //return "/WEB-INF/views/list.jsp";
39         return modelAndView;
40     }
41 }

  b)然后写service的方法,dao层我们使用的是逆向工程直接生成对应的mapper映射文件和mapper接口,所以在service中注入mapper接口后,直接调用mapper接口中的方法

1     /*
2         查询员工列表信息
3      */
4     public List<Employee> getAll() {
5         return employeeMapper.selectByExampleAndDepartment(null);
6     }

  c)编写好相应的前台jsp代码,进行测试(使用bootstrap简单布局一下)


  1 <%@ page language="java" contentType="text/html; charset=UTF-8"
  2          pageEncoding="UTF-8"%>
  3 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  4 <%@taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
  5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6 <html>
  7 <head>
  8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9 <title>员工列表</title>
 10 <script type="text/javascript"
 11     src="${pageContext.request.contextPath }/static/js/jquery-1.12.4.min.js"></script>
 12 <link
 13     href="${pageContext.request.contextPath }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
 14     rel="stylesheet">
 15 <script
 16     src="${pageContext.request.contextPath }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
 17 </head>
 18 <body>
 19     <!-- 搭建显示页面 -->
 20     <div class="container">
 21         <!-- 标题 -->
 22         <div class="row">
 23             <div class="col-md-12">
 24                 <h1>SSM整合测试</h1>
 25             </div>
 26         </div>
 27         <!-- 按钮 -->
 28         <div class="row">
 29             <div class="col-md-4 col-md-offset-8">
 30                 <button class="btn btn-primary">新增</button>
 31                 <button class="btn btn-danger">删除</button>
 32             </div>
 33         </div>
 34         <!-- 显示表格数据 -->
 35         <div class="row">
 36             <div class="col-md-12">
 37                 <table class="table table-hover">
 38                     <tr>
 39                         <th>编号</th>
 40                         <th>名字</th>
 41                         <th>性别</th>
 42                         <th>邮箱</th>
 43                         <th>部门</th>
 44                         <th>操作</th>
 45                     </tr>
 46                     <c:forEach items="${pageInfo.list }" var="emp">
 47                         <tr>
 48                             <th>${emp.userId }</th>
 49                             <th>${emp.userName }</th>
 50                             <th>${emp.userSex}</th>
 51                             <th>${emp.userEmail }</th>
 52                             <th>${emp.department.departmentName }</th>
 53                             <th>
 54                                 <button class="btn btn-primary btn-sm">
 55                                     <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
 56                                     编辑
 57                                 </button>
 58                                 <button class="btn btn-danger btn-sm">
 59                                     <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
 60                                     删除
 61                                 </button>
 62                             </th>
 63                         </tr>
 64                     </c:forEach>
 65                 </table>
 66             </div>
 67         </div>
 68 
 69         <!-- 显示分页信息 -->
 70         <div class="row">
 71             <!--分页文字信息  -->
 72             <div class="col-md-6">当前 ${pageInfo.pageNum }页,总${pageInfo.pages }
 73                 页,总 ${pageInfo.total } 条记录</div>
 74             <!-- 分页条信息 -->
 75             <div class="col-md-6">
 76                 <nav aria-label="Page navigation">
 77                 <ul class="pagination">
 78                     <li><a href="${pageContext.request.contextPath }/emps?pn=1">首页</a></li>
 79                     <c:if test="${pageInfo.hasPreviousPage }">
 80                         <li><a href="${pageContext.request.contextPath }/emps?pn=${pageInfo.pageNum-1}"
 81                             aria-label="Previous"> <span aria-hidden="true">&laquo;</span>
 82                         </a></li>
 83                     </c:if>
 84 
 85 
 86                     <c:forEach items="${pageInfo.navigatepageNums }" var="page_Num">
 87                         <c:if test="${page_Num == pageInfo.pageNum }">
 88                             <li class="active"><a href="#">${page_Num }</a></li>
 89                         </c:if>
 90                         <c:if test="${page_Num != pageInfo.pageNum }">
 91                             <li><a href="${pageContext.request.contextPath }/emps?pn=${page_Num }">${page_Num }</a></li>
 92                         </c:if>
 93 
 94                     </c:forEach>
 95                     <c:if test="${pageInfo.hasNextPage }">
 96                         <li><a href="${pageContext.request.contextPath }/emps?pn=${pageInfo.pageNum+1 }"
 97                             aria-label="Next"> <span aria-hidden="true">&raquo;</span>
 98                         </a></li>
 99                     </c:if>
100                     <li><a href="${pageContext.request.contextPath }/emps?pn=${pageInfo.pages}">末页</a></li>
101                 </ul>
102                 </nav>
103             </div>
104         </div>
105         
106     </div>
107 </body>
108 </html>

前台员工信息列表

  d)下面先测试一下,能否访问首页,地址栏中输入http://localhost:8080/ssm_crud/index.jsp

  index.jsp中转发到了emps.action(处理器映射器会将该url映射到我们刚刚编写的Controller层的getEmps()方法,然后返回首页的数据)

 

 

作者:风沙迷了眼