Detailed explanation of SSM framework construction

SSM (Spring + springmvc + mybatis) framework set is composed of three open-source frameworks: spring, springmvc and mybatis. It is often used as the framework for web projects with simple data source. It is the mainstream Java EE enterprise framework after SSH, which is suitable for building various large-scale enterprise application systems.

Spring: a lightweight control inversion (IOC) and aspect oriented (AOP) container framework.

There are many articles on control reversal and aspect oriented on the Internet. I feel that the following two articles are relatively easy to understand:

Control reversal: http://blog.csdn.net/icarus_wang/article/details/51457866

Facing section: https://www.zhihu.com/question/24863332

Spring MVC: Spring MVC is a follow-up product of the spring framework and has been integrated into spring web flow. Its native spring features make development very simple and standardized. Spring MVC separates the roles of controller, model object, dispatcher and handler object, which makes them easier to customize.

Mybatis: a Java based persistence layer framework. It uses simple XML or annotations for configuration and original mapping, and maps the interface and Java POJOs (plain old Java objects) into records in the database.

Now, let's start configuration happily ~ ~ (▽)

Basic environment: ide: eclipse; Database: MySQL;

The project will use jar packages with fried chicken. For convenience, we can use Maven to manage jar packages. We can directly configure the required jar packages in the Maven configuration file. Maven can help us download them automatically, which is very considerate~~

I Installation and configuration of maven

1. Download maven

Maven download address

2. Configure environment variables after downloading

3. Verify that the installation is successful

Enter the command: MVN - version. The configuration is successful when the version information appears

4. Configure Maven in eclipse

Select window - > preferences to configure Maven:

If you find that your eclipse does not have the Maven option, you need to install the Maven plug-in yourself:

Maven plug-in installation tutorial

After the installation is successful, the Maven option appears~

II Create Maven project

1. New project

2. Default direct next

3. Because it is a web project, select webapp

4. Give your project a nice name and click "finish"~

After modification, the directory will be complete automatically:

After that, the corresponding project structure can be established according to the needs of the project. My directory is as follows for reference only:

III SSM integration

1. Maven imports the required jar package

Modify POM XML file, and directly paste the following contents into POM Replace the original properties and dependencies in XML:

	<properties>
		<!-- spring版本号 -->
		<spring.version>4.0.2.RELEASE</spring.version>
		<!-- mybatis版本号 -->
		<mybatis.version>3.2.6</mybatis.version>
		<!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.7.7</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
			<scope>test</scope>
		</dependency>
		<!-- spring核心包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</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-oxm</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>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

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

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- mybatis核心包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- 导入java ee jar 包 -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
		</dependency>
		<!-- 导入MysqL数据库链接jar包 -->
		<dependency>
			<groupId>MysqL</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.30</version>
		</dependency>
		<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- JSTL标签类 -->
		<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>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.41</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 -->
		<!-- 映入JSON -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<!-- 上传组件包 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis.generator.core</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>

	</dependencies>

2. Integration of spring and mybatis

(1) Add three configuration files in Src / main / Resources Directory:

driver=com.MysqL.jdbc.Driver
url=jdbc:MysqL://127.0.0.1:3306/miaonetdisk
username=root
password=
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
<?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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- 自动扫描,这里的base-package需要改成你自己的 -->  
    <context:component-scan base-package="com.cn.netdisk" />  
    <!-- 引入配置文件 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${password}" />  
        <!-- 初始化连接大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 连接池最大数量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 连接池最大空闲 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 连接池最小空闲 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 获取连接最大等待时间 -->  
        <property name="maxWait" value="${maxWait}"></property>  
    </bean>  
  
    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.sqlSessionfactorybean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自动扫描mapping.xml文件,这里的value也需要改成你自己的 -->  
        <property name="mapperLocations" value="classpath:com/cn/netdisk/mapping/*.xml"></property>  
    </bean>  
  
    <!-- DAO接口所在包名,Spring会自动查找其下的类,别忘了改basePackage的value -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.cn.netdisk.dao" />  
        <property name="sqlSessionfactorybeanName" value="sqlSessionFactory"></property>  
    </bean>  
  
    <!-- (事务管理)transaction manager,use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
  
</beans>
#定义LOG输出级别  
log4j.rootLogger=INFO,Console,File  
#定义日志输出目的地为控制台  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#可以灵活地指定日志输出格式,下面一行是指定具体的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
  
#文件大小到达指定尺寸的时候产生一个新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定输出目录  
log4j.appender.File.File = logs/ssm.log  
#定义文件最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  
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

(2) . create data in the database

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL,`name` varchar(255) NOT NULL,`password` varchar(255) NOT NULL,`role_type` tinyint(4) NOT NULL,`create_time` datetime DEFAULT NULL,`delete_flag` tinyint(4) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1','miaomiaomiao','','0','2018-01-23 13:50:20','0');

(3). Automatic code creation with mybatis generator

Mybatis generator download address

Enter the Lib directory, where there are many jar packages and configuration files, including generator XML needs to be configured as follows:

<?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>
	<classPathEntry location="F:\mybatis-generator-core-1.3.2\lib\mysql-connector-5.1.8.jar" />
	<context id="sysGenerator" targetRuntime="MyBatis3">
		<jdbcConnection driverClass="com.MysqL.jdbc.Driver"
			connectionURL="jdbc:MysqL://localhost:3306/miaonetdisk" 
			userId="root" password="">
		</jdbcConnection>
		<javaModelGenerator targetPackage="com.cn.netdisk.entity"
			targetProject="F:\mybatis-generator-core-1.3.2\lib\src">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<sqlMapGenerator targetPackage="com.cn.netdisk.mapping"
			targetProject="F:\mybatis-generator-core-1.3.2\lib\src">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.cn.netdisk.dao" targetProject="F:\mybatis-generator-core-1.3.2\lib\src">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>
		<table tableName="user" domainObjectName="User" enableCountByExample="false"
			enableUpdateByExample="false" enableDeleteByExample="false"
			enableSelectByExample="false" selectByExampleQueryId="false">
			<generatedKey column="ID" sqlStatement="MysqL" identity="true" />
		</table>
	</context>
