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


    搭建各个模块的测试环境

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

    整合的思路

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

    先把Spring的配置搭建完成

    再使用Spring整合SpringMVC框架

    最后使用Spring整合MyBatis框架

    整合的porm.xml

    <dependencies> <dependency>   <groupId>org.aspectjgroupId>   <artifactId>aspectjweaverartifactId>   <version>1.6.8version> dependency>  <dependency>   <groupId>org.springframeworkgroupId>   <artifactId>spring-aopartifactId>   <version>${spring.version}version> dependency>  <dependency>   <groupId>org.springframeworkgroupId>   <artifactId>spring-contextartifactId>   <version>${spring.version}version> dependency>  <dependency>   <groupId>org.springframeworkgroupId>   <artifactId>spring-webartifactId>   <version>${spring.version}version> dependency>  <dependency>   <groupId>org.springframeworkgroupId>   <artifactId>spring-webmvcartifactId>   <version>${spring.version}version> dependency>  <dependency>   <groupId>org.springframeworkgroupId>   <artifactId>spring-testartifactId>   <version>${spring.version}version> dependency> <dependency>   <groupId>org.springframeworkgroupId>   <artifactId>spring-txartifactId>   <version>${spring.version}version> dependency> <dependency>   <groupId>org.springframeworkgroupId>   <artifactId>spring-jdbcartifactId>   <version>${spring.version}version> dependency> <dependency>   <groupId>junitgroupId>   <artifactId>junitartifactId>   <version>4.12version>   <scope>testscope> dependency> <dependency>   <groupId>mysqlgroupId>   <artifactId>mysql-connector-javaartifactId>   <version>${mysql.version}version> dependency> <dependency>   <groupId>javax.servletgroupId>   <artifactId>servlet-apiartifactId>   <version>2.5version>   <scope>providedscope> dependency> <dependency>   <groupId>javax.servlet.jspgroupId>   <artifactId>jsp-apiartifactId>   <version>2.0version>   <scope>providedscope> dependency> <dependency>   <groupId>jstlgroupId>   <artifactId>jstlartifactId>   <version>1.2version> dependency>  <dependency>   <groupId>log4jgroupId>   <artifactId>log4jartifactId>   <version>${log4j.version}version> dependency> <dependency>   <groupId>org.slf4jgroupId>   <artifactId>slf4j-apiartifactId>   <version>${slf4j.version}version> dependency> <dependency>   <groupId>org.slf4jgroupId>   <artifactId>slf4j-log4j12artifactId>   <version>${slf4j.version}version> dependency>   <dependency>   <groupId>org.mybatisgroupId>   <artifactId>mybatisartifactId>   <version>${mybatis.version}version> dependency>  <dependency>   <groupId>org.mybatisgroupId>   <artifactId>mybatis-springartifactId>   <version>1.3.0version> dependency> <dependency>   <groupId>c3p0groupId>   <artifactId>c3p0artifactId>   <version>0.9.1.2version>   <type>jartype>   <scope>compilescope> dependency>dependencies>

    java思维导图获取路径

    搭建和测试Spring框架

    1. 创建ApplicationContext.xml文件
    <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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd">        <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框架

    1. 在web.xml中配置DispatcherServlet前端控制器、编码过滤器
     <filter>  <filter-name>encodingfilter-name>  <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  <init-param>    <param-name>encodingparam-name>    <param-value>UTF-8param-value>  init-param>filter><filter-mapping>  <filter-name>encodingfilter-name>  <url-pattern>/*url-pattern>filter-mapping><servlet>  <servlet-name>dispatcherServletservlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  <init-param>    <param-name>contextConfigLocationparam-name>    <param-value>classpath:SpringMVC.xmlparam-value>  init-param>  <load-on-startup>1load-on-startup>servlet><servlet-mapping>  <servlet-name>dispatcherServletservlet-name>  <url-pattern>/url-pattern>servlet-mapping>
    • 创建SpringMVC.xml的配置文件,编写配置文件
    <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="controller">context:component-scan>        <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框架

    1. 在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件
    configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>        <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>        <mappers>                        <package name="dao"/>    mappers>configuration>
    • 在AccountDao接口的方法上添加注解,编写SQL语句
    public interface AccountDao {    //查询所有    @Select("select * from account")    public List 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框架

    1. 目的:在controller中能成功的调用service业务层对象中的方法。
    2. 整合原理

     

    实现步骤

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

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

    更多java资料点击此处领取

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

    <listener>    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>listener><context-param>    <param-name>contextConfigLocationparam-name>    <param-value>classpath:ApplicationContext.xmlparam-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框架

    1. 把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中,服务器在一启动就会加载该配置文件
    <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><bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">   <property name="dataSource" ref="DataSource">property>bean><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 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 findAll() {        System.out.println("业务层:findAll方法执行了...");        List 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 accounts = accountService.findAll();        model.addAttribute("accounts",accounts);        return "success";    }}

    配置Spring的声明式事务控制

    1. 因为控制的是业务层,所以在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>                  <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>                  <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;}

  • 相关阅读:
    设计模式(二十五)----行为型模式之访问者模式
    计算机视觉算法——基于Anchor Free的目标检测网络总结
    常用lambda表达式
    java基础之成员与局部变量以及this与static关键字[15]
    html:mate
    Vector-常用CAN工具 - CANoe入门到精通_02
    SQL Server详细使用教程
    会话结束原因:tcp-rst-from-server 常见原因分析和解决办法
    eclipse中使用Maven
    Java设计模式之组合模式
  • 原文地址:https://blog.csdn.net/lt_xiaodou/article/details/126156347