SSM Framework Integration

Keywords: Spring xml Mybatis Java

When you do not see the flower, it will be silent with your heart. When you come to see the flower, the color of the flower becomes clear for a moment, and you will know that the flower is not outside your heart.

The previous chapter briefly introduced the Spring MVC interceptor (14), if not seen. Look at the last chapter..

I. Integration of SSM Framework

SSM framework refers to Spring + Spring MVC + MyBatis framework.

Among them, Spring's knowledge can refer to old Butterfly's previous articles. Simple Development of Spring's "Two Butterflies Fly, Hello" (I)
MyBatis can also refer to Old Butterfly's previous articles: A Simple Understanding of MyBatis (I)

The integration of SSM is based on the previous knowledge. It does not explain the previous knowledge.

The integration of SSM is the same as the integration of SSH in the past. But Spring MVC is part of the Spring framework, so there is no need to integrate Spring MVC with Spring framework.
So you can integrate Spring directly with MyBatis.

Integrate SSM to implement REST-style CRUD operations.

Detailed steps for integration of SSM frameworks

2.1 Create a new dynamic Web project named SSM and select version 2.5

2.2 Create packages under src and source folders of config under the project of SSM

The packages created under src are: com.yjl.pojo, com.yjl.mapper, com.yjl.service, com.yjl.service.impl, com.yjl.action, com.yjl.utils to place the code.

Create the source folder as config to place the configuration file

2.3 Create mybatis database and create user table in it. Integration with user table as an example

User fields are id,name,sex,age,description, ID is Integer, automatic growth, primary key.

Data are:

II.4 Integrated Jar Packages for Importing SSM

1. The Jar package required by MyBatis

A total of 15.

2. The jar package required by Spring + Spring MVC


A total of 25

3. JSTL template class library, there are two

4. The jar package needed by database connection pool C3P0 or the jar package needed by dbcp. Use dbcp, unlike SSH. There are two

5. Mysql database driver 1.

6. The jar package required for MyBatis and Spring integration is provided by MyBatis. Note the version and choose version 1.3. One.

Place these jar packages in the lib folder under WEB-INF.

There are 16 + 25 + 2 + 2 + 1 + 1 = 46.

After importing, commons-logging-1.2.jar package duplication (both Spring and MyBatis) was found, and one was removed.

There are two versions of log4j.jar, log4j-1.2.17.jar (MyBatis), log4j-1.2.17.jar (Spring), with low versions removed and 1.2.17 retained.

So there are only 44 jar packages left.

Create db.properties file under the five-source folder config to store the connection configuration of the database

db.properties:

##Attributes of database
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=abc123
## Attributes of database connection pool
jdbc.maxActive=30
jdbc.maxIdle=5

Prefix the database with jdbc to avoid duplication of attributes in direct url,username and spring.

2. Create log4j.properties under the six-source folder config to store log information

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout

2.7 Create mybatis folder under source folder config, then create SqlMapConfig.xml file to store MyBatis configuration

2. Create spring folder under 8 config, and then create spring configuration file

For example, application Context-dao.xml (integration of Spring and dao), application Context-service.xml (integration of Spring and Service), spring mvc.xml (configuration file of Spring MVC)

After creation, the directory under the config source folder is as follows:

The above is the basic configuration file. It hasn't really started yet. Now, the configuration is officially in place.

2.9 Using MyBatis reverse engineering to generate reverse code of user table

MyBatis's Reverse Engineering, you can watch the article written by Old Butterfly: The Use of MyBatis Reverse Engineering (12)

After the reverse engineering is executed, the User. java, UserExample. java, UserMapper. java, UserMapper. XML files are generated.

Copy User.java,UserExample.java to com.yjl.pojo package, UserMapper.java, UserMapper.xml to com.yjl.mapper package.

Add the function of paging query in MyBatis. For MyBatis paging, you can watch the articles written by Old Butterfly before: Use of MyBatis's pageHelper Paging Plug-in (XV)

You need to add paging code in UserExample, UserMapper.java, UserMapper.xml.

