美文网首页
ssm框架整合(配置文件方式 和 纯注解方式)

ssm框架整合(配置文件方式 和 纯注解方式)

作者: 晓晓_1931 | 来源:发表于2022-12-21 16:02 被阅读0次

    一、配置文件方式

    创建maven项目,打包方式为war
    pom.xml文件
    <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 
    https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.xx</groupId>
        <artifactId>ssm</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <properties>
            <spring.version>5.2.8.RELEASE</spring.version>
        </properties>
    
        <dependencies>
            <!-- 此依赖会关联引用Spring中的所有基础jar包 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- SpringMVC的jar包 (会依赖spring-web)-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- Spring支持jdbc的jar包(会依赖 spring-tx事务jar包) -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- aspectj依赖jar包 -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.7</version>
            </dependency>
            <!-- jackson依赖jar包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.0</version>
            </dependency>
            <!--mybatis 依赖包 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.1</version>
            </dependency>
            <!-- mybatis-spring 依赖包 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.0</version>
            </dependency>
            <!-- mysql驱动 依赖包 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.6</version>
            </dependency>
            <!-- servlet依赖包 监听器和过滤器用-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.0</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.3.1</version>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    1、实体类
    package com.xx.ssm.po;
    
    public class Dept {
        private Integer deptno;
        private String dname;
        private String loc;
        public Integer getDeptno() {
            return deptno;
        }
        public void setDeptno(Integer deptno) {
            this.deptno = deptno;
        }
        public String getDname() {
            return dname;
        }
        public void setDname(String dname) {
            this.dname = dname;
        }
        public String getLoc() {
            return loc;
        }
        public void setLoc(String loc) {
            this.loc = loc;
        }
        @Override
        public String toString() {
            return "Dept [deptno=" + deptno + ", dname=" + 
                      dname + ", loc=" + loc + "]";
        }
        
    }
    
    
    2、创建dao层接口
    package com.xx.ssm.mapper;
    import java.util.List; 
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Select; 
    import com.xx.ssm.po.Dept;
    
    @Mapper
    public interface DeptMapper {
        @Select("select * from dept where deptno = #{deptno}")
        public Dept getDeptById(Integer deptno);   //注解方式实现
        
        public List<Dept> getDept();               //映射文件方式实现
    }
    

    如果想写动态复杂sql,则也可使用映射文件
    DeptMapper.xml放在resources目录下的mapper文件夹下

    <?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.xx.ssm.mapper.DeptMapper">
        <select id="getDept" resultType="Dept">
            select * from dept  
        </select>
    </mapper>
    
    3、创建service层接口
    package com.xx.ssm.service;
    
    import java.util.List; 
    import com.xx.ssm.po.Dept;
    
    public interface DeptService {
        public Dept getDeptById(Integer deptno);
    
        public List<Dept> getDept( );
     
    }
    
    4、创建service层实现类
    package com.xx.ssm.service.impl;
    
    import java.util.List; 
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service; 
    import com.xx.ssm.mapper.DeptMapper;
    import com.xx.ssm.po.Dept;
    import com.xx.ssm.service.DeptService;
    
    @Service
    public class DeptServiceImpl implements DeptService{
        @Autowired
        private DeptMapper deptMapper;
        
        @Override
        public Dept getDeptById(Integer deptno) {
            return deptMapper.getDeptById(deptno);
        }
    
        @Override
        public List<Dept> getDept() { 
            return deptMapper.getDept();
        }
    }
    
    5、创建controller层控制器
    package com.xx.ssm.controller;
    
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.xx.ssm.po.Dept;
    import com.xx.ssm.service.DeptService;
    
    @Controller
    public class DeptController {
        @Autowired
        private DeptService deptService;
        
        @ResponseBody
        @RequestMapping("/getDeptById")
        public Dept getDeptById(Integer deptno) throws Exception{ 
            return deptService.getDeptById(deptno);
        }
        
        @ResponseBody
        @RequestMapping("/getDept")
        public List<Dept> getDept( ) throws Exception{ 
            return deptService.getDept( );
        }
    }
    
    6、web.xml
    <?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"
        version="2.5">
        <display-name>ssm</display-name> 
        <!-- Spring整合web项目用的ServletContext监听器 -->
        <listener>
            <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>
    
        <!-- 指定spring配置文件路径,默认加载 /WEB-INF/applicationContext.xml -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
        <!-- springmvc前端控制器配置 -->
        <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-servlet.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!-- 各种错误页 前后端分离的不用配-->
        <!--
        <error-page>
            <error-code>404</error-code>
            <location>/WEB-INF/views/error/404.jsp</location>
        </error-page>
        <error-page>
            <error-code>403</error-code>
            <location>/WEB-INF/views/error/403.jsp</location>
        </error-page>
        <error-page>
            <error-code>405</error-code>
            <location>/WEB-INF/views/error/405.jsp</location>
        </error-page>
        <error-page>
            <error-code>500</error-code>
            <location>/WEB-INF/views/error/500.jsp</location>
        </error-page>
        -->  
    </web-app>
    
    

    7、在resources目录下创建applicationContext.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: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/context 
                            http://www.springframework.org/schema/context/spring-context.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">
        <!-- 引入db配置文件 -->
        <context:property-placeholder
            location="classpath:db.properties" />
        <!-- 配置dataSource数据源 -->
        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driver}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>
        <!-- 创建SqlSessionFactory,并配置实体对象别名 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
            <property name="typeAliasesPackage" value="com.xx.ssm.po" />
        </bean>
        
        <!-- 配置Mapper。自动扫描Mapper接口,并为其注入SqlSessionFactory -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.xx.ssm.mapper"></property> 
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
        <!-- 配置Spring提供的事务管理器 -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- 开启注解事务 -->
        <tx:annotation-driven transaction-manager="transactionManager" />
        <!-- 注解扫描service层 -->
        <context:component-scan base-package="com.xx.ssm.service" />
    </beans>
    

    8、在resources目录下创建springmvc-servlet.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:aop="http://www.springframework.org/schema/aop"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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
                            http://www.springframework.org/schema/aop
                            http://www.springframework.org/schema/aop/spring-aop.xsd
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
        <!--  自动加载注解的处理器映射和注解的处理器适配  -->   
        <mvc:annotation-driven />
        <!-- 开启注解扫描,将包下带有@Controller注解的类纳入Spring容器中-->
        <context:component-scan base-package="com.xx.ssm.controller" />
    
     
    
        <!-- 可以配置多个拦截器 -->
        <!-- 
        <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**" />
                <mvc:exclude-mapping path="/login" />
                <bean class="com.xx.ssm.interceptor.IndexInterceptor" />
            </mvc:interceptor>
        </mvc:interceptors>
        -->      
    
        <!--配置的视图解析器对象 --> 
        <!-- 
        <bean id="internalResourceViewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>
        -->
    
        <!--过滤静态资源 -->
        <!--
        <mvc:resources location="/css/" mapping="/css/**" />
        <mvc:resources location="/images/" mapping="/images/**" />
        <mvc:resources location="/js/" mapping="/js/**" />
        <mvc:resources location="/views/" mapping="/views/**" />
         -->
    </beans>
     
    
    9、在resources目录下创建db.properties
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=root
    

    二、纯注解方式

    创建maven项目,打包方式为war
    pom.xml文件 、.java文件、*mapper.xml均不变,
    去掉 :

    applicationContext.xml
    springmvc-servlet.xml
    db.properties
    web.xml

    1、创建AppInitializer类
    package com.xx.ssm;
    import org.springframework.web.servlet.support.
    AbstractAnnotationConfigDispatcherServletInitializer;
    
    
    
    public class AppInitializer extends 
    AbstractAnnotationConfigDispatcherServletInitializer{
        /**
         * 返回一个带有@Configuration注解的类。
         * 用来创建整个应用程序的全局Spring容器。
         * 也就是等同于创建applicationContext.xml容器
         */
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[] {RootConfig.class};
        }
        /**
         * 返回一个带有@Configuration注解的类。
         * 用来创建SpringMVC(即Web相关)的Spring容器。
         * 也就是等同于创建springmvc-servlet.xml容器
         */
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class[] {WebConfig.class};
        }
        //配置SpringMVC前端控制器映射路径
        @Override
        protected String[] getServletMappings() {
            return new String[] {"/"};
        }
    }
    
    2、创建RootConfig类
     package com.xx.ssm;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List; 
    import javax.sql.DataSource; 
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.core.io.support.ResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    import org.springframework.jdbc.datasource.DriverManagerDataSource;
    import org.springframework.transaction.PlatformTransactionManager;
     
    @Configuration 
    @ComponentScan(basePackages={"com.xx.ssm.service"})//@ComponentScan用于扫描通用组件,这里用来扫描Service组件
    @MapperScan(basePackages="com.xx.ssm.mapper")//@MapperScan用于扫描Mapper组件 
    public class RootConfig {
        
        @Bean//创建dataSource组件并放入Spring容器
        public DataSource dataSource()  {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8");
            dataSource.setUsername("root");
            dataSource.setPassword("root");
            return dataSource;
        }  
        
        @Bean//创建SqlSessionFactory组件并放入Spring容器
        public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException{ 
          SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
          sqlSessionFactoryBean.setDataSource(dataSource());
          sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations());//参数调用下面方法,获取映射文件位置
          sqlSessionFactoryBean.setTypeAliasesPackage("com.xx.ssm.po");//定义实体类别名
          return sqlSessionFactoryBean;
        }    
        //复杂动态sql写在对应的映射文件里会方便,这个方法主要给上面的setMapperLocations()方法提供参数,找到对应映射文件位置用的
        public Resource[] resolveMapperLocations() throws IOException {
            ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
            List<String> mapperLocations = new ArrayList<String>();
            mapperLocations.add("classpath*:mapper/*.xml"); 
            List<Resource> resources = new ArrayList<Resource>();
            if (mapperLocations != null) {
                for (String mapperLocation : mapperLocations) { 
                        Resource[] mappers = resourceResolver.getResources(mapperLocation);
                        resources.addAll(Arrays.asList(mappers)); 
                }
            }
            return resources.toArray(new Resource[resources.size()]);
        } 
       
        @Bean //创建PlatformTransactionManager组件并放入Spring容器
        public PlatformTransactionManager transactionManager(DataSource dataSource){
            //dataSource也可以通过参数注入
            return  new DataSourceTransactionManager(dataSource());
        }
    }
    
    3、创建WebConfig类
    package com.xx.ssm;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
     
    @Configuration 
    @EnableWebMvc   //等同于<mvc:annotation-driven/>Controller组件        
    @ComponentScan(basePackages={"com.xx.ssm.controller"})
    //用于扫描通用组件,这里用来扫描Controller组件
    public class WebConfig{ }
    

    测试数据

    drop TABLE emp;
    drop TABLE dept;
    drop TABLE salgrade;
    create table dept
    (
    deptno integer(4) not null,
    dname varchar(14),
    loc varchar(13)
    );
    alter table dept add constraint pk_dept primary key (deptno);
    create table emp
    (
    empno integer(4) not null,
    ename varchar(10),
    job varchar(9),
    mgr integer(4),
    hiredate date,
    sal decimal(7,2),
    comm decimal(7,2),
    deptno integer(2)
    );
    alter table emp add constraint pk_emp primary key (empno);
    alter table emp add constraint fk_deptno foreign key (deptno) references dept (deptno);
    create table salgrade
    (
    grade integer(1),
    losal decimal(7,2),
    hisal decimal(7,2)
    );
    insert into DEPT (DEPTNO, DNAME, LOC) values (10, 'ACCOUNTING', 'NEW YORK');
    insert into DEPT (DEPTNO, DNAME, LOC) values (20, 'RESEARCH', 'DALLAS');
    insert into DEPT (DEPTNO, DNAME, LOC) values (30, 'SALES', 'CHICAGO');
    insert into DEPT (DEPTNO, DNAME, LOC) values (40, 'OPERATIONS', 'BOSTON');
    insert into SALGRADE (GRADE, LOSAL, HISAL) values (1, 700, 1200);
    insert into SALGRADE (GRADE, LOSAL, HISAL) values (2, 1201, 1400);
    insert into SALGRADE (GRADE, LOSAL, HISAL) values (3, 1401, 2000);
    insert into SALGRADE (GRADE, LOSAL, HISAL) values (4, 2001, 3000);
    insert into SALGRADE (GRADE, LOSAL, HISAL) values (5, 3001, 9999);
    -- 下面要特别注意,%d-%m-%Y 里的 d 和 m 一定要小写
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7369, 'SMITH', 'CLERK', 7902, STR_TO_DATE('17-12-1980', '%d-%m-%Y'), 800.00, null, 20);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7499, 'ALLEN', 'SALESMAN', 7698, STR_TO_DATE('20-02-1981', '%d-%m-%Y'), 1600.00, 300.00, 30);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7521, 'WARD', 'SALESMAN', 7698, STR_TO_DATE('22-02-1981', '%d-%m-%Y'), 1250.00, 500.00, 30);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7566, 'JONES', 'MANAGER', 7839, STR_TO_DATE('02-04-1981', '%d-%m-%Y'), 2975.00, null, 20);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7654, 'MARTIN', 'SALESMAN', 7698, STR_TO_DATE('28-09-1981', '%d-%m-%Y'), 1250.00, 1400.00, 30);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7698, 'BLAKE', 'MANAGER', 7839, STR_TO_DATE('01-05-1981', '%d-%m-%Y'), 2850.00, null, 30);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7782, 'CLARK', 'MANAGER', 7839, STR_TO_DATE('09-06-1981', '%d-%m-%Y'), 2450.00, null, 10);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7788, 'SCOTT', 'ANALYST', 7566, STR_TO_DATE('19-04-1987', '%d-%m-%Y'), 3000.00, null, 20);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7839, 'KING', 'PRESIDENT', null, STR_TO_DATE('17-11-1981', '%d-%m-%Y'), 5000.00, null, 10);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7844, 'TURNER', 'SALESMAN', 7698, STR_TO_DATE('08-09-1981', '%d-%m-%Y'), 1500.00, 0.00, 30);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7876, 'ADAMS', 'CLERK', 7788, STR_TO_DATE('23-05-1987', '%d-%m-%Y'), 1100.00, null, 20);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7900, 'JAMES', 'CLERK', 7698, STR_TO_DATE('03-12-1981', '%d-%m-%Y'), 950.00, null, 30);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7902, 'FORD', 'ANALYST', 7566, STR_TO_DATE('03-12-1981', '%d-%m-%Y'), 3000.00, null, 20);
    insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    values (7934, 'MILLER', 'CLERK', 7782, STR_TO_DATE('23-01-1982', '%d-%m-%Y'), 1300.00, null, 10);
    

    相关文章

      网友评论

          本文标题:ssm框架整合(配置文件方式 和 纯注解方式)

          本文链接:https://www.haomeiwen.com/subject/ddkmqdtx.html