龙空技术网

全网最全面的SSM整合(没有之一)

JAVA互联搬砖工人 155

前言:

眼前朋友们对“ssm整合jar包”可能比较关切,同学们都需要剖析一些“ssm整合jar包”的相关内容。那么小编在网上网罗了一些有关“ssm整合jar包””的相关文章,希望姐妹们能喜欢,姐妹们一起来学习一下吧!

搭建各个模块的测试环境

整合说明:我们通常使用Spring框架来整合SpringMVC和Mybatis,且使用注解+XML的形式

整合的思路

先搭建整合的环境(porm.xml)

先把Spring的配置搭建完成

再使用Spring整合SpringMVC框架

最后使用Spring整合MyBatis框架

整合的porm.xml

<dependencies><!-- 用来解析切入点表达式 --> <dependency>   <groupId>org.aspectj</groupId>   <artifactId>aspectjweaver</artifactId>   <version>1.6.8</version> </dependency> <!-- spring中的aop --> <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-aop</artifactId>   <version>${spring.version}</version> </dependency> <!-- spring中的ioc --> <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-context</artifactId>   <version>${spring.version}</version> </dependency> <!-- 用于springWEB结构的整合 --> <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-web</artifactId>   <version>${spring.version}</version> </dependency> <!-- springMVC,依赖于spring-web --> <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-webmvc</artifactId>   <version>${spring.version}</version> </dependency> <!--用了整合junit--> <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-test</artifactId>   <version>${spring.version}</version> </dependency><!--spring的事务控制--> <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-tx</artifactId>   <version>${spring.version}</version> </dependency><!-- jdbcTemplate --> <dependency>   <groupId>org.springframework</groupId>   <artifactId>spring-jdbc</artifactId>   <version>${spring.version}</version> </dependency> <dependency>   <groupId>junit</groupId>   <artifactId>junit</artifactId>   <version>4.12</version>   <scope>test</scope> </dependency> <dependency>   <groupId>mysql</groupId>   <artifactId>mysql-connector-java</artifactId>   <version>${mysql.version}</version> </dependency> <dependency>   <groupId>javax.servlet</groupId>   <artifactId>servlet-api</artifactId>   <version>2.5</version>   <scope>provided</scope> </dependency> <dependency>   <groupId>javax.servlet.jsp</groupId>   <artifactId>jsp-api</artifactId>   <version>2.0</version>   <scope>provided</scope> </dependency> <dependency>   <groupId>jstl</groupId>   <artifactId>jstl</artifactId>   <version>1.2</version> </dependency> <!-- log start --> <dependency>   <groupId>log4j</groupId>   <artifactId>log4j</artifactId>   <version>${log4j.version}</version> </dependency> <dependency>   <groupId>org.slf4j</groupId>   <artifactId>slf4j-api</artifactId>   <version>${slf4j.version}</version> </dependency> <dependency>   <groupId>org.slf4j</groupId>   <artifactId>slf4j-log4j12</artifactId>   <version>${slf4j.version}</version> </dependency> <!-- log end -->  <dependency>   <groupId>org.mybatis</groupId>   <artifactId>mybatis</artifactId>   <version>${mybatis.version}</version> </dependency> <!-- mybatis与spring整合的中间jar包 --> <dependency>   <groupId>org.mybatis</groupId>   <artifactId>mybatis-spring</artifactId>   <version>1.3.0</version> </dependency> <dependency>   <groupId>c3p0</groupId>   <artifactId>c3p0</artifactId>   <version>0.9.1.2</version>   <type>jar</type>   <scope>compile</scope> </dependency></dependencies>
搭建和测试Spring框架创建ApplicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:xsi=";       xmlns:context=";       xmlns:aop=";       xmlns:tx=";       xsi:schemaLocation="							;>    <!--Spring框架只需要负责业务层和持久层即可,controller由SpringMVC框架来负责-->    <context:component-scan base-package="service"></context:component-scan>    <context:component-scan base-package="dao"></context:component-scan></beans>
在测试类中测试业务层方法
public class TestSpring {    private AccountService accountService;    @Before    public void init(){        ApplicationContext ac=new ClassPathXmlApplicationContext("ApplicationContext.xml");        accountService = ac.getBean("accountService", AccountService.class);    }    @Test    public void testSpring(){        accountService.findAll();    }}
搭建和测试SpringMVC框架在web.xml中配置DispatcherServlet前端控制器、编码过滤器
 <!--配置编码过滤器--><filter>  <filter-name>encoding</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>encoding</filter-name>  <url-pattern>/*</url-pattern></filter-mapping><!--配置前端控制器--><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>
创建SpringMVC.xml的配置文件,编写配置文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:mvc=";       xmlns:context=";       xmlns:xsi=";       xsi:schemaLocation="                                          ;>    <!--扫描Controller包下的注解-->    <context:component-scan base-package="controller"></context:component-scan>    <!--开启SpringMVC的注解支持-->    <mvc:annotation-driven></mvc:annotation-driven>    <!--视图解析器-->    <bean id="viewController" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="pages/"></property>        <property name="suffix" value=".jsp"></property>    </bean>    <!--静态资源不过滤-->    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>    <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources></beans>
创建AccountController类,编写方法,进行测试
@Controllerpublic class AccountController {    @RequestMapping("testMVC")    public String testMVC(){        System.out.println("testMVC执行了!");        return "success";    }}
搭建和测试Mybatis框架在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        ";><configuration>    <!--配置主环境(使用mysql的环境)-->    <environments default="mysql">        <environment id="mysql">            <transactionManager type="JDBC"></transactionManager>            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>                <property name="username" value="root"/>                <property name="password" value="123456"/>            </dataSource>        </environment>    </environments>    <!--配置mapper映射关系 这里使用注解-->    <mappers>        <!--<mapper class="dao.AccountDao"></mapper>-->        <!--该包下的所有dao接口都可以使用-->        <package name="dao"/>    </mappers></configuration>
在AccountDao接口的方法上添加注解,编写SQL语句
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 TestMybatis {    AccountDao proxyAccount;    SqlSession session;    InputStream in;    @Before    public void init() throws Exception {        //加载配置文件        in = Resources.getResourceAsStream("SqlMapConfig.xml");        //创建SqlSessionFactory工厂        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);        //根据工厂创建SqlSession对象        session = factory.openSession();        //创建代理对象        proxyAccount = session.getMapper(AccountDao.class);    }    @After    public void destroy() throws IOException {        //提交事务        session.commit();        session.close();        in.close();    }    @Test    public void testMybatis() {        Account account=new Account();        account.setName("lisi");        account.setMoney(200d);        //测试保存        proxyAccount.saveAccount(account);    }}
搭建各个模块之间的整合Spring整合SpringMVC框架目的:在controller中能成功的调用service业务层对象中的方法。整合原理

实现步骤

在项目启动的时候,就去加载applicationContext.xml的配置文件,创建好容器

在web.xml中配置ContextLoaderListener监听器(该监听器默认只能加载WEB-INF目录下的applicationContext.xml的配置文件)

在controller中注入service对象,调用service对象的方法进行测试

<!--  配置Spring的监听器(监听ServletContext域对象的创建与销毁)  当ServletContext域对象被创建(服务器一开启),默认加载WEB-INF下的applicationContext.xml文件  但是我们的Spring的配置文件在类路径下  需要配置加载类路径下的配置文件,使用<context-param>标签--><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>
@Controllerpublic class AccountController {    @Autowired    private AccountService accountService;    @RequestMapping("testMVC")    public String testMVC(){        System.out.println("表现层:testMVC执行了!");        accountService.findAll();        return "success";    }}
Spring整合Mybatis框架把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中,服务器在一启动就会加载该配置文件
<!--Spring整合Mybatis--><!--配置连接池--><bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">   <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>   <property name="url" value="jdbc:mysql://localhost:3306/ssm"></property>   <property name="username" value="root"></property>   <property name="password" value="123456"></property></bean><!--配置SqlSessionFactory对象--><bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">   <property name="dataSource" ref="DataSource"></property></bean><!--配置mappers映射,使用注解形式(要扫描的包)--><bean id="mappers" class="org.mybatis.spring.mapper.MapperScannerConfigurer">   <property name="basePackage"  value="dao"></property></bean>
在AccountDao接口中添加@Repository注解

将持久层的代理对象存入容器

@Repositorypublic interface AccountDao {    //查询所有    @Select("select * from account")    public List<Account> findAll();    //保存    @Insert("insert into account (name,money) values(#{name},#{money}) ")    public void saveAccount(Account account);}
在service中注入dao对象
@Service("accountService")public class AccountServiceImpl implements AccountService {    @Autowired    private AccountDao accountDao;    @Override    public List<Account> findAll() {        System.out.println("业务层:findAll方法执行了...");        List<Account> lists = accountDao.findAll();        return lists;    }}
在表现层controller中进行测试
@Controllerpublic class AccountController {    @Autowired    private AccountService accountService;    @RequestMapping("testMVC")    public String testMVC(ModelMap model){        System.out.println("表现层:testMVC执行了!");        List<Account> accounts = accountService.findAll();        model.addAttribute("accounts",accounts);        return "success";    }}
配置Spring的声明式事务控制因为控制的是业务层,所以在Spring的配置文件中开启声明式事务控制
<!--Spring中配置声明式事务控制--> <!--事务管理器--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">     <property name="dataSource" ref="DataSource"></property> </bean> <!--事务通知--> <tx:advice id="txAdvice" transaction-manager="txManager">     <tx:attributes>         <!--切入点方法为find...时,该事务为只读,且可以不开启事务管理-->         <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>         <!--切入点方法除了find...时,该事务必须有事务管理-->         <tx:method name="*" propagation="REQUIRED"></tx:method>     </tx:attributes> </tx:advice> <!--切入点与事务通知进行关联--> <aop:config>     <aop:pointcut id="pt1" expression="execution(* service.impl.*.*(..))"/>     <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor> </aop:config>
测试保存方法
@RequestMapping("testSave")public void testSave(Account account,HttpServletRequest req, HttpServletResponse resp) throws IOException {    System.out.println("表现层:testSave执行了!");    accountService.saveAccount(account);    resp.sendRedirect(req.getContextPath()+"/testFindAll");    return;}

喜欢的可以关注一下 转发一下 会不定时更新干货内容哦!

标签: #ssm整合jar包