完整的SSM整合環境源碼見個人Gitee:https://gitee.com/coydone/ssm_crudcss
整合說明:SSM整合能夠使用多種方式,建議選擇XML + 註解的方式。java
整合的思路:咱們是用Spring框架去整合其它兩個框架,先搭建整合的環境,先把Spring的配置搭建完成,再使用Spring整合MyBatis框架,最後使用Spring整合SpringMVC框架。mysql
一、建立數據庫和表結構git
此爲一對多關係的兩張表,一個年級有多個學生。github
二、建立Maven的javaweb工程web
<groupId>com.coydone</groupId> <artifactId>ssm_crud</artifactId>
三、建立包結構spring
在src/main
下建立文件夾java和resources文件夾,並將其改成源代碼目錄和資源目錄。能夠在src下建立test文件夾,將其改成test的測試目錄,在test下建立java和resources目錄(能夠參考Maven工程的目錄結構)。sql
在main/java
下建立com.coydone包,在其下建立包結構:entity、mapper、service、controller、utils包,能夠建立一個test包用於測試。數據庫
四、配置pom文件中的環境express
<?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.coydone</groupId> <artifactId>ssm_crud</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm_crud 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.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!--SpringMVC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <!--mybatis和Spring整合適配包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.5</version> </dependency> <!--鏈接池、數據庫驅動--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--jstl、servlet-api、junit--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--逆向工程--> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.3</version> </dependency> <!-- 文件上傳 start --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.1</version> </dependency> <!-- 文件上傳 end --> <!--添加mybatis分頁插件支持--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> <!-- 添加jackson支持 start--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <!-- 添加jackson支持 end --> <!-- Gson start --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency> <!-- Gson end --> </dependencies> <build> <finalName>ssm_crud</finalName> <pluginManagement> ...... </pluginManagement> <plugins> <!-- 編譯插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <path>/</path> <uriEncoding>UTF-8</uriEncoding> <server>tomcat7</server> </configuration> </plugin> </plugins> <!--將源碼目錄中的xml文件一塊兒打包發佈--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> </resources> </build> </project>
一、編寫數據庫鏈接文件db.properties
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/k0503db?useUnicode=true&characterEncoding=utf-8&useSSL=false jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=root123
二、編寫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"> <!--mybatis的核心配置文件--> <configuration> <settings> <!--下劃線轉駝峯--> <setting name="mapUnderscoreToCamelCase" value="true"/> <!--配置日誌--> <!-- <setting name="logImpl" value="STDOUT_LOGGING"/>--> </settings> <typeAliases> <!--掃描包:配置實體別名爲實體名--> <package name="com.coydone.entity"></package> </typeAliases> <plugins> <!--分頁配置--> <!-- 5.0 com.github.pagehelper.PageInterceptor --> <!-- 4.x com.github.pagehelper.PageHelper --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 在spring5版本不須要指定數據庫 --> <!-- <property name="dialect" value="mysql"></property>--> <!-- 3.3.0版本可用 - 分頁參數合理化,默認false禁用 --> <!-- 啓用合理化時,若是pageNum<1會查詢第一頁,若是pageNum>pages會查詢最後一頁 --> <!-- 禁用合理化時,若是pageNum<1或pageNum>pages會返回空數據 --> <!-- <property name="reasonable" value="true"/>--> </plugin> </plugins> </configuration>
咱們將Mybatis的配置交給spring的ioc容器進行管理,因此Mybatis中再也不配置鏈接數據庫等相關信息。
因爲SpringMVC是Spring系列的一部分,Spring對SpringMVC的集成基本上是自然集成。
一、編寫springmvc配置文件springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--開啓spring註解掃描包--> <context:component-scan base-package="com.coydone" use-default-filters="false"> <!--只掃描控制器--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--配置視圖解析器--> <!--視圖解析器會自動拼接路徑--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--配置前綴 value="/WEB-INF/jsp/pages/" --> <property name="prefix" value="/"></property> <!--配置後綴--> <property name="suffix" value=".jsp"></property> </bean> <!--配置可以訪問到的靜態資源的目錄 HTML js css--> <!--<mvc:resources mapping="/static/images/**" location="/static/images/"></mvc:resources>--> <!-- 容器默認的DefaultServletHandler處理全部靜態內容與無RequestMapping處理的URL--> <!--只攔截請求,不攔截靜態資源--> <mvc:default-servlet-handler/> <!--開啓springmvc的註解驅動--> <mvc:annotation-driven></mvc:annotation-driven> <!--配置文件上傳--> <!--必定要寫:multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--默認的字符編碼--> <property name="defaultEncoding" value="utf-8"></property> <!--配置單文件最大上傳大小 單位:byte 限制1M:1024*1024--> <property name="maxUploadSizePerFile" value="1048576"></property> <!--配置總文件最大上傳大小 限制100M--> <property name="maxUploadSize" value="104857600"></property> </bean> </beans>
二、配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置歡迎頁--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!--配置亂碼的過濾器--> <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>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--restful風格,將post請求轉爲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> <!--配置全局參數--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--監聽全局配置參數--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置springmvc的核心攔截器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
編寫spring的配置文件:applicationContext.xml,整合mybatis和springmvc。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--開啓spring的註解驅動掃描包--> <context:component-scan base-package="com.coydone"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--使用spring配置數據源--> <!--c3p0的配置--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--配置與mybatis的整合--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--數據源--> <property name="dataSource" ref="dataSource"></property> <!--mapper文件的位置--> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> <!--指定mybatis全局配置文件的位置--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!--配置掃描器,加載mapper的接口文件--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--掃描全部的mapper接口--> <property name="basePackage" value="com.coydone.mapper"></property> </bean> <!-- 配置一個能夠執行批量的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> <!--事務控制--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--控制數據源--> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置基於xml的aop--> <aop:config> <!--切入點表達式--> <aop:pointcut id="txPoint" expression="execution(* com.coydone.service..*(..))"/> <!--配置事務加強--> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"></aop:advisor> </aop:config> <!--配置事務加強如何切入--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--切入的全部方法都是事務方法--> <tx:method name="*"/> <!--以get開頭的全部方法--> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> </beans>
一、MBG的xml配置文件,放在resources下:generator.xml
鏈接的數據庫及其設置的數據庫表根據本身的需求進行修改便可。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 指定MBG的數據庫鏈接驅動,由於它使用的不是項目的jar包 --> <!-- <classPathEntry location="D:\mysql-connector-java-5.1.0-bin.jar" />--> <context id="Mysql2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"></property> <property name="suppressAllComments" value="true"></property> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/k0503db" userId="root" password="root123"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--指定生成實體全部在的包--> <javaModelGenerator targetPackage="com.coydone.entity" targetProject="ssm_crud/src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--指定sql映射文件的位置--> <sqlMapGenerator targetPackage="mapper" targetProject="ssm_crud/src/main/resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!--指定接口存放的位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.coydone.mapper" targetProject="ssm_crud/src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <table tableName="grade" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false"> </table> <table tableName="student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
二、MBG的工具類,運行main方法就能夠自動生成了。它會幫咱們自動生成實體類entity、mapper及其mapper.xml文件,咱們只須要編寫業務層和控制器就能夠了。
package com.coydone.utils; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class MybatisGeneratorUtil { public static void main(String[] args) { try { System.out.println("start generator ..."); List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File(MybatisGeneratorUtil.class.getResource("/generator.xml").getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); System.out.println("end generator!"); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
一、測試Spring整合Mybatis環境
package com.coydone.test; import com.coydone.entity.Grade; import com.coydone.entity.Student; import com.coydone.mapper.GradeMapper; import com.coydone.mapper.StudentMapper; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import java.util.UUID; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class StudentMapperTest { @Autowired private StudentMapper studentMapper; @Autowired private GradeMapper gradeMapper; @Autowired //執行批量操做 private SqlSession sqlSession; @Test public void getAllStudent(){ List<Student> students = studentMapper.selectByExample(null); for (Student student : students) { System.out.println(student); } } @Test public void getAllGrade(){ List<Grade> grades = gradeMapper.selectByExample(null); for (Grade grade : grades) { System.out.println(grade); } } @Test //批量添加 public void addMore(){ StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); String uuid = UUID.randomUUID().toString().substring(0, 5); for (int i = 0; i < 1000; i++) { mapper.insertSelective(new Student()); } } }
二、測試Spring整合SpringMVC環境
package com.coydone.test; import com.coydone.entity.Student; import com.github.pagehelper.PageInfo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.util.List; //使用spring測試模塊提供的測試請求功能,測試請求crud //spring4測試須要servlet3.0的支持 @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:springmvc.xml"}) public class StudentControllerTest { //傳入SpringMVC的ioc @Autowired private WebApplicationContext context; //虛擬mvc請求,獲取處處理結果 private MockMvc mockMvc; @Before public void initMockMvc(){ mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } //測試分頁 @Test public void testPage() throws Exception { //模擬請求拿到返回值 MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/getAll2") .param("pn", "1")).andReturn(); //請求成功後,request域中會有pageInfo,咱們能夠取出進行驗證 MockHttpServletRequest request = result.getRequest(); PageInfo pageInfo = (PageInfo) request.getAttribute("pageInfo"); System.out.println("當前頁碼:"+pageInfo.getPageNum()); System.out.println("總頁碼:"+pageInfo.getPages()); System.out.println("總記錄數:"+pageInfo.getTotal()); System.out.println("在頁面須要連續顯示的頁碼:"); int[] nums = pageInfo.getNavigatepageNums(); for (int num : nums) { System.out.print(" "+num); } //獲取學生數據 List<Student> list = pageInfo.getList(); for (Student student : list) { System.out.println(student.getName()); } } }
一、業務層接口
package com.coydone.service; import com.coydone.entity.Student; import java.util.List; public interface StudentService { List<Student> getAll(); }
二、業務層實現類
package com.coydone.service.impl; import com.coydone.entity.Student; import com.coydone.entity.StudentExample; import com.coydone.mapper.StudentMapper; import com.coydone.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("studentService") public class StudentServiceImpl implements StudentService { @Autowired private StudentMapper studentMapper; @Override public List<Student> getAll() { return studentMapper.selectByExample(new StudentExample()); } }
三、編寫控制器
package com.coydone.controller; import com.coydone.entity.Student; import com.coydone.service.StudentService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller public class StudentController { @Autowired private StudentService studentService; @RequestMapping("/getAll") public String getAll(Model model){ List<Student> students = studentService.getAll(); model.addAttribute("students",students); return "index"; } @RequestMapping("/getAll2") //分頁查詢 public String getAll2(@RequestParam(value = "pn",defaultValue = "1")Integer pn,Model model){ //引入分頁插件,在查詢以前只須要調用,查詢的頁碼,和每頁大小 PageHelper.startPage(pn,5); //startPage後緊跟的查詢就是分頁查詢 List<Student> students = studentService.getAll(); //使用pageInfo包裝查詢後的結果,只須要將pageInfo交給頁面就好了 //封裝了詳細的信息,包括查詢出來的數據,傳入連續顯示的頁數 PageInfo pageInfo = new PageInfo(students,5); model.addAttribute("pageInfo",pageInfo); return "index"; } }
四、編寫頁面顯示數據
<c:forEach items="${students}" var="student"> <tr> <td>${student.xh}</td> <td>${student.name}</td> <td>${student.age}</td> <td>${student.sex}</td> <td>${student.birthday}</td> <td>${student.state}</td> <td>${student.address}</td> </tr> </c:forEach>