zoukankan      html  css  js  c++  java
  • 在maven下使用SSM框架整合详解

    1.创建maven-archetype-webapp项目。

     

    2.创建目录

     目录讲解之文件名:

    src/main/java  存放我们的java代码

    src/main/resources  存放资源文件,譬如各种的spring,mybatis,log配置文件

    src/test/java  测试java代码

    src/test/resources  没什么好说的,很少用到,是maven的规范

    src/main/resources/spring  存放spring相关配置文件

    src/main/resources/mapper  存放dao接口配置文件,如mapper.xml

     目录讲解之包名:

    dao  数据访问层,与数据库打交道,可以是数据库操作、文件读写操作、redis缓存操作等

    entity  实体类,一般与数据库的表相对应,封装dao层取出来的数据为一个对象,也常用pojo,一般只在dao层与service层之间传输。

    dto  数据传输层,用于service层与web层之间传输,在实际开发中,entity并不能满足业务需求,这时候就有了dto、vo,对数据进行封装

    service  业务逻辑(接口),写我们的业务逻辑

    serviceImpl   业务逻辑(实现),实现我们业务接口,一般事务控制是写在这里

    web  控制器,springmvc就是在这里发挥作用的,一般人叫做controller控制器,相当于struts中的action

    enums  枚举类

    interceptor  拦截器

    3.引入jar包和插件,在pom.xml中加入如下配置

      1     <!-- spring版本 -->
      2     <properties>
      3         <spring.version>4.3.7.RELEASE</spring.version>
      4     </properties>
      5     <dependencies>
      6         <dependency>
      7             <groupId>junit</groupId>
      8             <artifactId>junit</artifactId>
      9             <version>4.12</version>
     10             <scope>test</scope>
     11         </dependency>
     12         <!-- 日志包 -->
     13         <dependency>
     14             <groupId>ch.qos.logback</groupId>
     15             <artifactId>logback-classic</artifactId>
     16             <version>1.2.3</version>
     17         </dependency>
     18         <!-- 1.Spring -->
     19         <!-- 1)Spring核心 -->
     20         <dependency>
     21             <groupId>org.springframework</groupId>
     22             <artifactId>spring-core</artifactId>
     23             <version>${spring.version}</version>
     24         </dependency>
     25         <dependency>
     26             <groupId>org.springframework</groupId>
     27             <artifactId>spring-beans</artifactId>
     28             <version>${spring.version}</version>
     29         </dependency>
     30         <dependency>
     31             <groupId>org.springframework</groupId>
     32             <artifactId>spring-context</artifactId>
     33             <version>${spring.version}</version>
     34         </dependency>
     35         <!-- 2)Spring DAO层 -->
     36         <dependency>
     37             <groupId>org.springframework</groupId>
     38             <artifactId>spring-jdbc</artifactId>
     39             <version>${spring.version}</version>
     40         </dependency>
     41         <dependency>
     42             <groupId>org.springframework</groupId>
     43             <artifactId>spring-tx</artifactId>
     44             <version>${spring.version}</version>
     45         </dependency>
     46         <!-- 3)Spring web -->
     47         <dependency>
     48             <groupId>org.springframework</groupId>
     49             <artifactId>spring-web</artifactId>
     50             <version>${spring.version}</version>
     51         </dependency>
     52         <dependency>
     53             <groupId>org.springframework</groupId>
     54             <artifactId>spring-webmvc</artifactId>
     55             <version>${spring.version}</version>
     56         </dependency>
     57         <!-- 4)Spring test -->
     58         <dependency>
     59             <groupId>org.springframework</groupId>
     60             <artifactId>spring-test</artifactId>
     61             <version>${spring.version}</version>
     62         </dependency>
     63         <!-- spring依赖包 -->
     64         <dependency>
     65             <groupId>com.fasterxml.jackson.core</groupId>
     66             <artifactId>jackson-databind</artifactId>
     67             <version>2.8.7</version>
     68         </dependency>
     69         <dependency>
     70             <groupId>javax.servlet</groupId>
     71             <artifactId>javax.servlet-api</artifactId>
     72             <version>3.1.0</version>
     73         </dependency>
     74         <!-- Map工具类 -->
     75         <dependency>
     76             <groupId>commons-collections</groupId>
     77             <artifactId>commons-collections</artifactId>
     78             <version>3.2</version>
     79         </dependency>
     80         <!-- 2.数据库 -->
     81         <dependency>
     82             <groupId>mysql</groupId>
     83             <artifactId>mysql-connector-java</artifactId>
     84             <version>8.0.11</version>
     85             <scope>runtime</scope>
     86         </dependency>
     87         <dependency>
     88             <groupId>c3p0</groupId>
     89             <artifactId>c3p0</artifactId>
     90             <version>0.9.1.2</version>
     91         </dependency>
     92         <!-- DAO: MyBatis -->
     93         <dependency>
     94             <groupId>org.mybatis</groupId>
     95             <artifactId>mybatis</artifactId>
     96             <version>3.4.2</version>
     97         </dependency>
     98         <dependency>
     99             <groupId>org.mybatis</groupId>
    100             <artifactId>mybatis-spring</artifactId>
    101             <version>1.3.1</version>
    102         </dependency>    
    103     </dependencies>
    104     <build>
    105         <finalName>o2o</finalName>
    106         <plugins>
    107             <plugin>
    108                 <groupId>org.apache.maven.plugins</groupId>
    109                 <artifactId>maven-compiler-plugin</artifactId>
    110                 <version>3.8.1</version>
    111                 <configuration>
    112                     <source>1.8</source>
    113                     <target>1.8</target>
    114                 </configuration>
    115             </plugin>
    116         </plugins>
    117     </build>

    4.创建实体对象

    Area:

    import java.util.Date;
    
    public class Area {
    
        private Integer areaId;
        private String areaName;
        private Integer priority;
        private Date createTime;
        private Date lastEditTime;
        //getter和setter方法省略
    }

    数据库建表插入数据:

    DROP TABLE IF EXISTS `tb_area`;
    CREATE TABLE `tb_area` (
      `area_id` int(2) NOT NULL AUTO_INCREMENT,
      `area_name` varchar(200) NOT NULL,
      `priority` int(2) NOT NULL DEFAULT '0',
      `create_time` datetime DEFAULT NULL,
      `last_edit_time` datetime DEFAULT NULL,
      PRIMARY KEY (`area_id`),
      UNIQUE KEY `UK_AREA` (`area_name`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

    insert into tb_area(area_name,priority) value("东苑",2),("西苑",1);

    5.写配置文件

    jdbc.properties:

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/o2o?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    jdbc.username=root
    jdbc.password=root

    MyBaties-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!-- 配置全局属性 -->
        <settings>
            <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
            <setting name="useGeneratedKeys" value="true" />
            <!-- 使用列标签替换列名 默认:true -->
            <setting name="useColumnLabel" value="true" />
            <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
            <setting name="mapUnderscoreToCamelCase" value="true" />
            <!-- 打印查询语句 -->
            <setting name="logImpl" value="STDOUT_LOGGING" />
        </settings>
    </configuration>

     spring-dao.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        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">
        <!-- 配置整合mybatis过程 -->
        <!-- 1.配置数据库相关参数properties的属性:${url} -->
        <context:property-placeholder location="classpath:jdbc.properties"/>
        <!-- 2.数据库连接池 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <!-- 配置连接池属性 -->
            <property name="driverClass" value="${jdbc.driver}" />
            <property name="jdbcUrl" value="${jdbc.url}" />
            <property name="user" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
    
            <!-- c3p0连接池的私有属性 -->
            <property name="maxPoolSize" value="30" />
            <property name="minPoolSize" value="10" />
            <!-- 关闭连接后不自动commit -->
            <property name="autoCommitOnClose" value="false" />
            <!-- 获取连接超时时间 -->
            <property name="checkoutTimeout" value="10000" />
            <!-- 当获取连接失败重试次数 -->
            <property name="acquireRetryAttempts" value="2" />
        </bean>
    
        <!-- 3.配置SqlSessionFactory对象 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource" />
            <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
            <property name="configLocation" value="classpath:mybatis-config.xml" />
            <!-- 扫描entity包 使用别名 -->
            <property name="typeAliasesPackage" value="com.zhang.o2o.entity" />
            <!-- 扫描sql配置文件:mapper需要的xml文件 -->
            <property name="mapperLocations" value="classpath:mapper/*.xml" />
        </bean>
    
        <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 注入sqlSessionFactory -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
            <!-- 给出需要扫描Dao接口包 -->
            <property name="basePackage" value="com.zhang.o2o.dao" />
        </bean>
    </beans>

    spring-service.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        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">
        <!-- 扫描service包下所有使用注解的类型 -->
        <context:component-scan base-package="com.zhang.o2o.service" />
    
        <!-- 配置事务管理器 -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!-- 配置基于注解的声明式事务 -->
        <tx:annotation-driven transaction-manager="transactionManager" />
    </beans>

    spring-web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns: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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
        <!-- 配置SpringMVC -->
        <!-- 1.开启SpringMVC注解模式 -->
        <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 
            (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 -->
        <mvc:annotation-driven />
    
        <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 -->
        <mvc:resources mapping="/resources/**"
            location="/resources/" />
        <mvc:default-servlet-handler />
    
        <!-- 3.定义视图解析器 -->
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/html/"></property>
            <property name="suffix" value=".html"></property>
        </bean>
        <!-- 4.扫描web相关的bean -->
        <context:component-scan
            base-package="com.zhang.o2o.web" />
    </beans>

     web.xml

    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                          http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1" metadata-complete="true">
        <display-name>Archetype Created Web Application</display-name>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
        <servlet>
            <servlet-name>spring-dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring/spring-*.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring-dispatcher</servlet-name>
            <!-- 默认匹配所以的请求 -->
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>

    6.写代码

    AreaDao.java

    package com.zhang.o2o.dao;
    
    import java.util.List;
    
    import com.zhang.o2o.entity.Area;
    
    public interface AreaDao {
        /**
         * 查询列表
         * @return areaList
         */
        List<Area> queryArea();
    
    }

    AreaService.java

    package com.zhang.o2o.service;
    
    import java.util.List;
    
    import com.zhang.o2o.entity.Area;
    
    public interface AreaService {
    
        List<Area> getAreaList();
    }

    AreaServiceImpl.java

    package com.zhang.o2o.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.zhang.o2o.dao.AreaDao;
    import com.zhang.o2o.entity.Area;
    import com.zhang.o2o.service.AreaService;
    
    @Service
    public class AreaServiceImpl implements AreaService {
    
        @Autowired
        private AreaDao areaDao;
    
        @Override
        public List<Area> getAreaList() {
            return areaDao.queryArea();
        }
    }

    AreaController.java

    package com.zhang.o2o.web.superadmin;
    
    import java.util.ArrayList;
    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.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.zhang.o2o.entity.Area;
    import com.zhang.o2o.service.AreaService;
    
    @Controller
    @RequestMapping("/superadmin")
    public class AreaController {
        @Autowired
        private AreaService areaService;
    
        @RequestMapping(value = "/listarea", method = RequestMethod.GET)
        @ResponseBody
        private Map<String, Object> listArea() {
            Map<String, Object> modelMap = new HashMap<String, Object>();
            List<Area> list = new ArrayList<Area>();
            try {
                list = areaService.getAreaList();
                modelMap.put("rows", list);
                modelMap.put("total", list.size());
    
            } catch (Exception e) {
                e.printStackTrace();
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
            }
            return modelMap;
        }
    
    }

    7.启动tomcat,运行项目,在浏览器上访问:http://localhost:8080/o2o/superadmin/listarea

  • 相关阅读:
    模型分离(选做)
    密码保护
    实现搜索功能
    完成个人中心—导航标签
    个人中心标签页导航
    评论列表显示及排序,个人中心显示
    完成评论功能
    从首页问答标题到问答详情页
    运行Junit单测时遇到的问题
    spring定时任务执行两次的原因与解决方法
  • 原文地址:https://www.cnblogs.com/e-x-c-e-ption/p/11949252.html
Copyright © 2011-2022 走看看