In depth analysis based on spring+springmvc+hibernate integration

  • 2021-11-24 01:31:53
  • OfStack

Directory 1. Create a new maven web project 2. pom file, import jar package 3. Configuration file 4. spring-mvc and spring integration 5. spring and hibernate integration 6. Summary

The three frameworks have been built many times over and over again. Although they can be built every time, the efficiency is not high. Recently, I re-built it once, straightened out my thinking, sorted out the places that need attention, and shared it.

Tools: Eclipse (jdk 1.7) spring and hibernate versions 4.0 and above

It is recommended to use maven to build projects, which is much more convenient than importing jar packages manually.

1. Create a new maven web project

(If you have never used maven, you can go to i to know it first)

Note: The maven project file structure created using Eclipse may not be correct, and you need to manually create the folder yourself.

Correct file structure:

-src

---main

--java (class file)

----resources (configuration file)

--webapp (web file)

--test (test file)

------java

------resources

2. pom file, import jar package

Importing jar packages is also a troublesome point in framework integration. Too many irrelevant packages are often imported, but they are unfamiliar and afraid to delete them, so jar

The packets are introduced more and more, and the framework is put up in the end, but jar packets are introduced more than 10 or 210.

Note: The recommended practice here is to import the core package first when you are unfamiliar with what jar packages need to be imported by the framework, and then add relevant dependencies according to the error prompt when prompting NotFoundClass when running the project, so as not to import redundant jar packages.

It is recommended to search for the dependencies you need on this website: https://mvnrepository.com/

pom file:


<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>hcoding</groupId>
  <artifactId>MyWebDemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>MyWebDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- spring start -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <!-- spring end -->
    <!-- springmvc start -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
    <!-- springmvc end -->
    <!-- loging start -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.6</version>
    </dependency>
    <!-- loging end -->
    <dependency>
        <groupId>aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjtools</artifactId>
        <version>1.8.7</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>javax.annotation-api</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <!-- hibernate start -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.2.3.Final</version>
    </dependency>
    <!-- hibernate end -->
    <!--c3p0 start -->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <!-- c3p0 end -->
    <!-- mysql start-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.35</version>
    </dependency>
    <!-- mysql end-->
  </dependencies>
    <build>
        <finalName>MyWebDemo</finalName>
    </build>
</project>

Where the comment block < spring > < springmvc > < hibernate > The dependencies in import framework core jar package, we can import in advance, others we can change according to prompts or requirements.

For example, my project uses the mysql database and the c3p0 data source, so the MySQL and c3p0 dependencies are introduced, and if you are using other databases and data sources, you need to make corresponding modifications.

The annotated part of pom file is the dependency introduced by the missing jar package prompted when the project is running, some of which are dependent on spring framework, and some of which are dependent on servlet or jsp. If you are unfamiliar with it when you build it for the first time, you can not import it first, and then introduce the dependency when you report an error, which can also deepen your understanding.

3. Configuration files

This is the most important part of framework integration. In addition to web. xml, the configuration files are placed in the main/resources folder. Of course, you can also put them in other new folders, but the configuration file address should be modified accordingly, which will be described in detail later.

Configuration file configuration, a lot of framework integration tutorials are not very 1 kind, here gives my own configuration methods and practices.

There are four main configuration files: web. xm, beans. xml, spring-mvc. xml, datasource. xml.

The configuration step is divided into two steps, the integration of spring-mvc and spring, the integration of hibernate and spring, and finally running the project. (This is also an efficient way to integrate separately, so that even if the running project has errors, it is easier to find, and the division integration is not easy to be chaotic)

Next, we will start the specific configuration.

4. spring-mvc and spring integration

This is the spring-mvc. xml configuration file:


<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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <mvc:annotation-driven />
    <context:component-scan base-package="com.hcoding.demo" >
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <!--  Exclude @service Annotated class  -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>
    <!--  Resolution of Model View Names , Add a prefix to the model view name on request  -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="demo/" /> <!--  Prefix  -->
        <property name="suffix" value=".jsp" />   <!--  Suffix  -->
    </bean>
    <!--  Mapping to static resources -->
    <mvc:resources mapping="/js/**" location="/resources/js/" />
    <mvc:resources mapping="/css/**" location="/resources/css/" />
    <mvc:resources mapping="/img/**" location="/resources/img/" />
</beans>

This is the basic configuration of spring-mvc, mainly for request and static resource mapping.

Note:

1. Special attention should be paid to excluding classes in service layer when scanning packages, otherwise, after integrating hibernate, the project runtime will report errors.