So it needs to be changed slightly.

The changed documents are as follows:

User.java

package com.yjl.pojo;

import java.io.Serializable;

public class User implements Serializable{
	private static final long serialVersionUID = 6736354022794444729L;

	private Integer id;

    private String name;

    private Integer age;

    private String sex;

    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description == null ? null : description.trim();
    }

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + ", description=" + description
				+ "]";
	}
}

UserExample.java

package com.yjl.pojo;

import java.util.ArrayList;
import java.util.List;

public class UserExample {
    protected String orderByClause;

    protected boolean distinct;
    
    //Add two fields for paging.
    private int start;  //Starting position
    
    private int offset; //Maximum number of pages displayed
    
    public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	// The main reason for omitting the code generated by reverse engineering is that there are too many, so the old butterfly will not replicate.
   
}

UserMapper.java

package com.yjl.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;

public interface UserMapper {
    int countByExample(UserExample example);

    int deleteByExample(UserExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    List<User> selectByExample(UserExample example);

    User selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

    int updateByExample(@Param("record") User record, @Param("example") UserExample example);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    
    //Query according to sql statement
	List<User> selectBySQL(@Param(value="limit")int limit, 
			@Param(value="offset") int offset);
}

UserMapper.xml

There are too many codes to copy. On top of the code generated by reverse engineering, write selectBySQL.

 <!-- Paging query -->
   <select id="selectBySQL" resultMap="BaseResultMap" parameterType="com.yjl.pojo.UserExample" >
    select
    <include refid="Base_Column_List" />
    from user
    limit #{limit},#{offset}
  </select>

The style is:

II.10 Config.xml configuration of Mybatis file in SqlMapConfig.xml

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Introducing constraints -->
<!DOCTYPE configuration  
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<!-- Setting up configuration files -->
		<!-- Open Level 2 Cache -->
		<setting name="cacheEnabled" value="true"/>
		<!-- Controlling lazy loading -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
		<setting name="multipleResultSetsEnabled" value="true"/>
		<setting name="useColumnLabel" value="true"/>
		<setting name="useGeneratedKeys" value="false"/>
		<setting name="autoMappingBehavior" value="PARTIAL"/>
		<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
		<setting name="defaultExecutorType" value="SIMPLE"/>
		<setting name="defaultStatementTimeout" value="25"/>
		<setting name="defaultFetchSize" value="100"/>
		<setting name="safeRowBoundsEnabled" value="false"/>
		<setting name="localCacheScope" value="SESSION"/>
		<setting name="jdbcTypeForNull" value="OTHER"/>
		<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
		<!-- Set the log to log4j -->
		<setting name="logImpl" value="LOG4J"/>
	</settings>
	<!-- Configure aliases -->
	<typeAliases>
		<!-- Define the form of the package ,There can be multiple-->
		<package name="com.yjl.pojo"/>
	</typeAliases>
	
	<!-- After the alias, before the environment -->
	<plugins>
		<!-- Paging plug-in, introducing interceptors -->
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!-- Specify the database as mysql,Although it will be automatically monitored. -->
			<property name="helperDialect" value="mysql"/>
		</plugin>
	</plugins>
	
</configuration>

Compared with the previous configuration of MyBatis, the configuration of database configuration and mapping file is removed and completed by application Context-dao.xml.

Only set, type Aliases, plugins are retained.

II.11 Configuration of Application Context-dao.xml

applicationContext-dao.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

	<!-- Load db.properties The contents of the document, db.properties Documentation key There must be some special rules for naming -->
	<context:property-placeholder location="classpath:db.properties" />
	<!-- Configure the data source. dbcp -->
	<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}" />
		<property name="maxActive" value="${jdbc.maxActive}" />
		<property name="maxIdle" value="${jdbc.maxIdle}" />
	</bean>
	<!-- sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- Database connection pool -->
		<property name="dataSource" ref="dataSource" />
		<!-- Load mybatis Global Profile -->
		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
	</bean>
	<!-- mapper Scanner -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- Scanning packet paths, if multiple packets need to be scanned, separated by a half-corner comma -->
		<property name="basePackage" value="com.yjl.mapper"></property>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>
