IDEA uses IDEA to build SSM framework projects

Keywords: Java Spring Mybatis log4j xml

1. New Project

Create a new Maven project in IDEA using the Maven Archetype prototype: maven-archetype-webapp

The new project structure is:

2. New package directory

  • New Java Code Directory: src.main.java

    New hierarchical model package under src.main.java, groupId with project (for reference only)

    • common: store global variables, public enumerations, etc.

    • base: Stores basic components such as tool classes, filters, configuration classes, etc.

    • controller: control layer

    • vo: Objects transferred from the front end, such as encapsulated requests

    • bo: Business object, possibly an integration of multiple dto/entity

    • service: business tier

      • intf: interface

      • impl: Implement

    • dao: database access layer

      • intf: interface (xxxMapper.java in MyBatis)
      • impl: implementation (auto-generated implementation class in MyBatis)
    • dto: data transfer object, storing multitable federated objects

    • Entity: entity, corresponding to a database table

  • New Resource Directory: src.main.resources

3. Introduce pom on demand

After a new project is built, it is not recommended to introduce all the dependencies at once, but to introduce them gradually when needed. Although you will walk in many pits, you can familiarize yourself with the role of each dependency to prevent you from stepping in larger pits in the future.

The first dependencies that need to be introduced after a new project is:

  • Servlet API

    The Java Web application server will have a Servlet API, so this dependent scope is set to provided

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${servlet.version}</version>
        <scope>provided</scope>
    </dependency>
    
  • Spring Web Mvc

    Spring Web dependency, including Spring MVC, IDEA will also introduce other Spring modules that Spring Web Mvc depends on, including aop, beans, context, core, expression, web, and the rest of the modules are not quoted, but it is better to introduce them for scalability.

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    

4. Configure web.xml

4.1 Configure ContextLoaderListener

ContextLoaderListener is a ServletContext listener that creates container objects, places ApplicationContext objects in the Application domain, and specifies the spring core configuration file.

A separate article will be written about the specific role and source code of the ContextLoaderListener.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
</context-param>
4.2 Configure Dispatcher Servlet

Dispatcher Servlet is a front-end controller that specifies the configuration file for Spring MVC in the configuration.

A separate article will be written about the specific role and source code of Dispatcher Servlet.

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
4.3 Handling Chinese scrambling

Configure CharacterEncodingFilter filter to handle Chinese scrambling before all filters.

<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>
    <init-param>
        <param-name>forceRequestEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>forceResponseEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
4.4 Integrating Restful Style Requests

Configure the HiddenHttpMethodFilter filter to convert get/post requests to standard http methods to support GET, POST, PUT, and DELETE requests.

<filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

5. Configure Spring profile

The Spring profile path is configured in the web.xml ContextLoaderListener.

The initial Spring configuration file requires a package scan to inject qualified Java beans into the Spring container, which Spring manages.

<!--  Set package scan, do not scan Controller  -->
<context:component-scan base-package="com.lyldelove">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

6. Configure Spring MVC Profile

The Spring MVC configuration file path is configured in the web.xml Dispatcher Servlet.

The initial Spring MVC profile requires the following three configurations:

  • Package scan.Scan all Controller s
  • Turn on annotation-driven mvc.Advanced Spring MVC features are available when turned on
  • Configure the default static resource processor
  • Configure View Parser
<!--Set up package scan, scan all Controllers -->
<context:component-scan base-package="com.lyldelove" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--Turn on the annotation-driven mvc and use Spring MVC's advanced features when turned on-->
<mvc:annotation-driven/>

<!--Configure the defau lt static resource processor-->
<mvc:default-servlet-handler/>

<!--Configure View Parser-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--Configure Resolution Prefix-->
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

Processing of static resources, configurations can also be resolved by <mvc:resources />

7. Introduce front-end JS/CSS

Static files, such as js/css, required for the front end, are typically placed in the webapp directory

