SpringMVC + Spring + Mybatis 整合开发
SpringMVC:视图层,界面层,负责接收请求显示处理结果对象。
Spring:业务层,管理service,dao,工具类对象
Mybatis:持久层,访问数据库
流程:用户发起请求—>SpringMVC接收—>Spring中的Service对象---->Mybatis处理数据
SSM整合,其中有两个容器:
(1)SpringMVC容器:管理controller控制器对象还有web相关的对象交给springMVC管理,
(2)Spring容器:管理service,dao,工具类对象
springMVC是Spring的子容器,所以springMVC 中可以使用Spring容器中的对象,例如Controller中调用Service中的对象
SSM整合具体步骤:
1,新建maven webapp,导入所需依赖。
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!--springMVC依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--spring事务依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--jackson依赖,json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--数据库连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!--数据库连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
2,新建数据库ssm表student
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`email` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
3,编写web,xml文件
(1)注册 DispatcherServlet 中央调度器:
目的:创建SpringMVC容器对象,才能创建Controller类的对象,2,创建的Servlet才能接收用户的请求。
<!--注册SpringMVC中央调度器DispatcherServlet-->
<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:conf/dispatcherServlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
(2)注册Spring 的监听器 ContextLoaderListener,
目的:创建spring容器对象,才能创建service、dao对象
<!--将spring容器将给监听器创建-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(3)注册字符集过滤器,解决post请求乱码问题
<!--注册字符集过滤器-->
<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>
4,创建工程中的包结构
5,编写SpringMVC、Spring和mybatis的配置文件
(1)SpringMVC配置文件
dispatcherServlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--SpringMVC配置文件,用于声明Controller和其他web相关的对象-->
<!--声明组件扫描器-->
<context:component-scan base-package="com.lishizhan.controller"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--加注解驱动,因为用到响应Ajax返回json,和解决静态资源访问问题需要用到-->
<mvc:annotation-driven/>
</beans>
(2)Spring配置文件
applicationContext.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--Spring配置文件,声明service、dao,工具类等对象-->
<!--!声明数据源 DataSource,作用是链接数据库-->
<!--读取配文件中数据库中的信息-->
<context:property-placeholder location="classpath:conf/jdbcdruid.properties"/>
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!--set注入 DataSource提供数据库的信息-->
<!--使用配置文件中的数据-->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="${jdbc.max}"/>
</bean>
<!--声明mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--set注入,把数据库连接池付给-dataSource属性-->
<property name="dataSource" ref="myDataSource"/>
<!--mybatis主配置文件的位置-->
<property name="configLocation" value="classpath:conf/mybatis.xml"/>
</bean>
<!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)
MapperScannerConfigurer:在内部调用getMapper()生成每个Dao的代理对象
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定SqlSessionFactory对象id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--指定包名 包名是dao接口所在的包名。多个包逗号分割
MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行一次getMapper()方法,得到每个接口的到dao对象。
创建好的dao对象放在Spring容器中
-->
<property name="basePackage" value="com.lishizhan.dao"/>
</bean>
<!-- +++++++++++++++++++++++++++以上配置是固定的不需要记忆直接copy++++++++++++++++++++++++ -->
<!--声明service的注解所在的包-->
<context:component-scan base-package="com.lishizhan.service"/>
<!--事务的配置(注解方式或AspectJ方式)-->
<!--后续再加-->
</beans>
(3)Mybatis主配置文件
mybatis.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>
<!--打印日志-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--设置别名-->
<typeAliases>
<!--实体类所在的包名-->
<package name="com.lishizhan.domain"/>
</typeAliases>
<!-- 指定sql mapper(sql映射文件)的位置
从类路径开始的信息:target/classes类路径
-->
<mappers>
<!--包名,这个包中所有的mapper配置文件-->
<package name="com.lishizhan.dao"/>
</mappers>
</configuration>
(4)数据连接池配置文件
jdbcdruid.properties
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm
jdbc.user=root
jdbc.password=123456
jdbc.max=20
6,编写业务逻辑代码
(1)dao
public interface StudentDao {
public int insertStudent(Student student);
public List<Student> selectStudents();
}
StudentDao.xml
<?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.lishizhan.dao.StudentDao">
<insert id="insertStudent">
insert into t_student(name,email,age) values(#{name},#{email},#{age})
</insert>
<select id="selectStudents" resultType="com.lishizhan.domain.Student">
select id,name,email,age from t_student order by id desc ;
</select>
</mapper>
(2)service
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
return studentDao.insertStudent(student);
}
@Override
public List<Student> queryStudentAll() {
return studentDao.selectStudents();
}
}
(3)controller
@Controller
public class StudentController {
@Autowired
private StudentServiceImpl studentService;
@RequestMapping(value = "/addStu.do")
@ResponseBody
public ModelAndView addStu(Student student){
System.out.println(student);
ModelAndView mv = new ModelAndView();
int i = studentService.addStudent(student);
System.out.println("注册结果:"+i);
if (i>0){
mv.addObject("msg", "注册成功!!");
}else {
mv.addObject("msg", "注册失败!!");
}
mv.setViewName("register");
return mv;
}
}