J2EE-022 SSM XML configuration SSM framework


Spring IOC,DI
Spring MVC process control from front end to back end
Mybatis ORM framework

Understanding of xml framework structure

Explanation of each XML process and function

General structure of the overall XML framework

web.xml

  • Configure the dispatcher servlet to access the entry path and distribute the process
  • Configure characterencoding filter and configure the encoding format as UTF-8
  • Configure the listener ContextLoaderListener to initialize the load Bean together with the fact of web initialization

spring-mvc.xml

  • Configure the view parser InternalResourceViewResolver and set the prefix and suffix paths
  • import, load Bean file
  • MVC: default servlet handler, enabling static resource release
  • MVC: annotation driven enable custom tags

spring-Mybatis.xml

  • Load JDBC properties
  • Configure DataSource datasource
  • Configure sqlSessionBeanFactory and integrate the SqlSessionFactory object of Mybatis into the spring container for management
  • Configure mappercannerconfigurer. In the previous way, the object is obtained through the environment tag in config. Here, the object is injected directly. The configuration uses proxy method to generate XML file. The instance of Mapper interface is handed over to spring container management, which is equivalent to calling sqlsession Getmapper() method

I think twice today. Before that, I obtained the SqlSession method by loading XML with data stream, and then passed SqlSession Opensession() gets the object, and then through sqlsesson Getmapper (class object) gets Mapper, for example:
Reader reader = Resources.getResourceAsReader("mybatisconfig/MybatisConfiguration.xml"); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader); sqlSession = build.openSession();UserDAO mapper = sqlSession.getMapper(UserDAO.class);

spring-tx.xml

  • Configure DataSourceTransactionManager, transaction manager
  • Configure < TX: advice aspect notification rules
  • Configure < AOP: config tangent point
  • The loading bean context logic layer is responsible for loading the service layer and transaction processing the service layer

Bean-context.xml

  • Bean configuration for service class

Bean-controller.xml

  • Bean configuration for controller class

BeanMapper.xml

  • Mapper class mapping interface completes TSQL writing

summary

Conclusion: it can be roughly regarded as four layers,
1.Web. The config layer is responsible for startup
2. The spring MVC layer is responsible for distribution
3. Spring mybatis is responsible for data source and sqlSessionFactory
4. Spring TX, which is responsible for the link object and Mpaper mapping relationship of the database

Project creation

After considering how our xml needs to be classified, we began to think about the Maven references we need to use to create the project

pom.xml

Spring webmvc: load dipacherServlet distributor
Spring aspects: notifications for transaction pointcuts
JDBC spring database link
druid: data source
mybatis: ORM framework
mybatis-spring: sqlSeesionFactory
MySQL connector Java: database driver
Servlet API: distribution
lombok: tool class

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

web.config

  • Configuring the dispatcher servlet distributor
  • You need to add spring MVC Configure after XML file
<servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:context/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  • Configure the encoding format of characterencoding filter
 <filter>
        <filter-name>Filter</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>Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  • Configure the listener to start with the web
  • The applicationContext file needs to be added
<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>

Spring-mvc.xml

  • Configure InternalResourceViewResolver and jsp view parser
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="suffix" value=".jsp"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
    </bean>
  • Enable mvc custom label usage
 - <mvc:annotation-driven/>
  • Enable the release of static resources
<mvc:default-servlet-handler/>
  • Introduce bean controller xml
<import resource="classpath:context/book/book-controller.xml"/>

Spring-mybatis.xml

  • Configure data source
    1. Load configuration file
<context:property-placeholder location="classpath:jdbc.properties"/>

2. Load data source

 <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.root}"></property>
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="password" value="${jdbc.pwd}"></property>
    </bean>

3. Configure SqlSessionFactoryBean
1. The attribute DataSource is the data source
2. Configlocation and maperlocations are two ways to configure mapper
Maperlocations is to configure the loading of XML files in different packages
Configlocation is the configuration environment Env for loading Mybatisconfig

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="druidDataSource"></property>
    <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
    <property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"></property>
</bean>

4. The mappercannerconfigurer is configured to solve the cumbersome mappercanfactorbean. With mappercannerconfigurer, we don't need to declare a bean for each mapping interface. Greatly reduce the efficiency of development.

   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="scannerConfigurer">
        <property name="basePackage" value="demo.mvc.dao"/>
    </bean>

Spring-tx.xml

1. Configure the transaction DataSourceTransactionManager and load the data source

<bean id="transcationManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

