Integration of SSM framework for java learning

Integration of SSM framework for java learning

0x00 Preface

The spring, spring MVC and mybatis frameworks that we learned earlier have basically been learned, but to use them, we need to integrate these three frameworks and use them together.

0x01 spring integration spring MVC

First, we should integrate spring and spring MVC, and then integrate mybatis after it can run normally.

Here, configure the coordinates and the jar packages to be used.

pom. xml:

<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>

Write an entity class:


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 interface:


public interface Accountdao {
    List<Account> findAll();
    void saveAccount();

}

web. XML file:

<!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 file:

<?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>

Here, you need to configure not to scan the controller annotation. The controller should be handed over to spring MVC for operation.

spring mvc. XML file:

<?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>

After these configurations, you can write other classes.

Service interface:

public interface Accountservice {
    List<Account> findAll();
    void saveAccount(Account account);

}

Service implementation class:


@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("业务层,保存用户信息");

    }
}


Finally, write the controller class:

@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("业务层,保存用户信息");

    }
}


After injecting the variable into the container, you can call his method directly.

The integration of these two frameworks is completed when the methods calling serviceimpl can be executed normally.

0x02 integrate mybatis

We need to configure the sqlsession factory class in the spring configuration file.

applicationcontenxt. XML file:

<?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>

After the configuration is completed, you can modify the Dao interface.

Dao interface:

@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 class:

@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:

@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";
    }
}

Encapsulate the query content into the model object, then use the addAttribute method to share it into the domain, write el and jspl expressions in the JSP page, and we can see the query content in the page.

Configure transaction management

Configure transaction management in spring configuration

applicationcontenxt. xml:

 <!-- 配置事务管理器 -->
    <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>

The AccountController class adds more than one saved method, so that the form of the JSP page is submitted to the method, then it is acquired, and then the saved method is called to store the data.

    @RequestMapping("/save")
    public String save(Account account){
        accountservice.saveAccount(account);
        return "list";
    }

JSP page:

<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 end

The integration of SSM framework is completed. Here is a small case to demonstrate the integration. There are frequent problems during debugging. Most of the reasons are XML configuration problems.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>