Single (pseudo-distributed) architecture using Maven to establish dependencies, inheritance, aggregation relationships between projects SSM JAR dependencies unified management project: Parent POM.xml

The < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > com < / groupId > < artifactId > parent < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < packaging > pom < / packaging > < modules > < module > common < module > <module>ui-manager</module> <module>component</module> </modules> <! <properties> <spring.version>4.0.0.RELEASE</spring.version> </properties> <! <dependencyManagement> <dependencies> <! --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</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-test</artifactId> <version>${spring.version}</version> </dependency> <! --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> < version > 1.6.8 < / version > < / dependency > < the dependency > < groupId > org. Codehaus. Jackson < / groupId > < artifactId > Jackson - mapper - asl < / artifactId > < version > 1.9.2 < / version > < / dependency > <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> The < version > 1.0.31 < / version > < / dependency > <! Mybatis </artifactId> Mybatis </artifactId> <version>3.2.8</version>  </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> The < version > 1.2.2 < / version > < / dependency > <! PageHelper </groupId> <artifactId> PageHelper </artifactId> The < version > 4.0.0 < / version > < / dependency > <! Log4j </groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId> slf4J-api </artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <! <dependency> <groupId> Commons -fileupload</groupId> <artifactId> Commons -fileupload</artifactId> The < version > 1.3.1 < / version > < / dependency > <! -- JSTL tag --> <dependency> <groupId> JSTL </artifactId> JSTL </artifactId> <version>1.2</version> </dependency> <! --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <! -- servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> The < version > 2.5 < / version > < scope > provided < / scope > < / dependency > <! -- jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version> 2.1.3-B06 </version> <scope>provided</scope> </dependency> </dependencies> </dependencies> </project>Copy the code

Build database build table SQL

CREATE DATABASE IF NOT EXISTS `atcrowdfunding` CHARACTER SET utf8 COLLATE utf8_bin;
USE atcrowdfunding;
create table IF NOT EXISTS t_user
(
   id                   int not null auto_increment,
   loginacct            varchar(255) not null,
   userpswd             char(32) not null,
   username             varchar(255) not null,
   email                varchar(255) not null,
   createtime           char(19),
   primary key (id)
);
Copy the code

Mybatis related Mybatis profile

File name: mybatis-config.xml

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE configuration PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> </configuration>Copy the code



Create MyBatis reverse engineering

Create another project in addition to the other projects

Pom. XML is set

The < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > com < / groupId > < artifactId > reverse < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > <! This dependency is used to avoid errors when creating a Mapper interface. > <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId> The < version > 3.2.8 < / version > < / dependency > < / dependencies > <! -- Configure the reverse engineered Maven plugin --> <build> <! -- plugins: plugins used in the build process --> <plugins> <! -- plugin: plugin --> <plugin> <! MyBatis generator</groupId> <artifactId> MyBatis generator-maven-plugin</artifactId> The < version > 1.3.0 < / version > <! > <dependencies> <dependency> <groupId>org.mybatis. Generator </groupId> < artifactId > mybatis generator - core < / artifactId > < version > 1.3.2 < / version > < / dependency > < the dependency > <groupId>com.mchange</groupId> <artifactId> c3P0 </artifactId> <version>0.9.2</version> </dependency> <dependency> < the groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 5.1.8 < / version > < / dependency > </dependencies> </plugin> </plugins> </build> </project>Copy the code

Reverse engineer the configuration file: Generatorconfig.xml

<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="tables" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <commentGenerator> <! -- Whether to remove automatically generated comments true: Yes; False: no --> <property name="suppressAllComments" value="true" /> </commentGenerator> <! Database connection information: Driver class, connection address, username, password --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/atcrowdfunding" userId="root" password="root"> </jdbcConnection> <! -- Default false, resolves JDBC DECIMAL and NUMERIC types to Integer, When true, resolve JDBC DECIMAL and NUMERIC types to java.math.BigDecimal --> <javaTypeResolver> < Property name="forceBigDecimals" value="false" /> </javaTypeResolver> <! -- targetProject: path to generate Entity class --> <javaModelGenerator targetProject=".src \main\ Java "targetPackage="com.entity"> <! Property name="enableSubPackages" value="false" /> <! <property name="trimStrings" value="true" /> </javaModelGenerator> <! -- targetProject XxxMapper. XML mapping file generated path -- > < sqlMapGenerator targetProject = ". \ SRC/main/Java" targetPackage="com.component.mapper"> <! Property name="enableSubPackages" value="false" /> </sqlMapGenerator> - targetPackage: <javaClientGenerator type="XMLMAPPER" targetProject=".src \main\ Java" targetPackage="com.component.mapper"> <! <property name="enableSubPackages" value="false" /> </javaClientGenerator> <table tableName="t_user" domainObjectName="UserDO" /> </context> </generatorConfiguration>Copy the code

