SSM框架整合
完整的SSM整合环境源码见我的Gitee:https://gitee.com/coydone/ssm_crud
搭建整合环境
整合说明:SSM整合可以使用多种方式,建议选择XML + 注解的方式。
整合的思路:我们是用Spring框架去整合其它两个框架,先搭建整合的环境,先把Spring的配置搭建完成,再使用Spring整合MyBatis框架,最后使用Spring整合SpringMVC框架。
1、创建数据库和表结构
- grade年级表:字段:年级编号:gid;年级名称:gname。
- student学生表:字段:学号:xh;学生名:name;年龄:age;性别:sex;birthday:生日;state:状态;地址:address;年级编号:gid。
此为一对多关系的两张表,一个年级有多个学生。
2、创建Maven的javaweb工程
<groupId>com.coydone</groupId>
<artifactId>ssm_crud</artifactId>
3、创建包结构
在src/main
下创建文件夹java和resources文件夹,并将其改为源代码目录和资源目录。可以在src下创建test文件夹,将其改为test的测试目录,在test下创建java和resources目录(可以参考Maven工程的目录结构)。
在main/java
下创建com.coydone包,在其下创建包结构:entity、mapper、service、controller、utils包,可以创建一个test包用于测试。
4、配置pom文件中的环境
- 配置ssm的所需依赖
- 配置项目创建和运行的环境
<?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>
搭建Mybatis的环境
1、编写数据库连接文件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
2、编写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环境
由于SpringMVC是Spring系列的一部分,Spring对SpringMVC的集成基本上是天然集成。
1、编写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>
2、配置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整合
编写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代码自动生成
1、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>
2、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();
}
}
}
测试整合环境
单元测试
1、测试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());
}
}
}
2、测试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());
}
}
}
功能测试
1、业务层接口
package com.coydone.service;
import com.coydone.entity.Student;
import java.util.List;
public interface StudentService {
List<Student> getAll();
}
2、业务层实现类
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());
}
}
3、编写控制器
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";
}
}
4、编写页面显示数据
<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>