English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example code for integrating ssm framework based on Maven

Basic Concepts

1.1and Spring

Spring is an open-source framework, Spring is2003 A lightweight Java development framework that emerged in the year, written by Rod Johnson in his book Expert One-On-One J2The concepts and prototypes elaborated in EE Development and Design have derived. It was created to address the complexity of enterprise application development. Spring uses basic JavaBeans to accomplish what was previously only possible with EJBs. However, the use of Spring is not limited to server-side development. From the perspectives of simplicity, testability, and loose coupling, any Java application can benefit from Spring. In short, Spring is a lightweight container framework for Inversion of Control (IoC) and Aspect-Oriented Programming (AOP).

1.2, SpringMVC

Spring MVC is a follow-up product of SpringFrameWork and has been integrated into Spring Web Flow. Spring MVC separates the roles of controllers, model objects, dispatchers, and handler objects, making them easier to customize.

1.3, MyBatis

MyBatis was originally an open source project iBatis of Apache, 2010This project was migrated from Apache Software Foundation to Google Code and renamed to MyBatis. MyBatis is a persistence framework based on Java. The persistence framework provided by iBATIS includes SQL Maps and Data Access Objects (DAO). MyBatis eliminates almost all JDBC code and manual setting of parameters as well as retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects, ordinary Java objects) to records in the database.

Step 1:Create a web project through Maven.

Step 2:pom file imports jar packages

(1) pom.xml

I have copied the entire pom file here, some initializations should be removed, and keep the one 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> 
  <!-- log4Version of j log file management package --> 
  <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 the java ee jar package --> 
  <dependency> 
   <groupId>javax/groupId> 
   <artifactId>javaee-api/artifactId> 
   <version>7.0</version> 
  </dependency> 
  <!-- Import the Mysql database connection jar package --> 
  <dependency> 
   <groupId>mysql/groupId> 
   <artifactId>mysql-connector-java/artifactId> 
   <version>5.1.30</version> 
  </dependency> 
  <!-- Import the dbcp jar package 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 the object for easy 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 --> 
  <!-- Mapping into 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>

Third step:Look at the overall project architecture, first explain that I don't have anything related to springMVC here, because I integrate sping first-mybatis, to test whether it is successful, successful in integrating springMVC

Fourth step:Establish a model class

public class User {
 private int id;
 private String name;
 private String password;
 private String password2; 
/*Provide set and get methods, toString method*/
}

Step 5:Create a database, UserDao interface and mapper mapping file

(1)Establish a simple table

(2)UserDao interface

public interface UserDao {
  User findUserById(User user);
}

(3)UesrMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//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 by id -->
 <!-- 
  id: Identifies a unique statement, consistent with the method name of UserDao
  #{}: Represents a placeholder, if simple type parameters are passed into #{}, the name in #{} is arbitrary
  parameterType: Input parameter type, consistent with the parameter type in UserDao()
  resultType: Output result type, consistent with the return type of UserDao()
  -->
 <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 UserServerImpl

(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.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/test?useUnicode=true&&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

(2)log4j.properties

log4j.rootLogger=INFO,Console,File 
#Define the log output destination as the console 
log4j.appender.Console=org.apache.log4j.ConsoleAppender 
log4j.appender.Console.Target=System.out 
The log output format can be specified flexibly, the following line specifies the specific format 
log4j.appender.Console.layout = org.apache.log4j.PatternLayout 
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n 
# A new file is generated when the file size reaches the specified size 
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 all logs, if changed to DEBUG it means output logs of DEBUG level and above 
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 

Step 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/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"> 
 <!-- Automatic scanning --> 
 <context:component-scan base-package="com.ssm" /> 
 <!-- Introduce the implementation of jdbc configuration file --> 
 <bean id="propertyConfigurer" 
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
  <property name="location" value="classpath:jdbc.properties" /> 
 </0" 
 <!-- 2. Database connection pool -->
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
  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}" /> 
 </0" 
  <!-- Spring and MyBatis integration, managing the MyBatis SqlSessionFactory session factory through Spring -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
  <!-- Specify the database connection pool reference -->
  <property name="dataSource" ref="dataSource" /> 
  <!-- Automatically scan mapping.xml files --> 
  <property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property> 
 </0" 
 <!-- The package name of the DAO interface, Spring will automatically find the classes under it --> 
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
  <property name="basePackage" value="com.ssm.dao" /> 
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 
 </0" 
 <!-- (transaction management) transaction manager, use JtaTransactionManager for global tx --> 
 <bean id="transactionManager" 
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
  <property name="dataSource" ref="dataSource" /> 
 </0" 
</bean>

Step 8:Establish the test class

After the above steps (log4j is not configured and it does not affect), we have completed the integration of Spring and mybatis, so we can write a piece of test code to try if it is successful.

The test class is located in src/test/Established in Java, if the test is successful, it indicates that Spring and Mybatis have been integrated successfully. The output information uses Log4j prints to the console.

(1TestMyBatis 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;
/*Run tests in the Spring test environment*/
@RunWith(SpringJUnit4ClassRunner.class) 
/*Used to specify the location of the Spring configuration file to be loaded, which will load the default configuration file*/
@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("张三");
  user.setPassword("123");
  User user1 = userService.getUserById(user);
  System.out.println(user1.toString());
 }
}

Finally! The key is to look at the output on the back end, which is also the time to witness miracles. If an object is output, it means you have successfully configured the integration!

So next, let's 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/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"> 
 <!-- Automatically scan the package, so that SpringMVC considers the classes annotated with @controller under the package as controllers --> 
 <context:component-scan base-package="com.ssm.controller" /> 
 <!--Avoid the situation where IE executes AJAX and the returned JSON triggers file download --> 
 <bean id="mappingJacksonHttpMessageConverter" 
  class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
  <property name="supportedMediaTypes"> 
   <list> 
    <value>text/html;charset=UTF-8</value> 
   </list> 
  </property> 
 </0" 
 <!-- Enable annotation features of SpringMVC, complete mapping of requests and annotation POJOs --> 
 <bean 
  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
  <property name="messageConverters"> 
   <list> 
    <ref bean="mappingJacksonHttpMessageConverter" />!-- JSON converter --> 
   </list> 
  </property> 
 </0" 
 <!-- Define the prefix and suffix of the file to be redirected, view mode configuration--> 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
  <!-- My understanding of this configuration is to automatically add a prefix and suffix to the string returned by the action method later, making it a usable URL address --> 
  <property name="prefix" value="/WEB-INF/jsp/" /> 
  <property name="suffix" value=".jsp" /> 
 </0" 
 <!-- Configure file upload, if file upload is not used, it is not necessary to configure, of course, if not configured, then it is not necessary to introduce the upload component package in the configuration file --> 
 <bean id="multipartResolver" 
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
  <!-- Default encoding --> 
  <property name="defaultEncoding" value="utf-8" /> 
  <!-- Maximum file size --> 
  <property name="maxUploadSize" value="10485760000" /> 
  <!-- Maximum value in memory --> 
  

(2)Writing UserController

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ssm.dao.UserDao;
import com.ssm.model.User;
@Controller
public 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 according to username and student
 user.setName(username);
 user.setPassword(password);
  User users=userDao.findUserById(user);
 //If there are students, it means the login is successful
 if(users!=null){
  return "susscss";
 }
 //I haven't written this jsp, just know that, you can write it yourself
 return "err";
} 
}

(3)last susscss.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8">
<html>
<body>
<P>User account password is correct, login successful</P>
</body>
</html>

Perfect!

That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please report violations by sending an email to codebox.com (replace # with @) and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.

You May Also Like