Detailed explanation of configuration files in SSM framework

Posted by Derleek on Sat, 20 Nov 2021 03:22:25 +0100

We have been integrating the SSM framework these days. Although there are many integrated ones on the Internet, we haven't explained too much about the configuration files. Many people know it and don't know why. After several days of search and sorting, we finally have a certain understanding of the XML configuration files, so we take them out and share them together. I hope we can criticize and correct the deficiencies~~~

First of all, this article only explains the configuration files used in the framework for the time being, and it is in the form of annotations. The specific process of framework operation will be summarized in two days

Three XML configuration files are used in the spring+springmvc+mybatis framework: web.xml, spring-mvc.xml and spring-mybatis.xml. Needless to say, each web project has its own configuration associated with the whole project. The second file, spring-mvc.xml, is some configuration related to springmvc, and the third is the configuration related to mybatis

Two resource property files and are also used in the project. One is about JDBC configuration, which can be extracted for future modification. The other is the configuration of log files

The above is what I want to say in this article, which is relatively simple and easy to understand. I hope Daniel will not despise ~ ~ next, let's get to the point:

A web.xml

I've always been in a hazy state about this configuration file. I just took the opportunity of this integration framework to understand it clearly. In the following code, I annotated each label in detail. You can understand it as soon as you read it. The main understanding is the configuration in which the front-end controller is configured. In the SSM framework, The front-end controller plays the most important role. The code is pasted below

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
	<context-param> <!--Global environment parameter initialization-->
		<param-name>contextConfigLocation</param-name>  		<!--Parameter name-->
		<param-value>classpath:spring-mybatis.xml</param-value>		<!--Parameter value-->
		 <!--Load order for the following configuration:before ServletContext >> context-param >> listener >> filter >> servlet >>  spring-->
	<!---------------------------------------------------Filter configuration------------------------------------------------------>
	<!--example:Coding filter-->
	<filter>		<!-- Used to declare filter Related settings of,A filter can intercept and modify a Servlet or JSP Page request or from a Servlet or JSP Response from page-->
		<filter-name>encodingFilter</filter-name>     <!--appoint filter Name of-->
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>	<!--definition filter The name of the class-->
		<async-supported>true</async-supported>		<!--Sets whether asynchronous support is enabled-->
		<init-param><!--Used to define parameters,If in Servlet The following methods can be used to obtain:String param_name=getServletContext().getInitParamter("param-name Value inside");-->
			<param-name>encoding</param-name>   <!--Parameter name-->
			<param-value>UTF-8</param-value> <!--Parameter value-->
	<filter-mapping><!--Used to define filter Corresponding URL-->
		<filter-name>encodingFilter</filter-name>     <!--Specify correspondence filter Name of-->
		<url-pattern>/*</url-pattern>		<!--appoint filter Corresponding URL-->
	<!---------------------------------------------------Listener configuration------------------------------------------------------>
	<!--example:spring monitor-->
	<listener>		<!--Used to set Listener Interface-->
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class><!--definition Listener Class name for-->
	<!-- prevent Spring Memory overflow listener  -->
	<!---------------------------------------------------servlet to configure------------------------------------------------------>
	<servlet>		<!--Used to declare a servlet Data -->  
		<servlet-name>SpringMVC</servlet-name>	<!--appoint servlet Name of-->
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--appoint servlet Class name for,Front end controller is configured here-->
		<init-param><!--Used to define parameters,Can there be more than one init-param. stay servlet Class getInitParamenter(String name)Method to access initialization parameters    -->
			<param-name>contextConfigLocation</param-name>	<!--Parameter name-->
			<param-value>classpath:spring-mvc.xml</param-value>	<!--Parameter value-->
		<load-on-startup>1</load-on-startup><!--When the value is positive or zero: Servlet The container is loaded with a small value first servlet´╝îThen load other large values in turn servlet.-->
		<async-supported>true</async-supported><!--Sets whether asynchronous support is enabled-->
	<servlet-mapping><!--Used to define servlet Corresponding URL-->
		<servlet-name>SpringMVC</servlet-name>	<!--appoint servlet Name of-->
		<url-pattern>/</url-pattern>		<!--appoint servlet Corresponding URL-->
	<!-----------------------------------------------Session timeout configuration (in minutes)------------------------------------------------->
	<session-config><!--If a session is not accessed for a certain period of time, the server can throw it away to save memory-->
	<!---------------------------------------------------MIME Type configuration   ------------------------------------------------------>
	<mime-mapping><!--Set the method and type of opening a file with an extension with an application. When the extension file is accessed, the browser will automatically open it with the specified application-->
		<extension>*.ppt</extension>			<!--Extension name-->
		<mime-type>application/mspowerpoint</mime-type>			<!--MIME format-->
	<!---------------------------------------------------Welcome page configuration  ------------------------------------------------------>
	<welcome-file-list><!--Define first page list.-->
		<welcome-file>/index.jsp</welcome-file>	<!--Used to specify the first page file name.We can use<welcome-file>Specify several home pages,The server will find the home page in the set order.-->
	<!---------------------------------------------------Configuration error page------------------------------------------------------>
	<error-page>	<!--Error code(Error Code)Or abnormal(Exception)The type of corresponds to web Application resource path.-->
		<error-code>404</error-code>		<!--HTTP Error code,for example: 404,403-->
		<location>error.html</location>			<!--Used to set the page to display when an error or exception occurs-->
		<exception-type>java.lang.Exception</exception-type><!--Set what might happen java Exception type,for example:java.lang.Exception-->
		<location>ExceptionError.html</location>			<!--Used to set the page to display when an error or exception occurs-->

II. spring-mvc.xml

Configuration required to realize basic functions
1. Configure MVC: annotation driven/
2. Configure < context: component scan base package = "com.springmvc.controller" / > / / configure controller injection
3 configure view parser

MVC: annotation driven / is equivalent to registering two bean s: defaultannotationhandlermapping (mapper) and annotationmethodhandleradapter (adapter). That is, it solves the premise configuration of @ Controller annotation.

Context: component scan scans the specified package, implements annotation driven bean definition, and automatically injects beans into the container for use. That is, it solves the injection and use of the bean of the class identified by @ Controller.

 <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns=""
       <!-- 1,Configure mapper and adapter -->
       <!-- 2,view resolver  -->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <span style="white-space:pre">	</span><!-- prefix and suffix  -->
         <property name="prefix" value="/"/>
         <property name="suffix" value=".jsp"/>
       <!-- 3,Automatically scan the package so that SpringMVC I think the bag is used@controller The annotated class is the controller  -->
       <context:component-scan base-package="com.rhzh.controller"/>

III. spring-mybatis.xml

Configuration required to realize basic functions
1. Configure < context: component scan base package = "com.rhzh" / > / / automatic scanning, automatically convert the classes marked with Spring annotations to beans, and complete Bean injection at the same time
2 load data resource attribute file
3 configure data source three data source configuration methods
4. Configure sessionfactory
5 assemble Dao interface
6. Explicit transaction management
7 annotation transaction aspect

  <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns=""
      <!--1 Autoscan labels Spring Automatic conversion of annotated classes Bean-->
      <context:component-scan base-package="com.rhzh" />
      <!--2 Load data resource properties file -->
      <bean id="propertyConfigurer"
        <property name="location" value="" />
      <span style="white-space:pre"><!-- 3 Configure data sources --></span>
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- Initialize connection size -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- Maximum number of connection pools -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- Connection pool maximum idle -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- Connection pool minimum idle -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- Gets the maximum connection wait time -->
        <property name="maxWait" value="${maxWait}"></property>
      <!-- 4   to configure sessionfactory -->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- Automatic scanning mapping.xml file -->
        <property name="mapperLocations" value="classpath:com/rhzh/mapping/*.xml"></property>
      <!-- 5  assembling dao Interface -->
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.rhzh.dao" /> <!-- DAO Package name of the interface, Spring The class under it is automatically found -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
      <!-- 6,Declarative transaction management -->
      <bean id="transactionManager"
        <property name="dataSource" ref="dataSource" />
      <!-- 7,Annotation transaction aspect --><span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="html">   <tx:annotation-driven transaction-manager="transactionManager"/>


The following are two resource attribute files to be imported:

    #Defines the number of initial connections
    #Define the maximum number of connections
    #Define maximum idle
    #Define minimum idle
    #Define maximum wait time

 #Define LOG output level
    #Define the log output destination as the console
    #You can flexibly specify the log output format. The following line specifies the specific format
    log4j.appender.Console.layout = org.apache.log4j.PatternLayout
    log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
    #When the file size reaches the specified size, a new file is generated
    log4j.appender.File = org.apache.log4j.RollingFileAppender
    #Specify output directory
    log4j.appender.File.File = logs/ssm.log
    #Define maximum file size
    log4j.appender.File.MaxFileSize = 10MB
    # Output all logs. If it is replaced with DEBUG, it means that logs above DEBUG level are output
    log4j.appender.File.Threshold = ALL
    log4j.appender.File.layout = org.apache.log4j.PatternLayout
    log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

The above is just an explanation of the configuration file in the framework. It's OK if the integration framework can't run. Understand the principles so that you can find and solve problems in the future. Don't be eager for success. Step by step, you'll find that you go faster than others!!!

Topics: Java Spring mvc