Basic concepts
1.1. Spring
Spring is an open source framework, a lightweight Java development framework that emerged in 2003, derived from some of the ideas and prototypes explained by Rod Johnson in his book Expert One-On-One J2EE Development and Design. It was created to address the complexity of enterprise application development. Spring uses basic JavaBeans to do things that were previously possible only by EJB. However, Spring's uses are not limited to server-side development. From a simplicity, testability and loose coupling perspective, any Java application can benefit from Spring. Simply put, Spring is a lightweight inversion of control (IoC) and section-oriented (AOP) container framework.
1.2. SpringMVC
Spring MVC is a subsequent product of SpringFrameWork and has been integrated into Spring Web Flow. Spring MVC separates the roles of controllers, model objects, dispatchers, and handler objects, and this separation makes them easier to customize.
1.3. MyBatis
MyBatis is an open source project of apache. In 2010, this project was moved from apache software foundation to Google code and was renamed MyBatis. MyBatis is a Java-based persistence layer framework. iBATIS provides persistence layer frameworks including SQL Maps and Data Access Objects (DAO) MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping to map interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
Step 1: Create a web project through maven.
Step 2: Import the pom file into the jar package
(1) pom.xml
I copied the entire pom file, and you need to remove some of the initialization things and keep the copy you generated by your own pom.
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssm Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring version number --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis version number --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j log file management package version --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <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 core package--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring package--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- Import java ee jar package--> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- Import Mysql database link jar package--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- Import the jar package of dbcp to configure the database in applicationContext.xml --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL tag class --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Log file management package--> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- Format objects to facilitate log output--> <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 --> <!-- Input JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- Upload component package--> <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> </dependencies> <build> <finalName>ssm</finalName> </build></project>Step 3: Look at the overall project structure, let me first explain that I don’t have any related things about springMVC here, because I first integrate spring-mybatis, and when testing whether it is successful, I successfully integrate springMVC.
Step 4: Create a model class
public class User { private int id; private String name; private String password; private String password2; /*Providing set and get methods, toString method*/}Step 5: Create database, UserDao interface and mapper mapping file
(1) Create a very simple table
(2) UserDao interface
public interface UserDao { User findUserById(User user);}(3) UesrMapper.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace namespace, pointing to the full path of UserDao --><mapper namespace="com.ssm.dao.UserDao"> <!-- Query user information based on id --> <!-- id: Uniquely identify a statement, which is the same as the UserDao method name#{}: represents a placeholder. If a simple type parameter is passed in #{}, the name in #{} is arbitrary parameterType: the type of the input parameter, which is the same as the parameter in UserDao() resultType: the output result type, which is the same as the UserDao() return type-> <select id="findUserById" parameterType="com.ssm.model.User" resultType="com.ssm.model.User"> SELECT * FROM USER <where> <if test="name != null"> AND Name= #{name} </if> <if test="password != null"> AND password= #{password} </if> </where> </select> </mapper>Step 5: Create UserService and UserServiceImpl
(1) UserService
public interface UserService { public User getUserById(User user); }(2) UserServiceImpl
import org.springframework.stereotype.Service;import com.ssm.dao.UserDao;import com.ssm.model.User;import com.ssm.service.UserService;@Service("userService")public class UserServerImpl implements UserService { @Resource private UserDao userDao; public User getUserById(User user) { return this.userDao.findUserById(user); }}Step 6: Create jdbc file and log log file
(1) jdbc.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc/:mysql/://localhost/:3306/test?useUnicode=true&&characterEncoding=UTF-8jdbc.username=rootjdbc.password=root
(2) log4j.properties
log4j.rootLogger=INFO,Console,File #Define the log output destination as console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #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 the output directory log4j.appender.File.File = logs/ssm.log #Define the maximum file size log4j.appender.File.MaxFileSize = 10MB #Output so log. If you change it to DEBUG, it means outputting logs at DEBUG or above level log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyyy-MM-dd HH/:mm/:ss}][%c]%m%nStep 7: Integrate spring-mybatis.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/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"> <!-- Automatic scanning--> <context:component-scan base-package="com.ssm" /> <!-- Introducing jdbc configuration files--> <bean id="propertyConfigurer" > <property name="location" value="classpath:jdbc.properties" /> </bean> <!-- 2. Database connection pool--> <bean id="dataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- integrate spring and MyBatis to manage MyBatis' SqlSessionFactory session factory through spring --> <bean id="sqlSessionFactory"> <!-- Specify database connection pool reference--> <property name="dataSource" ref="dataSource" /> <!-- Automatic scanning of mapping.xml files --> <property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property> </bean> <!-- The package name where the DAO interface is located, Spring will automatically find the class under it --> <bean> <property name="basePackage" value="com.ssm.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (Transaction Management) transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" > <property name="dataSource" ref="dataSource" /> </bean> </beans>Step 8: Create a test class
After the above steps (log4j does not match and has no effect), we have completed the integration of Spring and mybatis, so we can write a piece of test code to try whether it has been successful.
The test class is established 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.
(1) TestMyBatis test class
package ssm;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.ssm.model.User;import com.ssm.service.UserService;/*Let the test run in the Spring test environment*/@RunWith(SpringJUnit4ClassRunner.class) /* Used to specify the location of the loaded Spring configuration file, the default configuration file will be loaded*/@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })public class TestMyBatis { @Resource(name = "userService") private UserService userService; @Test public void test1() { User user=new User(); user.setName("Zhang San"); user.setPassword("123"); User user1 = userService.getUserById(user); System.out.println(user1.toString()); }}at last! The key is to look at the background output, which is also a time to witness miracles. If the output object is output, it means that your configuration and integration are successful!
Then we start integrating springMVC
Step 9: Configure springmvc.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/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"> <!-- Automatically scan the package so that SpringMVC thinks that the class annotated by @controller under the package is the controller --> <context:component-scan base-package="com.ssm.controller" /> <!-- Avoid download files when IE executes AJAX and return to JSON--> <bean id="mappingJacksonHttpMessageConverter" > <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- Start SpringMVC annotation function to complete the mapping of requests and annotations POJOs --> <bean > <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON converter--> </list> </property> </bean> <!-- Define the pre-suffix of the jumped file, view mode configuration--> <bean> <!-- My understanding of the configuration here is to automatically prefix and suffix the string returned by the method of the subsequent action to become an available url address--> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- Configuration file upload. If you do not use file upload, you do not need to configure it. Of course, if you do not match, then there is no need to introduce the upload component package in the configuration file --> <bean id="multipartResolver" > <!-- Default encoding--> <property name="defaultEncoding" value="utf-8" /> <!-- Maximum file size --> <property name="maxUploadSize" value="10485760000" /> <!-- Maximum value in memory --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
Step 10: Configure the web.xml file
The introduction of spring-mybatis.xml and the configured spring-mvc Servlet are for SSM integration. The previous two framework integration did not require any configuration here.
<?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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- Spring and mybatis configuration files --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- Encoding filter--> <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> <!-- Prevent Spring memory from overflowing listener--> <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:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- Here you can configure *.do, corresponding to the suffix habit of struts--> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
Step 11 Final Test:
(1) Write login.jsp first
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><html><head><title>User login:</title></head><body><form action="login"><label>User name:</label><input type="text" id="username" name="username"></input><br><br><label>Password:</label><input type="text" id="password" name="password"></input><br><br><input type="submit" value="Login"/></form></body></html>
interface:
(2) Writing UserController
import javax.servlet.http.HttpServletRequest;import org.springframework.steretype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.ssm.dao.UserDao;import com.ssm.model.User;@Controllerpublic class UserController { @Resource private UserDao userDao; @RequestMapping("/jsp/login") public String login(HttpServletRequest request){ String username=request.getParameter("username"); String password=request.getParameter("password"); User user=new User(); //Query the database user.setName(username); user.setPassword(password); User users=userDao.findUserById(user); //If there are students, it means that the login is successful if(users!=null){ return "susscss"; } //I didn't write this jsp, as long as you know, you can write your own return "err";} }(3) Finally, susscss.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><html><body><P>The user account password is correct, the login is successful</P></body></html>
Perfect!
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.