一、搭建环境
(1)创建数据库,导入数据
(2)导入依赖坐标,创建子模块
(3)编写domain实体类,service层和dao层接口
public class Account implements Serializable{
private Integer id; private String name; private Double money;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Double getMoney() { return money; }
public void setMoney(Double money) { this.money = money; }
@Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
|
@Repository public interface AccountDao {
public List<Account> findAll();
public void saveAccount(Account account);
}
public interface AccountService {
public List<Account> findAll();
public void saveAccount(Account account);
}
|
二、Spring框架
Spring作为ssm整合的基础,通过spring来与其他两个框架分别进行整合。先将三个框架,分别独立运行再整合。先保证Spring框架在web工程中独立运行
第一步:编写spring配置文件并导入约束
由于只希望处理service和dao的注解@,controller不需要Spring框架去处理,有专门的SpringMVC层的注解去处理
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/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">
<context:component-scan base-package="cn.itcast" > <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
|
第二步:使用注解配置业务层和持久层
service层实现类 和 dao层注解配置
@Service("accountService") public class AccountServiceImpl implements AccountService{
@Autowired private AccountDao accountDao;
@Override public List<Account> findAll() { System.out.println("业务层:查询所有账户..."); return accountDao.findAll(); }
@Override public void saveAccount(Account account) { System.out.println("业务层:保存帐户..."); accountDao.saveAccount(account); } }
|
持久层实现类代码: 此时不要做任何操作,就输出一句话。目的是测试spring框架搭建的结果。
@Repository public interface AccountDao {
@Select("select * from account") public List<Account> findAll();
@Insert("insert into account (name,money) values (#{name},#{money})") public void saveAccount(Account account);
}
|
public class TestSpring {
@Test public void testSpring(){ ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); AccountService as = (AccountService) ac.getBean("accountService"); as.findAll(); }
}
|
三、SpringMVC框架
开始整合Spring与SpringMVC的。保证SpringMVC在web工程中独立运行
(1)第一步:在web.xml中配置核心控制器(DispatcherServlet)和 解决中文乱码的过滤器
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
<context-param> <param-name/> <param-value/> </context-param>
<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> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
<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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
(2)第二步:编写SpringMVC的配置文件
注解扫描,只扫描Controller注解
<?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">
<context:component-scan base-package="cn.itcast"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean>
<mvc:resources location="/css/" mapping="/css/**" /> <mvc:resources location="/images/" mapping="/images/**" /> <mvc:resources location="/js/" mapping="/js/**" />
<mvc:annotation-driven/>
|
(3)第三步:编写Controller和jsp页面
@Controller @RequestMapping("/account") public class AccountController {
@Autowired private AccountService accountService;
@RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层:查询所有账户..."); List<Account> list = accountService.findAll(); model.addAttribute("list",list); return "list"; }
@RequestMapping("/save") public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { accountService.saveAccount(account); response.sendRedirect(request.getContextPath()+"/account/findAll"); return; }
}
|
四、Spring整合SpringMVC
整合Spring和SpringMVC,因为要在SpringMVC的Controller中使用service层的bean对象。则需要在服务器启动时,就将Spring的配置文件(applicationContext.xml)加载,将其中的bean导入IOC容器中。
@Autowired private AccountService accountService;
|
需要配置监听器实现启动服务创建容器
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
|
五、Mybatis框架
保证MyBatis框架在web工程中独立运行
(1)第一步:编写SqlMapConfig配置文件
<?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> <properties resource="jdbcConfig.properties"></properties> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="pooled"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments>
<mappers> <package name="cn.itcast.dao"/> </mappers>
</configuration>
properties文件中的内容: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.username=root jdbc.password=1234
|
测试一下Mybatis的运行结果
public class TestMyBatis {
@Test public void run1() throws Exception { InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); SqlSession session = factory.openSession(); AccountDao dao = session.getMapper(AccountDao.class); List<Account> list = dao.findAll(); for(Account account : list){ System.out.println(account); } session.close(); in.close(); }
|
六、Spring整合Mybatis
由于我们使用的是代理Dao的模式,Dao具体实现类由MyBatis使用代理方式创建,所以此时mybatis配置文件(SqlMapConfig.xml)不能删。 当我们整合spring和mybatis时,mybatis创建的Mapper.xml文件名必须和Dao接口文件名一致
(1)第一步:Spring接管MyBatis的Session工厂
将Mybatis的SqlSessionFactory交由Spring来控制,当做组件。有了工厂便可以创建SqlSession,然后就可以创建代理对象AccountDao,来执行方法。
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost/ssm"/> <property name="user" value="root"/> <property name="password" value="xmgl0609"/> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean>
|
(2)第二步:配置自动扫描所有Mapper接口和文件
这个作用相当于SqlMapConfig.xml,来得到dao下的配置信息和映射文件。我们就不需要在resources里面配置SqlMapConfig.xml了。
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.itcast.dao"/> </bean>
|
(3)第三步:配置spring的事务(AOP)
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice>
<aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/> </aop:config>
|
最后编写jsp来访问Controller,然后来调用service层的方法。返回到指定页面进行显示
@Controller @RequestMapping("/account") public class AccountController {
@Autowired private AccountService accountService;
@RequestMapping("/findAll") public String findAll(Model model){ System.out.println("表现层:查询所有账户..."); List<Account> list = accountService.findAll(); model.addAttribute("list",list); return "list"; }
@RequestMapping("/save") public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { accountService.saveAccount(account); response.sendRedirect(request.getContextPath()+"/account/findAll"); return; }
}
|