</generatorConfiguration>

The location needs to be changed to your installation path, JDBC to your own database connection, and don't forget to modify targetpackage and targetproject. In particular, the targetpackage must be changed to your own!

After completion, just open the console, enter the Lib directory, and execute the script:

java -jar mybatis.jar -configfile generator.xml -overwrite

In this way, after generation, you can find the corresponding folder in the SRC directory, and each table will correspond to three files (entity class, interface and configuration file). For custom, you can change the generated interface name usermapper to userdao, and copy the corresponding files to your project:

(4). Establish service interface and implementation class

UserService. java

package com.cn.netdisk.service;

import com.cn.netdisk.entity.User;

public interface UserService {  
    public User getUserById(Long userId);
}

UserServiceImpl. java

package com.cn.netdisk.service.impl;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.cn.netdisk.dao.UserDao;
import com.cn.netdisk.entity.User;
import com.cn.netdisk.service.UserService;

@Service("userService")  
public class UserServiceImpl implements UserService {  
    @Resource  
    private UserDao userDao;  
    public User getUserById(Long userId) {  
        return this.userDao.selectByPrimaryKey(userId);  
    }  
}

(4). Testing with JUnit

Create a test class in Src / test / Java. If the test is successful, it means that spring and mybatis have been integrated successfully. The output information is printed to the console using log4j.

TestMyBatis. java

package com.cn.netdisk.testMyBatis;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.cn.netdisk.entity.User;
import com.cn.netdisk.service.UserService;  
  
@RunWith(SpringJUnit4ClassRunner.class)     
//表示继承了SpringJUnit4ClassRunner类  
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})  
  
public class TestMyBatis {  
    private static Logger logger = Logger.getLogger(TestMyBatis.class);  
    @Resource  
    private UserService userService = null;  
  
    @Test  
    public void test1() {  
        User user = userService.getUserById(1l);
        logger.info(JSON.toJSONString(user));  
    }  
}

To tell you the truth, I don't know much about testing. I tried to run it by referring to other people's code. If you want to know more about JUnit, you can learn about JUnit~

At testmybatis Right click the java file and select run as - > JUnit test run:

If the test passes, a green flag will appear and the data in your database will be output on the console;

Otherwise, an error message will appear at the position of the arrow in the figure, so you need to correct the error yourself, God bless you~~

So far, the integration of spring and mybatis has been completed. Next, we will continue the integration of spring MVC.

III Integrate spring MVC

(1) . add profile

Create spring-mvc.net in resources XML document:

spring-mvc. xml

<?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:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->  
    <context:component-scan base-package="com.cn.netdisk.controller" />  
    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->  
    <bean id="mappingJacksonHttpMessageConverter"  
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
        <property name="supportedMediaTypes">  
            <list>  
                <value>text/html;charset=UTF-8</value>  
            </list>  
        </property>  
    </bean>  
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->  
    <bean  
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->  
            </list>  
        </property>  
    </bean>  
    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的URL地址 -->  
        <property name="prefix" value="/WEB-INF/jsp/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
      
    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->  
    <bean id="multipartResolver"    
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <!-- 默认编码 -->  
        <property name="defaultEncoding" value="utf-8" />    
        <!-- 文件大小最大值 -->  
        <property name="maxUploadSize" value="10485760000" />    
        <!-- 内存中的最大值 -->  
        <property name="maxInMemorySize" value="40960" />    
    </bean>   
  
</beans>

Modify the web XML file:

web. xml

<?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_3_0.xsd"  
    version="3.0">  
    <display-name>Archetype Created Web Application</display-name>  
    <!-- Spring和mybatis的配置文件 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring-mybatis.xml</param-value>  
    </context-param>  
    <!-- 编码过滤器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <!-- Spring监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!-- 防止Spring内存溢出监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  
  
    <!-- Spring MVC 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>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  
  
</web-app>

(2). test

New showuser jsp

showUser. jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <title>测试</title>  
  </head>  
    
  <body>  
    ${user.name}  
  </body>  
</html>

Notice the user here Name wants to talk to you Keep consistent in Java~

UserController. java

package com.cn.netdisk.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.netdisk.entity.User;
import com.cn.netdisk.service.UserService;  
  
@Controller  
@RequestMapping("/user")  
public class UserController {  
    @Resource  
    private UserService userService;  
      
    @RequestMapping("/showUser")  
    public String toIndex(HttpServletRequest request,Model model){  
        Long userId = Long.parseLong(request.getParameter("id"));  
        User user = this.userService.getUserById(userId);  
        model.addAttribute("user",user);  
        return "showUser";
    }  
}

(3). function

Right click Run as - > run on server in the project. Since the creation and configuration of Tomcat server is relatively simple, it is not written here. After successful operation and no error log, open the browser and enter the address (the port configured by my Tomcat is 8605, and the default is generally 8080):

http://localhost:8080/你的项目名/user/showUser?id=1

Test successful! Flower spreading ✿✿ヽ (° ▽ °) ノ✿~~~~

If Mu is successful, go to the error log to check the bug. Come on, teenagers!

PS: this blog refers to the blog with the following links, which mainly refines and arranges the contents. Thank the original author for his arrangement and offer Huahua ✿ ✿ ~ ~:

Original link http://blog.csdn.net/gebitan505/article/details/44455235

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
分享
二维码
< <上一篇
下一篇>>