8. Log Framework Integration

In the process of integrating other frameworks, there may be a lot of exceptions/errors in the project, and we need to look for problems through the logs.

Log framework requires log facade and log implementation. We use slf4j as log facade and log4j as log implementation to see how to integrate.

Introduce dependencies:

<!--  Journal, slf4j Make a log face, log4j Logging implementation  -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
</dependency>

With the introduction of slf4j-log4j12, IDEA automatically introduces the dependencies of slf4j-api and log4j, and does not need to show the introduction anymore

Log4j automatically scans log4j.xml or log4j.properties in the src/main/resources directory, where we place the configuration file.

#log4j.properties

#Log Output Level
log4j.rootLogger=debug,stdout,D,E

#Set stdout's log output console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#Output log to console mode, default is System.out
log4j.appender.stdout.Target = System.out
#Set up a flexible layout
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#Flexible output format definition
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p]  method:[%c (%rms)] - %m%n

9. Data Source Integration

For Druid, you need to introduce the dependencies of Spring JDBC and Druid, and database connection information is best managed by a separate configuration file, followed by external configuration files in the Spring configuration file.

Dependency:

<!--  Spring jdbc  -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!--  data source Druid  -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${druid.version}</version>
</dependency>

Note: Remember to introduce the dependency of Spring jdbc, otherwise problems will be difficult to find later (it's better to have a log, so it's best to put the integration of the log framework first).

Spring Configuration:

<!--Load external profile-->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!--Configure Druid Data Source-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.user}"/>
    <property name="password" value="${jdbc.password}"/>

    <!--Specify the maximum number of active connections in the connection pool-->
    <property name="maxActive" value="20"/>
    <!--Specify the number of connections initially established when starting the connection pool-->
    <property name="initialSize" value="1"/>
    <!--Specifies the maximum wait time, in milliseconds, for the connection pool to wait for the connection to return. -->
    <property name="maxWait" value="60000"/>
    <!--Specifies the minimum value at which connections must be maintained (For DBCP and Tomcat connection pools) -->
    <property name="minIdle" value="1"/>
</bean>

10. MyBatis + MySql Integration

Dependency:

<!--  Spring jdbc  -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!--  MyBatis  -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
</dependency>

<!--  MyBatis integration spring  -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>${mybatis.spring.version}</version>
</dependency>

<!--  MySQL drive  -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
</dependency>

Configure MyBatis in the Spring profile:

The following two items need to be configured:

  • Configure sqlSessionFactory
  • Configure Mapping Scanner
<!--  To configure MyBatis sqlSessionFactory  -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--  Appoint MyBatis Of XML Profile Path  -->
    <property name="configLocation" value="classpath:mybatis.xml"/>
    <!--  Specify Mapper XML File Path  -->
    <property name="mapperLocations" value="classpath:mapper/**/*.xml"/>
</bean>

<!--  scanning MyBatis Mapper  -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.lyldelove.dao"/>
</bean>

MyBatis profile:

MyBatis's profile is configured in the Spring profile sqlSessionFactory configuration item, which requires camel naming rules and aliases to be configured.

<settings>
    <!--The rest of the camel nomenclature rules are that database fields can correspond to JavaBean properties-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

<!--Alias so that resultType can be abbreviated in the apper.xml file and the default rule is lowercase JavaBean class names-->
<typeAliases>
    <package name="com.lyldelove.entity.system"/>
</typeAliases>

11. Points needing deep excavation

  • Role of ContextLoaderListener and Source Code Analysis
  • Dispatcher Servlet Function and Source Code Analysis
  • How Filter Filter works
  • Spring/Spring MVC Profile Resolution and the Role of Related Configuration Items and Source Code Analysis
  • Log Framework Deep, Configure Items
  • How the logging framework is integrated and how it is implemented
  • What is a data source

Posted by Felex on Sat, 04 Apr 2020 10:17:31 -0700