Maven command to generate resources: mybatis-generator:generate



Resources back to F5 refresh project

Copy files to other projects





Spring and MyBatis integration in the Common Project to add Spring and MyBatis integration needs to rely on POP.xml

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-orm</artifactId>
	</dependency>
	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
	</dependency>
	<dependency>
		<groupId>org.aspectj</groupId>
		<artifactId>aspectjweaver</artifactId>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</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>log4j</groupId>
		<artifactId>log4j</artifactId>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-api</artifactId>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-log4j12</artifactId>
	</dependency>
</dependencies>
Copy the code

Add it to the UI-Manger project

jdbc.properties

jdbc.user=root jdbc.password=root jdbc.url=jdbc:mysql://localhost:3306/atcrowdfunding? rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8 jdbc.driver=com.mysql.jdbc.Driver jdbc.initialSize=20 jdbc.minIdle=10 jdbc.maxActive=50 jdbc.maxWait=10000 jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.minEvictableIdleTimeMillis=300000 jdbc.testWhileIdle=trueCopy the code

log4j.properties

# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml! # For all other servers: Comment out the Log4J listener in web.xml to activate Log4J. # DEBUG < INFO < WARN < ERROR < FATAL log4j.rootLogger=DEBUG, a, logfile log4j.appender.a=org.apache.log4j.ConsoleAppender log4j.appender.a.layout=org.apache.log4j.PatternLayout log4j.appender.a.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,S} %-5p [%c] %l - %m%n log4j.appender.logfile=org.apache.log4j.RollingFileAppender log4j.appender.logfile.File=D:/atcrowdfunding.log log4j.appender.logfile.MaxFileSize=512KB # Keep three backup files. log4j.appender.logfile.MaxBackupIndex=3 # Pattern to  output: date priority [category] - message log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%nCopy the code

spring-tx.xml