</beans>

The work done is to configure the data source, generate sqlSession Factory, and configure the scanner.

2.12 Create UserService Interface and UserService Impl Implementation Class

UserService interface:

package com.yjl.service;

import java.util.List;

import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;

/**
 @author:yuejl
 @date: 2019 9 September 7:40:35 p.m.
 @Description Relevant Descriptions of Classes
*/
public interface UserService {
    int countByExample(UserExample example);

    int deleteByExample(UserExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    List<User> selectByExample(UserExample example);

    User selectByPrimaryKey(Integer id);

    int updateByExampleSelective( User record,UserExample example);

    int updateByExample(User record, UserExample example);

    int updateByPrimaryKeySelective(User record);
    int updateByPrimaryKey(User record);
    //Query according to sql statement
	List<User> selectBySQL(int limit, int offset);
}

UserService Impl implementation class:

package com.yjl.service;

import java.util.List;

import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;

/**
 @author:yuejl
 @date: 2019 9 September 7:40:35 p.m.
 @Description Relevant Descriptions of Classes
*/
public interface UserService {
    int countByExample(UserExample example);

    int deleteByExample(UserExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    List<User> selectByExample(UserExample example);

    User selectByPrimaryKey(Integer id);

    int updateByExampleSelective( User record,UserExample example);

    int updateByExample(User record, UserExample example);

    int updateByPrimaryKeySelective(User record);
    int updateByPrimaryKey(User record);
    //Query according to sql statement
	List<User> selectBySQL(int limit, int offset);
}

The styles are as follows:

II.13 Configuration of Application Context-service.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- Transaction Manager 
	//For mybatis operation database transaction control, spring uses jdbc transaction control class
-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<!-- data source
	dataSource stay applicationContext-dao.xml Configured in
	 -->
	<property name="dataSource" ref="dataSource"/>
</bean>

<!-- notice -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<tx:attributes>
		<!-- Communication Behavior -->
		<!--List common methods-->
          <tx:method name="insert*" propagation="REQUIRED" />  
          <tx:method name="update*" propagation="REQUIRED" />  
          <tx:method name="edit*" propagation="REQUIRED" />  
          <tx:method name="save*" propagation="REQUIRED" />  
          <tx:method name="add*" propagation="REQUIRED" />  
          <tx:method name="new*" propagation="REQUIRED" />  
          <tx:method name="set*" propagation="REQUIRED" />  
          <tx:method name="remove*" propagation="REQUIRED" />  
          <tx:method name="delete*" propagation="REQUIRED" />  
          <tx:method name="change*" propagation="REQUIRED" />  
          <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
          <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
          <tx:method name="count*" propagation="REQUIRED" read-only="true" />  
          <tx:method name="load*" propagation="REQUIRED" read-only="true" />  
          <tx:method name="*" propagation="REQUIRED" read-only="true" />  
	</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
	<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.yjl.service.impl.*.*(..))"/>
</aop:config>
</beans>

Mainly configure transactions, using the idea of AOP.

II.14 Backend UserAction

Implement CRUD operation and inject UserService interface

UserAction.java

package com.yjl.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yjl.pojo.User;
import com.yjl.service.UserService;

/**
@atuhor:yuejl
@Description: Class Description
*/
@Controller
@RequestMapping(value="/user")
public class UserAction {
	@Autowired
	private UserService userService;
	//Go to the login page
	@RequestMapping(value="toLogin")
	public String toLogin(Model model){
		model.addAttribute("user",new User());
		return "user/login";
	}
	//Make sure you don't forget to add the produces attribute. When added, the method is POST
	@RequestMapping(value="add",method=RequestMethod.POST,produces={"application/json"})
	public @ResponseBody Map<String,Object> add(User user){
		userService.insert(user);
		Map<String,Object> resultMap=new HashMap<String,Object>();
		resultMap.put("request_status",true);
		return resultMap;
	}
	//When modified, the method is PUT   
	@RequestMapping(value="edit/{id}",method=RequestMethod.PUT,produces={"application/json"})
	public @ResponseBody Map<String,Object> edit(User user){
		userService.updateByPrimaryKeySelective(user);
		Map<String,Object> resultMap=new HashMap<String,Object>();
		resultMap.put("request_status",true);
		return resultMap;
	}
	//When deleted, the method uses DELETE
	@RequestMapping(value="deleteById/{id}",method=RequestMethod.DELETE,produces={"application/json"})
	public @ResponseBody Map<String,Object> deleteById(@PathVariable(value="id") int id){
		userService.deleteByPrimaryKey(id);
		Map<String,Object> resultMap=new HashMap<String,Object>();
		resultMap.put("request_status",true);
		return resultMap;
	}
	//When querying, use GET
	@RequestMapping(value="findById/{id}",method=RequestMethod.GET,produces={"application/json"})
	public @ResponseBody Map<String,Object> findById(@PathVariable(value="id") int id){
		User user=userService.selectByPrimaryKey(id);
		Map<String,Object> resultMap=new HashMap<String,Object>();
		resultMap.put("request_status",true);
		resultMap.put("user",user);
		return resultMap;
	}
	//When querying, use GET
	@RequestMapping(value="findAll",method=RequestMethod.GET,produces={"application/json"})
	public @ResponseBody Map<String,Object> findAll(){
		List<User> userList=userService.selectBySQL(1, 10);
		Map<String,Object> resultMap=new HashMap<String,Object>();
		resultMap.put("request_status",true);
		resultMap.put("userList",userList);
		return resultMap;
	}
}


II.15 Spring mvc.xml Configuration

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
       	http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd ">
	<!-- Configured with annotations,Rewrite View Parser -->
	<context:component-scan base-package="com.yjl.action,com.yjl.service"></context:component-scan>
	
