Java学习之SSM框架整合

2022-07-13 19:30:52 浏览数 (1)

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

Java学习之SSM框架整合

0x00 前言

前面的学习的Spring、Spring MVC 和Mybatis框架基本已经学习完了,但是要使用起来,我们需要把这三大框架给整合起来一起使用。

0x01 Spring 整合Spring MVC

首先要先把Spring 和Spring MVC 给整合起来,能正常运行后,再去整合Mybatis。

这里来配置一下坐标,把要使用的jar包都配置一下。

pom.xml:

代码语言:javascript复制
<properties>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

 <dependencies>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.8</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <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>compile</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>
  <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>

编写一个实体类:

代码语言:javascript复制
import java.io.Serializable;

public class Account implements Serializable {
    private int id;
    private String name;

    public Account() {
    }

    public Account(int id, String name, double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

    private double money;

    public int getId() {
        return id;
    }

    public void setId(int 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;
    }
}

dao 接口:

代码语言:javascript复制
public interface Accountdao {
    List<Account> findAll();
    void saveAccount();

}

web.xml文件:

代码语言:javascript复制
<!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>
  <servlet>
<!--    配置前端控制器-->
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
<!--      配置加载springmvc.xml文件-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </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>
<!--  使用监听器加载spring.xml文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationcontenxt.xml</param-value>
  </context-param>


</web-app>

applicationcontent.xml文件:

代码语言:javascript复制
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--    开启注解扫描-->
    <context:component-scan base-package="com.test">
<!--        配置不扫描Controller注解-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        
    </context:component-scan>
    

</beans>

这里需要配置不扫描Controller注解,Controller要交给Spring mvc来操作。

spring mvc.xml文件:

代码语言:javascript复制
<?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">
    <!-- 扫描controller的注解,别的不扫描 -->
    <context:component-scan base-package="com.test">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- JSP文件所在的目录 -->
        <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/**" />
    <!-- 开启对SpringMVC注解的支持 -->
    <mvc:annotation-driven />
</beans>

这些配置完后,就可以来写其他的类了。

service接口:

代码语言:javascript复制
public interface Accountservice {
    List<Account> findAll();
    void saveAccount(Account account);

}

service实现类:

代码语言:javascript复制
@Service("accountserivce")
public class AccountserivceImpl implements Accountservice{
    @Override
    public List<Account> findAll() {
        System.out.println("业务层,查询所有账户信息");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层,保存用户信息");

    }
}

最后一步,编写controller类:

代码语言:javascript复制
@Service("accountserivce")
//当Spring要创建AccountServiceImpl的的实例时,bean的名字必须叫做accountserivce
public class AccountserivceImpl implements Accountservice{
    @Override
    public List<Account> findAll() {
        System.out.println("业务层,查询所有账户信息");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层,保存用户信息");

    }
}

将变量注入到容器后,就可以直接来调用他的方法了。

能正常执行调用serviceimpl的方法就把这两大框架给整合完成了。

0x02 整合Mybatis

我们需要在spring配置文件里面把sqlsession工厂类给配置进去。

applicationcontenxt.xml 文件:

代码语言:javascript复制
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--    开启注解扫描-->
    <context:component-scan base-package="com.test">
<!--        配置不扫描控制器-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        
    </context:component-scan>

<!--配置连接池对象    -->
    
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql:///ssm" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>
    <!-- 配置SqlSession的工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 配置扫描dao的包 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.dao"/>
    </bean>
</beans>

配置完成后,就可以来修改dao接口了。

dao接口:

代码语言:javascript复制
@Repository
//使用注解将该接口注入到spring
public interface Accountdao {
    @Select("select * from account")
    List<Account> findAll();
    @Insert("insert into account (name,money)values (#{name},#{money})")
    void saveAccount(Account account);

}

serviceimpl类:

代码语言:javascript复制
@Service("accountserivce")
//当Spring要创建AccountServiceImpl的的实例时,bean的名字必须叫做accountserivce
public class AccountserivceImpl implements Accountservice{
    @Autowired
//    将该变量注入到spring中
    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);

    }
}

controller:

代码语言:javascript复制
@Controller

@RequestMapping("/account")
public class AccountController {
    @Autowired
//    使用注解将变量注入到spring容器中
    private Accountservice accountservice;

@RequestMapping("/findAll")
    public String findAll(Model model){
    System.out.println("表现层执行了");
    List<Account> userlist = accountservice.findAll();
    model.addAttribute("userlist",userlist);
        return "list";
    }
}

把查询内容封装到model对象里面,然后使用addAttribute方法共享到域中,在jsp页面里面写入el和jspl表达式我们就可以在页面中看到查询的内容了。

配置事务管理

在spring配置里面配置事务管理

applicationcontenxt.xml:

代码语言:javascript复制
 <!-- 配置事务管理器 -->
    <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="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置 aop -->
    <aop:config>
        <!-- 配置切入点表达式 -->
        <aop:pointcut expression="execution(* com.test.serivce.*.*(..))"
                      id="pt1"/>
        <!-- 建立通知和切入点表达式的关系 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>

AccountController类加多一个保存的方法,让jsp页面的表单提交到该方法后,进行获取,然后调用保存的方法进行存储数据。

代码语言:javascript复制
    @RequestMapping("/save")
    public String save(Account account){
        accountservice.saveAccount(account);
        return "list";
    }

jsp页面:

代码语言:javascript复制
<form action="${pageContext.request.contextPath}/account/save" method="post">
    id: <input name="id" type="text">
    姓名: <input name="name" type="text">
    钱: <input name="money" type="text">
    <input type="submit" value="提交">

0x03 结尾

ssm的框架整合完成,这里写了一个小案例来做了整合的演示。在调试的时候频繁出问题,大部分的原因还是因为xml配置的问题。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/119925.html原文链接:https://javaforall.cn

0 人点赞