See this article for specific reasons

2. Then, if your package name and structure are different, remember to change the scan package address.

Then there is the web. xml configuration file:


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>MyWebDemo</display-name>
    <!--  Unified 1 Code   Solve the problem of Chinese garbled codes -->
    <filter>
        <filter-name>charsetEncoding</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>charsetEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- spring MVC  Configure -->
    <servlet>
         <servlet-name>spring</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--  What we point to here is SpringMVC Configuration file for   If the profile address and name are not 1 Sample needs to be changed -->
            <param-value>classpath:spring-mvc.xml</param-value>
         </init-param>
         <!-- The configuration container loads this at startup time servlet And instantiate -->
         <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- spring MVC config end-->
</web-app>

Add the spring-mvc configuration file to web. xml, and springmvc will not be loaded until the server starts the project. After the configuration is completed, write an example to test 1.

The project structure at this time:

-src

---main

--java (class document)

----------com.hcoding.controller

----------com.hcoding.service

----------com.hcoding.dao

----------com.hcoding.model

----resources (configuration file)

----------spring-mvc.xml

--webapp (web file)

----demo (jsp document)

-----resources (static resource files: css, js, img)

-----WEB-INF (web related configuration file)

First create DemoController in the controller package, class:


package com.hcoding.demo.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.hcoding.demo.model.People;
import com.hcoding.demo.service.DemoService;
@Controller
public class DemoController{
    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}

Then create demo. jsp in the demo folder:


<%@ page language="java" contentType="text/html; 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">
<title>Insert title here</title>
</head>
<body>
<p> This is the test page. </p>
</html>

Start the project and enter the address in the browser: http://localhost: 8080/(project name)/test. Success can see the page.

5. Integration of spring and hibernate

datasource. xml configuration file:


<?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:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
    http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
   http://www.springframework.org/schema/jee 
   http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.2.xsd">
   <!-- Configure the data source   What is used here is c3p0 Connection pool -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
       <property name="driverClass" value="${jdbc.driver}" />  <!-- Database connection driver -->
       <property name="jdbcUrl" value="${jdbc.url}" />     <!-- Database address -->
       <property name="user" value="${jdbc.username}" />   <!-- User name -->
       <property name="password" value="${jdbc.password}" />   <!-- Password -->
       <property name="maxPoolSize" value="40" />      <!-- Maximum number of connections -->
       <property name="minPoolSize" value="1" />       <!-- Minimum number of connections -->
       <property name="initialPoolSize" value="10" />      <!-- Initialize a database connection in a connection pool -->
       <property name="maxIdleTime" value="20" />  <!-- Maximum free time -->
   </bean>
   <!-- Configure session Factory -->
   <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
       <property name="dataSource" ref="dataSource" />
       <property name="packagesToScan" value="com.hcoding.demo" />
       <property name="hibernateProperties">
           <props>38                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate Automatically generate database tables from entities -->
               <prop key="hibernate.dialect">${hibernate.dialect}</prop>   <!-- Specify the database dialect -->
               <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>     <!-- Display database operation statements performed on the console -->
               <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>     <!-- Display the executed data crying operation statement on the console (format) -->
           </props>
       </property>
   </bean>
   
   <!--  Transaction configuration   Declarative transaction -->
   <bean id="transactionManager"
       class="org.springframework.orm.hibernate4.HibernateTransactionManager">
       <property name="sessionFactory" ref="sessionFactory" />
   </bean>
   <!--  Use annotation Defining Transactions  -->
   <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

datasource. properties file:


#database connection config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = 123456
#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

beans. xml file:


<?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:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
    <!--  Annotation  -->
    <context:annotation-config />
    <!-- Scanning -->
    <context:component-scan base-package="com.hcoding.demo">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!--  Import multiple Properties Configuration file  -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!-- If you have multiple profiles, just continue to add them here  -->
                <value>classpath:datasource.properties</value>
            </list>
        </property>
    </bean>
31     <!--  Load the data source component  -->        32     <import resource="classpath:datasource.xml" />33     34 </beans>

Note: In xml import properties file is more common, will be one of the relevant configuration data written to properyties file is also a common method to facilitate modification.

Another common way to import propertise: < context:property-placeholder location="classpath:/datasource.properties" / > . The default value of spring in this method only imports 1 properties,

When you have multiple properties files to import, you need to use another method:


    <!--  Import multiple Properties Configuration file  -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!-- If you have multiple profiles, just continue to add them here  -->
                <value>classpath:datasource.properties</value>                
                <value>classpath:redis.properties</value>
            </list>
        </property>
   </bean>

