SSM的环境搭建(整合Spring、SpringMVC、Mybatis框架)

版权声明:本文为博主原创文章,版权归原作者小思所有,转载或者引用本文内容请注明来源及原作者 https://blog.csdn.net/zeal9s/article/details/83856277

本案例基于开发工具IDEA、MySQL,模拟查询学生类的信息

项目模块图:
在这里插入图片描述
MySQL中Student表
在这里插入图片描述
(1)新建一个maven的web-app项目
(2)新建test、java、resources文件夹,并对文件进行标记
在这里插入图片描述
(3)将controller(控制包)、mapper(映射包)、model(模型包)、services(业务包的接口)、serviceImpl(业务包的实现包)等基本包建好,然后进行各文件的配置
pom.xml(整合需//要的依赖,如果需要其他依赖,请前往Maven的中央仓库查找)

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringMVC</artifactId>
        <groupId>SpringMVC</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>SSM</groupId>
    <artifactId>SSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>SSM Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <!--spring的版本-->
        <spring.version>4.3.10.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!--单元测试的依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--MyBatis的依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!--MySQL的依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.43</version>
        </dependency>
        <!--SpringMVC的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring连接数据库的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring配置切面的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring的上下文的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring和MyBatis和整合依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--C3p0的依赖-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.1</version>
        </dependency>
        <!--servlet的依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>SSM</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

先搭建SpringMVC的环境
springmvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置注解扫描仪-->
    <context:component-scan base-package="com.zs"></context:component-scan>
    <!--配置内部视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置页面访问的前后缀-->
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

db.properties(连接数据库的配置文件)

#配置数据库的连接
user=root
password=1234
jdbcUrl=jdbc:mysql://localhost:3306/zs?characterEncoding=utf-8
dirverClass=com.mysql.jdbc.Driver
initialPoolSize=3
maxPoolSize=20

applicationContext-common.xml(spring的核心配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--引入数据库配置文件-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!--配置数据库连接池c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="driverClass" value="${dirverClass}"></property>
        <property name="initialPoolSize" value="${initialPoolSize}"></property>
        <property name="maxPoolSize" value="${maxPoolSize}"></property>
    </bean>

    <!--配置sqlSessionFactory,由spring工厂代理产生-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--类型命名-->
        <property name="typeAliasesPackage" value="com.zs.model"></property>
    </bean>

    <!--配置扫描Mapper包下的映射类-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zs.mapper"></property>
    </bean>

    <!--配置事务管理器,事务需要切面和切点-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置切面-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--配置切面的方法和事务的传播特性-->
            <tx:method name="add*" propagation="REQUIRED"></tx:method>
            <tx:method name="delete*" propagation="REQUIRED"></tx:method>
            <tx:method name="update*" propagation="REQUIRED"></tx:method>
            <!--所有查询的方法不需要事务-->
            <tx:method name="*" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--配置切点-->
    <aop:config>
        <!--* com.zs.services.*.*(..)   com.zs.services包下的所有类的所有方法的所有参数的返回类型-->
        <aop:pointcut id="pointCut" expression="execution(* com.zs.services.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"></aop:advisor>
    </aop:config>


</beans>

web.xml(项目启动的配置文件)

<!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>Archetype Created Web Application</display-name>
  <!--spring的上下文-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext-common.xml</param-value>
  </context-param>
  <!--spring的核心监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--springMVC的核心的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-config.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

Student.java(学生模型类)

package com.zs.model;

/**
 * @author 小思
 * @PackageName:com.zs.model
 * @ClassName: Student
 * @Description:对应数据库的Studen表
 * @date 2018/11/7 20:23
 */
public class Student {
    private Integer sid;//学生的Id
    private String sname;//学生的姓名
    private String ssex;//学生的姓名
    private String sage;//学生的年龄

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getSsex() {
        return ssex;
    }

    public void setSsex(String ssex) {
        this.ssex = ssex;
    }

    public String getSage() {
        return sage;
    }

    public void setSage(String sage) {
        this.sage = sage;
    }

    public Student() {
    }

    public Student(String sname, String ssex, String sage) {
        this.sname = sname;
        this.ssex = ssex;
        this.sage = sage;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", sname='" + sname + '\'' +
                ", ssex='" + ssex + '\'' +
                ", sage='" + sage + '\'' +
                '}';
    }
}

StudentMapper.java

package com.zs.mapper;

import com.zs.model.Student;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 小思
 * @PackageName:com.zs.mapper
 * @ClassName: StudentMapper
 * @Description:学生类的映射类(使用注解操作数据库)
 * @date 2018/11/7 20:23
 */

@Service("studentMapper")
public interface StudentMapper {
    //查询所有的学生
    @Select("select * from student")
    public List<Student> getAllStudent();
}



StudentService.java

package com.zs.services;

import com.zs.model.Student;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 小思
 * @PackageName:com.zs.services
 * @ClassName: StudentService
 * @Description:业务层的接口
 * @date 2018/11/7 20:25
 */
public interface StudentService {
    //查询所有的学生
    public List<Student> getAllStudent();
}

StudentServiceImpl.java

package com.zs.services.Impl;

import com.zs.mapper.StudentMapper;
import com.zs.model.Student;
import com.zs.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 小思
 * @PackageName:com.zs.services.Impl
 * @ClassName: StudentServiceImpl
 * @Description:实现业务层的接口
 * @date 2018/11/7 20:26
 */
@Service("studentMapper")
public class StudentServiceImpl implements StudentService {
    //根据返回类型自动注入
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public List<Student> getAllStudent() {
        return studentMapper.getAllStudent();
    }
}

StudentController.java(项目的控制器)

package com.zs.controller;

import com.zs.model.Student;
import com.zs.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

/**
 * @author 小思
 * @PackageName:com.zs.controller
 * @ClassName: StudentController
 * @Description:
 * @date 2018/11/7 20:21
 */
@Controller
public class StudentController {
    @Resource(name = "studentService",type = com.zs.services.Impl.StudentServiceImpl.class)
    //@Autowired
    private StudentService studentService;
    @RequestMapping("getAllStudent")
    public String getAllStudent(){
        System.out.println("请求已经进入");
        System.out.println(studentService.getAllStudent().size());
        return "index";
    }

}

(4)测试:将项目启动,在浏览器地址访问http://localhost:8080/getAllStudent.action,如果浏览器页面出现
在这里插入图片描述
控制台出现
在这里插入图片描述

说明项目搭建成功!

注意数据库连接配置文件修改为你自己的数据库配置

如果不使用以上的注解式开发,用模型类的xml文件开发,则需要在mapper包下新建Student.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">
<mapper namespace="com.zs.mapper.StudentMapper">
    <!--查询所有的学生-->
    <select id="getAllStudent" resultType="Student">
        select * from student
    </select>
</mapper>

在pom.xml配置可以编译xml文件
在这里插入图片描述

		<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

applicationContext-common.xml在配置文件中的sqlSessionFactory部分添加代码:

		<!--配置映射文件-->
        <property name="mapperLocations" value="classpath:com/zs/mapper/*.xml"></property>

将StudentMapper.java文件的注解删除

package com.zs.mapper;

import com.zs.model.Student;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 小思
 * @PackageName:com.zs.mapper
 * @ClassName: StudentMapper
 * @Description:学生类的映射类(使用注解操作数据库)
 * @date 2018/11/7 20:23
 */

@Service("studentMapper")
public interface StudentMapper {
    public List<Student> getAllStudent();
}



重新发布项目即可。

搭建环境基本步骤:

1):导入所需依赖到pom.xml

2):配置springmvc-config.xml

3):配置数据库连接文件

4):建各类的包controller(控制包)、mapper(映射包)、model(模型包)services(业务类接口包)、servicesImpl(业务接口实现包)

5):建立spring的核心配置文件
引入数据库配置文件–>配置数据库连接池c3p0–>配置sqlSessionFactory–>配置扫描Mapper包下的映射类–>配置事务管理器–>配置切面–>配置切点

6):web.xml配置好springmvc(springMVC的核心的servlet)和spring(spring的上下文、spring的核心监听器)

说在最后的话:编写实属不易,若喜欢或者对你有帮助记得点赞+关注或者收藏哦~

猜你喜欢

转载自blog.csdn.net/zeal9s/article/details/83856277
今日推荐