2. Configure section tx:advice

 <tx:advice transaction-manager="transcationManager" id="interceptor">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="query*" propagation="SUPPORTS"/>
            <tx:method name="log*" propagation="REQUIRES_NEW"/>
            <tx:method name="*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/>
        </tx:attributes>
    </tx:advice>

3. Configure the pointcut AOP conifg

<aop:config>
        <aop:pointcut id="pcut" expression="execution(* ssm.mvc..*.*(..))"/>
        <aop:advisor advice-ref="interceptor" pointcut-ref="pcut"/>
    </aop:config>

4. Configure the entry point AOP conifg
Introduce the context file of DAO layer

 <import resource="classpath:context/book/book-context.xml"/>

Bean-Context.xml

Register Servie layer Bean

<bean class="ssm.mvc.service.BooksServiceImpl" id="bookService">
        <property name="bookMapper" ref="bookMapper"></property>
</bean>

ref="bookMapper" refers to the interface

Bean-controller.xml

Register ben of controller

    <bean id="bookController" class="ssm.mvc.controller.BookController">
        <property name="bookService" ref="bookService"></property>
    </bean>

Configure mapper xml

<mapper>
    <!--Add a Book-->
    <insert id="addBook" parameterType="book">
        insert into books(bookName,bookCount,detail)
        values (#{bookName},#{bookCount},#{detail})
    </insert>
    <!--Delete a Book-->
    <delete id="deleteBookByID" parameterType="int">
        delete from books where bookID=#{bookID}
    </delete>
    <!--Update a Book-->
    <update id="updateBook" parameterType="book">
        update books set
                         bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookID} ;
    </update>
    <!--Inquire about a Book-->
    <select id="queryByID" resultType="book">
        select * from books where bookID=#{bookID}
    </select>
    <!--Query all books-->
    <select id="queryAllBooks" resultType="book">
        select * from books
    </select>
</mapper>

Configure ApplicationContext xml

  <import resource="classpath:context/spring-mybatis.xml"/>
    <import resource="classpath:context/spring-tx.xml"/>
    <import resource="classpath:context/spring-mvc.xml"/>

Class code writing

Front end JS page

<h1>Display of all books</h1>
${list}

Controller

@RequestMapping("/book")
public class BookController {
    private BookService bookService;
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }
    //Query all books and return to a page for display
    @RequestMapping("/allBooks")
    public String list(Model model) {
        List<Books> books = bookService.queryAllBooks();
        model.addAttribute("list", books);
        return "allBooks";
    }
}

Mapper

public interface BookMapper {
    //Add a Book
    int addBook(Books books);
    //Delete a Book
    //@The Param annotation specifies the name of the passed in parameter
    int deleteBookByID(@Param("bookID") int id);
    //Update a Book
    int updateBook(Books books);
    //Inquire about a Book
    //@The Param annotation specifies the name of the passed in parameter
    Books queryByID(@Param("bookID") int id);
    //Check all the books
    List<Books> queryAllBooks();
}

model

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
    private Integer bookID;
    private String bookName;
    private Integer bookCounts;
    private String bookeDetail;
}

Service layer,

public class BooksServiceImpl implements BookService{
    //Mapper interface object of dao layer
    private BookMapper bookMapper;
    //set method to prepare for subsequent Spring injection
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
    public int addBook(Books books) {
        //Call dao layer method
        return bookMapper.addBook(books);
    }
    public int deleteBookByID(int id) {
        //Call dao layer method
        return bookMapper.deleteBookByID(id);
    }
    public int updateBook(Books books) {
        //Call dao layer method
        return bookMapper.updateBook(books);
    }
    public Books queryByID(int id) {
        //Call dao layer method
        return bookMapper.queryByID(id);
    }
    public List<Books> queryAllBooks() {
        //Call dao layer method
        return bookMapper.queryAllBooks();
    }
}

services layer

public interface BookService {
    //Add a Book
    int addBook(Books books);
    //Delete a Book
    int deleteBookByID(int id);
    //Update a Book
    int updateBook(Books books);
    //Inquire about a Book
    Books queryByID(int id);
    //Check all the books
    List<Books> queryAllBooks();
}

Run the test it's OK

summary

A lot of space has been spent on the layering of xml in the front, but less space has been spent in the back. The previous content is mainly to explain that xml is divided into three layers, spring MVC, spring TX and spring TX. Their respective responsibilities and what each function does. As well as the methods of the classes that need to be registered, you need to keep in mind that you should be familiar with the following source code and understand the functions that are indispensable.

code

https://pan.baidu.com/s/1SV0rbN0pDlzlTJw2PrqqXg
b4om

Keywords: Java Spring

Added by lordphate on Sun, 20 Feb 2022 12:34:52 +0200