<? The 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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <! - the introduction of external properties file - > < context: the property - placeholder location = "classpath: JDBC. Properties" / > <! - configuration automatically scan the package -- -- > < context: component - scan base - package = "com.com ponent. Service. Impl" / > <! - configuration data source - > < bean id = "dataSource" class = "com. Alibaba. Druid. Pool. DruidDataSource" > < property name = "username" value="${jdbc.user}" /> <property name="password" value="${jdbc.password}" /> <property name="url" value="${jdbc.url}" /> <property name="driverClassName" value="${jdbc.driver}" /> <! ${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <! <property name="maxWait" value="${jdbc.maxwait}" /> <! -- How often does the configuration check for idle connections that need to be closed, Unit is milliseconds - > < property name = "timeBetweenEvictionRunsMillis" value = "${JDBC. TimeBetweenEvictionRunsMillis}" / > <! -- Set the minimum lifetime of a connection in the pool, Unit is milliseconds - > < property name = "minEvictableIdleTimeMillis" value = "${JDBC. MinEvictableIdleTimeMillis}" / > < property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> </bean> <! SqlSessionFactoryBean --> <! SqlSessionFactoryBean implements the FactoryBean interface, so the configured bean returns the object of SqlSessionFactory --> <! < id=" SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <! < dataSource ="dataSource"/> <! <property name="configLocation" value=" clasSPath: MyBatis -config.xml"/> <! <property name="mapperLocations" value="classpath: Mapper /* mapper.xml "></property> </bean> <! <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <! <property name="basePackage" value="com.component.mapper"/> </bean> <! -- Configure declarative transactions --> <! - configuration transaction manager - > < bean id = "transactionManager" class = ". Org. Springframework. JDBC datasource. DataSourceTransactionManager "> <! < dataSource ="dataSource"/> </ dataSource > <! < AOP :config> < AOP :pointcut expression="execution(* *.. *Service.*(..) )" id="txPointCut"/> <! <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> <! --> < TX :advice ID ="txAdvice" transaction-manager="transactionManager"> < TX: Attributes > <tx:method name="get*" read-only="true"/> <tx:method name="list*" read-only="true"/> <tx:method name="count*" read-only="true"/> <! Rollback-for attribute: specifies the exception for transaction rollback --> <! Propagation --> <! --REQUIRED: The current method must run in a transaction, but in the current transaction if a transaction is already started on the current thread --> <! REQUIRES_NEW: The current method must run in a transaction and must start a new transaction to run in its own transaction. Avoid rollback of the current method when other method operations fail in shared transactions. --> <tx:method name="remove*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/> <tx:method name="save*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/> <tx:method name="update*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/> </tx:attributes> </tx:advice> </beans>Copy the code

The test class

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring-tx.xml") public class AtCrowdfundingTest { @Autowired private DataSource dataSource; @Test public void testDataSource() throws SQLException { Connection connection = dataSource.getConnection(); System.out.println(connection); }}Copy the code

Put the spring-tx.xml,jdbc.properties files under test SRC /test/resources if the following error occurs



Error found add Add junit.jar and spring-test

Or in the POM.xml file of the UI-Manger project

The < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > com < / groupId > < artifactId > parent < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > < / parent > < artifactId > UI - manager < / artifactId > < packaging > war < / packaging > <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>com</groupId> <artifactId> Component </artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> </dependencies> </project>Copy the code

If there are still errors



Add in the common project’s POM.xml

 <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
</dependency>
Copy the code

Spring and SpringMVC integrate to create the SpringMVC configuration file spring-mVC.xml

Add Web development-related dependencies to the Common project, so you don’t need to add them if you’ve added them before

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
	</dependency>
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
	</dependency>
Copy the code



Add Web development dependencies to the UI-Manger project

<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency>  <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <scope>provided</scope> </dependency>Copy the code

Add namespaces to spring-mVC.xml



Configure spring – the MVC. XML

<? The XML version = “1.0” encoding = “utf-8”? >

<! <context:component-scan base-package="com.component.handler"/> <! - the parser configuration view - > < bean id = "viewResolver" class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"/> </bean> <! < MVC :annotation-driven/> <! DefaultServletHandler[Optional] Plans to map the DispatcherServlet extension in web.xml, so DefaultServletHandler can be left unconfigured. --> <mvc:default-servlet-handler/> </beans>Copy the code

Configure it in web.xml

web.xml

<? The XML version = "1.0" encoding = "utf-8"? > <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version = "2.5" > <display-name>ui-manager</display-name> <! -- needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-tx.xml</param-value> </context-param> <! -- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <! -- DispatcherServlet --> <! -- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</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> <! -- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <! CharacterEncodingFilter --> <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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! HiddenHttpMethodFilter --> <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> </web-app>Copy the code

If you have other problems, you can delete your Maven repository and re-download it. You can also press Alt +F5 and select Project Update. You may also have eclipse that does not have Maven configuration or leave a comment below

Pseudo-static effects are implemented by having the DispatcherServlet map *.html. Dynamic requests handled by SpringMVC can be made to look like they are visiting a static HTML page, making it hard to guess what technology is used to implement the project. Make it harder for hackers to break in. To a certain extent, SEO optimization: make it easier for search engines to find our website.

The parent project has a subproject. When importing Eclipse with the Spring plugin, the subproject can be imported from the parent project. Note that eclipse with the Spring plugin needs to be configured with Maven

Let’s do a home page presentation

Home page display

Create index. The JSP

Possible error, solution

Perform the forward action in index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% request.getRequestDispatcher("/index.html").forward(request, response); % >Copy the code

Map a handler method to the /index.html address

package com.component.handler; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @controller public class PortalMainHandler {@requestMapping ("/index") public String showIndexPage() {@requestMapping ("/index") public String showIndexPage() { return "portal/main"; }}Copy the code

After the spring-mVC.xml view parser concatenation, we create main.jsp

Page write yourself, now directly



You can see your own page

You can also add prototype code (written by the front end staff) to main.jsp with the base tag

<base href="http://${pageContext.request.serverName }:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
Copy the code

Note 1: Do not place “/” between the port number and contextPath. Note 2: contextPath is followed by a “/”.



Style plus