SSM就是Spring,SpringMvc,MyBatis
Spring
Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。
Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地`new`一个对象,而是让Spring框架帮你来完成这一切。
SpringMVC
SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
mybatis
mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。
在最后面附了依赖
我的项目结构
第一步:先保证SpringMvc能正常运行
第二步:然后在测试MyBatis
第三步:再用Spring整合SpringMvc和MyBatis
完整实例
第一步:SpringMvc的配置
1.创建一个控制器StudentController
@Controller
public class StudentController {
@RequestMapping("testAll")
public String testAll(){
System.out.println("成功");
return "index";
}
}
2.创建springmvc的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!--注解扫描-->
<context:component-scan base-package="com.ywy"></context:component-scan>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
3.web.xml的配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--解决springmvc框架的中文乱码问题-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--springmvc的核心servlet-->
<servlet>
<servlet-name>springmvc</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>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
4.可以运行测试
第二步:然后在测试MyBatis
实体类Student
public class Student {
private Integer sid;
private String name;
private String sex;
private Integer age;
private Date time;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public Student(String name, String sex, Integer age, Date time) {
this.name = name;
this.sex = sex;
this.age = age;
this.time = time;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", time=" + time +
'}';
}
}
实体类的映射
<?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.ywy.mapper.StudentMapper">
<select id="findAllStudent" resultType="Student">
select * from student
</select>
</mapper>
1.创建mybatis的配置文件
<?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>
<!--给包取别名-->
<typeAliases>
<package name="com.ywy.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ywy/model/Student.xml"></mapper>
</mappers>
</configuration>
2.新建StudentMapper的接口
@Service//后面的StudentService的接口会报错
public interface StudentMapper {
//查询全部的方法
public List<Student> findAllStudent();
}
3.在pom.xml中加
<!--为了解决不加载java文件夹中xml的配置-->
<build>
<finalName>MySSM_01</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<!--。。。。。。-->
</build>
4.可以在控制器中测试的方法里面加(测试mybatis有没有用)
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(getClass().getClassLoader().getResourceAsStream("mybatis-config.xml"));
SqlSession session = factory.openSession();
StudentMapper smapper=session.getMapper(StudentMapper.class);
Liat<Student> list=smapper.findAllStudent();
System.out.println(list);
session.commit();
session.close();
前两步可用后,就进行第三步,也是最重要的一步
第三步:再用Spring整合SpringMvc和MyBatis
1.新建spring的配置文件applicationContxet.xml
这一步完后,可以将mybatis的配置文件删除
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:mybatis.properties"></context:property-placeholder>
<!--配置数据源 c3p0代替mybatis的数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="20"></property>
</bean>
<!--配置mybatis的sessionFactory工厂-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--配置别名-->
<property name="typeAliasesPackage" value="com.ywy.model"></property>
<!--配置实体类的映射-->
<property name="mapperLocations" value="classpath:com/ywy/model/*.xml"></property>
</bean>
<!--配置mapper的扫描-->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ywy.mapper"></property>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置项目中有哪些方法需要事务管理器-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置切入点-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.ywy.service.impl.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
</beans>
2.在web.xml中配置监听器和spring的环境
<!--配置spring的环境-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--这里是mybatis的乱码-->
<!--监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3.在service包中新建StudentService (代码和StudentMapper的接口一样)
public interface StudentService {
//查询全部的方法
public List<Student> findAllStudent();
}
4.新建一个impl实现包
在里面新建实现类StudentServiceImpl实现StudentService
@Service("studentService")//因为Controller里面会报错
public class StudentServiceImpl implements StudentService {
//需要一个StudentMapper的对象
//Autowired自动注入
@Autowired
private StudentMapper studentMapper;
@Override//查询全部的方法
public List<Student> findAllStudent() {
return studentMapper.findAllStudent();
}
}
5 .在回到Controller中
@Controller
public class StudentController {
//需要一个StudentService
@Autowired//自动注入
private StudentService studentService;
@RequestMapping("testAll")
public String testAll(){
System.out.println("成功");
for (Student student : studentService.findAllStudent()) {
System.out.println(student);
}
return "index";
}
}
6.测试
实例外的
我的util包,里面写的是自定义转换器,就是将String类型的转换成sql.Date
public class DateConverter implements Converter<String, Date> {
private Date time;
@Override
public Date convert(String s) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
java.util.Date d=sdf.parse(s);
time = new Date(d.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
}
然后必须在springmvc的配置文件中加
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置自己的转换工厂-->
<mvc:annotation-driven conversion-service="serviceFactoryBean"></mvc:annotation-driven>
<!--注解扫描-->
<context:component-scan base-package="com.ywy"></context:component-scan>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--自定义的转换工厂 引入的包是自定义和系统的都可以用-->
<bean id="serviceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.ywy.util.DateConverter"></bean>
</set>
</property>
</bean>
</beans>
依赖
需要在pom.xml的这个位置加上
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!--统一的版本号-->
<spring.version>5.1.5.RELEASE</spring.version>
</properties>
<!--MyBatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--MySQL的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.43</version>
</dependency>
<!--SpringMVC的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring连接数据库的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring配置切面的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring的上下文的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring和MyBatis和整合依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--C3p0的依赖-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.1</version>
</dependency>
<!--servlet的依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<!--jstl表达式-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>