	<!--Configuring static resources -->
	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/image/" mapping="/image/**"></mvc:resources>
	
	<!-- Set up fastjson Configuration scheme -->
    <mvc:annotation-driven>
    	<!-- Setting up a message converter that does not use the default -->
        <mvc:message-converters register-defaults="false">
        	<!-- To configure Spring Converter -->
        	<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
    		<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
    		<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
    		<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
            <!-- To configure fastjson Realization in Chinese HttpMessageConverter Interface Converter -->
            <bean id="fastJsonHttpMessageConverter" 
            	class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <!-- Added Support Media Type: Return contentType -->
                <property name="supportedMediaTypes">
                    <list>
                        <!-- The order here can not be reversed, we must write first. text/html,otherwise ie Download hints will appear below -->
                       <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
				 <!-- Additional attributes can be added to extend functionality,If Date -->
                 <property name="features">
                    <list>
                    <!-- Default means that if you do not configure this property, you will not configure it by default. -->
                       <!-- Whether the output value is null The default is false-->
                        <value>WriteMapNullValue</value>
                        
                        <value>WriteNullNumberAsZero</value>
                        <value>WriteNullListAsEmpty</value>
                        <value>WriteNullStringAsEmpty</value>
                        <value>WriteNullBooleanAsFalse</value>
                        <value>WriteDateUseDateFormat</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
	
	<!-- view resolver -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- prefix -->
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<!-- Suffix -->
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>

Configure json, and view parser. If there are converters and internationalizations, configure them according to what the old butterfly said before.

II.16 web.xml configuration file

<?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" id="WebApp_ID" version="2.5">
  <display-name>SSM</display-name>
  
  <!-- start-up spring -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- Random Code Filter -->
  <filter>
    <filter-name>EncodingFilter</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>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- Hidden Domain Method -->
  <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>
  
  <!--Front-end controller -->
  <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/springmvc.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>
  
  <!-- Welcome page -->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

II.17 Front-end login.jsp page

Ajax is used to transmit data.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="/SSM/js/jquery-2.1.1.min.js"></script>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<title>Exhibition</title>
</head>
<body>
	<h2>Two Butterflies Flying,SSM Framework integration</h2>
	<form:form commandName="user" type="post">
		<button type="button" id="add" onclick="addJson()">Add to</button><br/>
		<button type="button" id="edit" onclick="editJson()">modify</button><br/>
		<button type="button" id="delete" onclick="delJson()">delete</button><br/>
		<button type="button" id="findById" onclick="findByIdJson()">query id></button><br/>
		<button type="button" id="findAll" onclick="findAllJson()">All queries</button><br/>
		<div id="showId"> Information presented</div>
	</form:form>
	
	<script>
	function addJson(){
		jsonAjax("add","add","id=10&name=Elf Sister&password=1234&sex=female&age=24&description=A Happy Spirit&_method=POST");
	}
	function editJson(){
		jsonAjax("edit","edit/10","id=10&name=Elf Sister&description=A Happy Elf&_method=PUT");		
		}
	function delJson(){
		jsonAjax("delete","deleteById/10","_method=DELETE");
	}
	function findByIdJson(){
		jsonAjax("findById","findById/10","_method=GET");
	}
	function findAllJson(){
		jsonAjax("findAll","findAll","_method=GET");
	}
	function jsonAjax(sign,url,data){
		var message="";
		switch(sign){
			case "add":{
				message="Added Successfully";
				break;
			}
			case "edit":{
				message="Successful revision";
				break;
			}
			case "delete":{
				message="Successful deletion";
				break;
			}
			case "findById":{
				message="Query single success";
				break;
			}
			case "findAll":{
				message="All the queries were successful.";
				break;
			}
		}
		
		$.ajax({
			type:"post", 
			url:url,  //Note the request path
			data:data,
			success:function(resultData){
				if(resultData.request_status){
					//empty
					$("#showId").empty();
					//Append
					$("#showId").append(message+"<br/>");
					
					if(sign=="findById"){
						var data=resultData.user;
						var str="<table><tr><th>number</th><th>Full name</th><th>describe</th></tr>";
						str+="<tr>"; 
						str+="<td>"+data.id+"</td>"; 
						str+="<td>"+data.name+"</td>"; 
						str+="<td>"+data.description+"</td>"; 
						str+="</tr>"; 
						str+="</table>";
						$("#showId").append(str);
					}
					if(sign=="findAll"){
						var data=resultData.userList;
						var str="<table><tr><th>number</th><th>Full name</th><th>describe</th></tr>";
						$.each(data,function(idx,item){ 
							str+="<tr>"; 
							str+="<td>"+item.id+"</td>"; 
							str+="<td>"+item.name+"</td>"; 
							str+="<td>"+item.description+"</td>"; 
							str+="</tr>"; 
						}) 
						str+="</table>";
						$("#showId").append(str);
					}
				}
			}
		})
	}
	</script>
</body>
</html>

2.18 Restart the server to verify the success of integration

Click Query All

Click Add, and then click Query All

The database shows:

Click Modify, and then click Query All

Database Display


Click on the query id to display:

It shows that the integration is successful.

II.19 Other Configurations

For service layer processing, Old Butterfly added @Service annotations to the UserService Impl implementation class, and then configured only one application Context-service.xml configuration file. Then when the springmvc.xml package is scanned, the com.yjl.service package is scanned.

Some people will create application Context-service.xml and application Context-tx.xml configuration files, and place bean s in - service.xml files to instantiate the implementation class of UserService Impl.

<!--Write multiple bean-->
<bean id="userService" class="com.yjl.service.impl.UserServiceImpl"></bean>

- Transaction processing is placed in tx.xml, which is the content of application Context - service. XML in Old Butterfly.
Too much, no replication. That is, the content of the second and thirteenth chapter.

In this way, you don't need to add the @Service annotation to UserService Impl, and you don't need to scan the com.yjl.service package when scanning spring mvc. xml.

Both can be done.

Thank you!!!

Posted by blink359 on Mon, 09 Sep 2019 22:21:45 -0700