Personally, this is recommended. With the expansion of the project, the number of configurations that need to be imported increases, and there is definitely more than one properties file. This method is more common.

Note: The database address, user and password in datasource. properties file are modified according to your own situation.

Modify the previous web. xml file:


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>MyWebDemo</display-name>
    <!--  Unified 1 Code   Solve the problem of Chinese garbled codes -->
    <filter>
        <filter-name>charsetEncoding</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>charsetEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- spring MVC  Configure -->
    <servlet>
         <servlet-name>spring</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--  What we point to here is SpringMVC Configuration file for  -->
            <param-value>classpath:spring-mvc.xml</param-value>
         </init-param>
         <!-- The configuration container loads this at startup time servlet And instantiate -->
         <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- spring MVC config end-->
    <!--  Loading spring Configuration file  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>
    <!-- listener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

These are the four files that spring needs to configure to integrate hibernate. Load sequence and inclusion relationship of files: web. xml → bans. xml → datasource. xml → datasource. properties

Note: If your profile name and location are different, you need to modify it accordingly.

Note: 1 Always remember to configure transactions, otherwise the project may not report errors when operating the database, but the data in the database will not be updated (deleted or modified). Specific can own Baidu affairs related knowledge.

After the configuration is completed, write an example to test 1.

Create People in the model package. class:


<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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <mvc:annotation-driven />
    <context:component-scan base-package="com.hcoding.demo" >
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <!--  Exclude @service Annotated class  -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>
    <!--  Resolution of Model View Names , Add a prefix to the model view name on request  -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="demo/" /> <!--  Prefix  -->
        <property name="suffix" value=".jsp" />   <!--  Suffix  -->
    </bean>
    <!--  Mapping to static resources -->
    <mvc:resources mapping="/js/**" location="/resources/js/" />
    <mvc:resources mapping="/css/**" location="/resources/css/" />
    <mvc:resources mapping="/img/**" location="/resources/img/" />
</beans>
0

And create the people table in the database and add the corresponding fields.

Then create DemoDao in the dao package. class:


<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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <mvc:annotation-driven />
    <context:component-scan base-package="com.hcoding.demo" >
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <!--  Exclude @service Annotated class  -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>
    <!--  Resolution of Model View Names , Add a prefix to the model view name on request  -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="demo/" /> <!--  Prefix  -->
        <property name="suffix" value=".jsp" />   <!--  Suffix  -->
    </bean>
    <!--  Mapping to static resources -->
    <mvc:resources mapping="/js/**" location="/resources/js/" />
    <mvc:resources mapping="/css/**" location="/resources/css/" />
    <mvc:resources mapping="/img/**" location="/resources/img/" />
</beans>
1

Create DemoServic in the service package. class:


<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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <mvc:annotation-driven />
    <context:component-scan base-package="com.hcoding.demo" >
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <!--  Exclude @service Annotated class  -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Service" />
    </context:component-scan>
    <!--  Resolution of Model View Names , Add a prefix to the model view name on request  -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="demo/" /> <!--  Prefix  -->
        <property name="suffix" value=".jsp" />   <!--  Suffix  -->
    </bean>
    <!--  Mapping to static resources -->
    <mvc:resources mapping="/js/**" location="/resources/js/" />
    <mvc:resources mapping="/css/**" location="/resources/css/" />
    <mvc:resources mapping="/img/**" location="/resources/img/" />
</beans>
2

Note: Add the @ Transactional annotation to the save method to open the transaction.

Call the save method in DemoController. class to save the data:


package com.hcoding.demo.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.hcoding.demo.model.People;
import com.hcoding.demo.service.DemoService;
@Controller
public class DemoController{
    @Resource(name="demoService")
    private DemoService demoService;
    @RequestMapping("/test")
    public String test(){
        People p=demoService.newPeople();
        demoService.save(p);
        return "test";
    }
}

Start the server and access the project. Refresh the database. If the data is saved in the database, the framework is completed.

6. Summary

The above is the whole process of framework integration. I also read a lot of tutorials and put them in order many times. Basically, the configuration file is neat and there is no redundant content (because it is easy to write some contents that are inexplicably absent because I don't understand the principle). Most of the contents also have explanatory functions, and I also said some things that need attention, and I made mistakes myself.

Of course, if you are building a framework for the first time, there are far fewer problems. If you encounter problems, you should have more Baidu. Of course, it will be more conducive to learning to know more about spring framework before this. In addition, the project is fully annotated, so if you don't know much about the annotations, you can also use Baidu 1.


Related articles: