• 科猫网项目总结(基于SSM框架)


    1.配置文件的添加
    SSM整合需要web.xml配置文件,springmvc的配置文件,spring和mybatis整合的配置文件。
    1.web.xml文件的配置
    1.在WEB-INF下新建web.xml
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
     
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    上面控制springmvc的servlet,下面控制哪些文件会走springmvc
    <servlet-name>标签的取名影响到XXX-servlet.xml文件的命名 
     
    2.在web.xml中新增Listener标签
       
     <listener>
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         </listener>
    ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext( 可以用来获取Spring容器中已初始化的bean)的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
    如果要对spring的配置文件位置,名称进行指定(框架中的配置文件都可以对名称位置进行指定,springmvc则是在web.xml中添加<init-param>),可以添加:
      
     <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext.xml</param-value>
        </context-param>
    classpath:spring/applicationContext.xml也可以简化为/WEB-INF/applicationContext.xml
    当我们不对位置进行配置,则默认位置为WEB-INF,文件名称为:applicationContext.xml(其作用是spring和mybatis的整合)
     
    3.其他的标签
    <servlet-mapping>
         <servlet-name>springmvc</servlet-name>    需要与上面名称相对应
         <url-pattern>*.action</url-pattern>    哪些路径要走springmvc
    </servlet-mapping>
     
    <welcome-file-list>
         <welcome-file>index.jsp</welcome-file>    指定起始页
    </welcome-file-list>
    2.spring-servlet.xml文件的配置
    spring-servlet.xml也就是springmvc的配置文件
    <?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:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
     
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <!-- 使用注释方式 -->
         <mvc:annotation-driven/>
    <!-- 自动扫描Controller-->
         <context:component-scan base-package="controller"/>
    <!-- 配置一个springMVC视图解析器 -->
         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
             <property name="prefix" value= ""/>
             <property name="suffix" value= ".jsp"/>
         </bean>
    <!-- 返回json的处理 -->
         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
             <property name="messageConverters">
                 <list>
                     <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                         <property name="supportedMediaTypes">
                             <list>
                                 <value>text/html; charset=UTF-8</value>
                                 <value>application/json;charset=UTF-8</value>
                             </list>
                         </property>
                     </bean>
                     <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                         <property name="supportedMediaTypes">
                             <list>
                                 <value>text/html; charset=UTF-8</value>
                                 <value>application/json;charset=UTF-8</value>
                             </list>
                         </property>
                     </bean>
                 </list>
             </property>
         </bean>
    </beans>
    使用springMVC有xml配置与注解配置,这里用注解配置
     
    1.引入mvc和context的命名空间
    mvc:
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
    context:
    xmlns:context="http://www.springframework.org/schema/context" 
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.xsd
     
    2.设置注解驱动
    <mvc:annotation-driven/>
     
    3.自动实例化路径(需要改动)
     
    <context:component-scan base-package="controller"/>
     
       在xml配置了这个标签后spring可以自动去扫描base-pack下面或者子包下面的Java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean
    只要添加@Controller,spring会为里面的类创建实例
    @Controller 标注 web 控制器, @Service 标注 Service 层的服务, @Respository 标注 DAO层的数据访问。 @Component 是通用标注,只是定义为一个类为 Bean , SpringMVC 会把所有添加 @Component 注解的类作为使用自动扫描注入配置路径下的备选对象。 @Controller 、 @Service@Respository 只是更加的细化
     
    3.applicationContext.xml文件的配置
     
    applicationContext.xml也就是spring和mybatis整合的配置文件
    <?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"
        xmlns:aop="http://www.springframework.org/schema/aop"
        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-4.1.xsd
              http://www.springframework.org/schema/tx
              http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
              http://www.springframework.org/schema/aop
              http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
     
              <context:component-scan base-package="dao"/>
              <context:property-placeholder location="classpath:db.properties" />
     
             <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
                 <!-- 初始化连接数量; -->
                 <property name="initialSize" value="0" />
                 <!-- 最大并发连接数   -->
                 <property name="maxActive" value="20" />
     
                 <!-- 最大空闲连接数 -->
                 <property name="maxIdle" value="20" />
                 <!-- 最小空闲连接数 -->
                 <property name="minIdle" value="0" />
                 <!-- 最大等待时长 -->
                 <property name="maxWait" value="60000" />
                 <!-- 超过时间限制是否回收 -->
                 <property name="removeAbandoned" value="true" />
                 <!-- 超过时间限制多长; -->
                 <property name="removeAbandonedTimeout" value="180"/>
     
     
                 <!-- 数据源连接参数配置; -->
                 <property name="username" value="${db.username}"/>
                 <property name="url" value="${db.url}"/>
                 <property name="password" value="${db.password}"/>
                 <property name="driverClassName" value="${db.driver}"/>
     
             </bean>
     
    <!-- 配置SessionFactory -->
         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
               <property name="dataSource" ref="dataSource"/>
    <!-- <property name="mapperLocations" value="classpath:mapper/*.xml" /> -->
               <property name="mapperLocations">
                 <list>
                     <value>classpath:config/*.xml</value>
                 </list>
               </property>
         </bean>
     
    <!-- 自动扫描mapper接口,注入sqlSessionFactory -->
         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
             <property name="basePackage" value="mapper"/>
         </bean>
     
    <!-- 配置事务管理器 -->
         <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"/>
         </bean>
     
    <!-- <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/> -->
    <!-- 定义切面 -->
         <aop:config>
         <aop:pointcut expression="execution(* dao.*.* (..))" id="txPointCut"/>
         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
         </aop:config>
     
    <!-- 声明式事务 -->
         <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <tx:attributes>
               <tx:method name="isValid" propagation="REQUIRED" read-only="true"/>
               <tx:method name="add" propagation="REQUIRED" read-only="true"/>
         </tx:attributes>
         </tx:advice>
     
    </beans>
    1.自动实例化对象包的指定(需要改动)
    <!-- 开启自动初始化标签:添加Component就可以自动将类初始化 -->
         <context:component-scan base-package="dao"></context:component-scan>
    为dao的类前面添加注解:
    @Component
    表示自动创建实例,而controller的类也是需要自动创建实例的,但是其由springMVC来完成了(添加了@Controller)
    2.数据库信息文件的指定
    <context:property-placeholder location="classpath:db.properties" />
    表示在src目录下的db.properties文件(需要改动)
    3.数据源dataSource使用dbcp
    4.配置SessionFactory
    <!-- 配置SessionFactory -->
         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
               <property name="dataSource" ref="dataSource"/>
    <!-- <property name="mapperLocations" value="classpath:mapper/*.xml" /> -->
               <property name="mapperLocations">
                 <list>
                     <value>classpath:config/*.xml</value>
                 </list>
               </property>
         </bean>
    id是固定的,一定不能写错(要修改很麻烦)
    Mybatis和spring的整合需要添加 SSM整合完整Jar包”(将在文章末尾提供下载链接)
    dataSource连数据库需要:
    1.dataSource要和前面的标签对得上
    2.映射文件的位置,所以指定config/*.xml
    这里把接口放在名为mapper的包中,而映射文件放在config包中
     
    5.指定接口的位置
    <!-- 自动扫描mapper接口,注入sqlSessionFactory -->
         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
             <property name="basePackage" value="mapper"/>
         </bean>
    指定接口的标签也会默认找sqlSessionFactory,如果上面修改过,这里就得进行处理
     
    6.添加事务管理器&切面&事务
    <!-- 配置事务管理器 -->
         <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"/>
         </bean>
     
    <!-- <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/> -->
    <!-- 定义切面 -->
         <aop:config>
         <aop:pointcut expression="execution(* dao.*.* (..))" id="txPointCut"/>
         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
         </aop:config>
     
    <!-- 声明式事务 -->
         <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <tx:attributes>
               <tx:method name="isValid" propagation="REQUIRED" read-only="true"/>
               <tx:method name="add" propagation="REQUIRED" read-only="true"/>
         </tx:attributes>
         </tx:advice>
    attributes标签中用REQUIRED,表示运行到isValid方法的时候有事务就运行事务,没事务就创建事务。
    4.mybatis-cfg.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>
     
        <properties resource="db.properties"></properties>
        <!-- 对事务的管理和连接池的配置 -->
     
        <environments default="development">
     
            <environment id="kcat">
     
                <transactionManager type="JDBC" />     事务管理器的类型
       
                <dataSource type="POOLED">              连接池的方式
     
                    <property name="driver" value="${db.driver}" />
     
                    <property name="url" value="${db.url}" />
     
                    <property name="username" value="${db.username}" />
     
                    <property name="password" value="${db.password}" />
     
                </dataSource>
     
            </environment>
     
        </environments>
     
        <!-- mapping 文件路径配置 -->
     
        <mappers>
     
              <!--<mapper resource="javastudy/userMapper.xml"/> -->
              <!-- <mapper class="javastudy.CourseMapper"/> -->
              <mapper class="mapper.BangMapper"/>
     
        </mappers>
     
    </configuration>
    environments(环境)标签的default可以自己命名
    environment(一个环境连一个数据库)标签的id相当于自己起名字,后面会用到,这里用kcat
     
    2.注解的使用
    到这里就整合完了SSM环境,下面就要使用注解
    因为applicationContext.xml已经对dao包进行了扫描,所以只要添加注解就可以自动生成实例化对象。
     
    有了dao,那么在controller中就可以进行注入
     
    控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。
    拥有与@Resource注解所提供名字相匹配的“bean name(bean名字)”的Spring管理对象会被注入
    @responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML
    3.SSM的MVC目录结构
    1.config包
    config包放置的为映射文件
    <?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="mapper.BangMapper">
         <select id="get"  resultType="model.Bang">
              select * from bang
         </select>
    </mapper>
    name space是用于绑定Dao接口的,即面向接口编程
    resultType返回类型
    下面编写查询用的sql语句
     
    2.controller包
    MVC的核心就是Controller(控制器),它负责处理浏览器传送过来的所有请求,并决定要将什么内容响应给浏览器。但Controller并不负责决定内容应该如何显示,而是将特定形态的内容响应给MVC架构,最后才由MVC架构依据响应的形态来决定如何将内容响应给浏览器。如何决定响应内容是View的责任。
    package controller;
     
    import java.io.IOException;
    import java.util.ArrayList;
     
    import javax.annotation.Resource;
     
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ResponseBody;
     
    import dao.BangDAO;
    import model.Bang;
     
    @Controller
    public class BangController {
        BangDAO dao;
     
        public BangDAO getDao() {
            return dao;
        }
        @Resource
        public void setDao(BangDAO dao) {
            this.dao = dao;
        }
     
        @ResponseBody
        public ArrayList<Bang> get() throws IOException{
            ArrayList<Bang> list=dao.get();
            return list;
        }
     
    }
     
    3.dao包
    一般程序都是用模型层与数据库进行交互,而dao层则用于程序对数据库的操作,所以认为dao层属于模型层。
    也有这样的看法,把dao层看做MVC框架之外的单独的一层,称之为数据持久层
     
    package dao;
     
    import java.util.ArrayList;
     
    import javax.annotation.Resource;
     
    import org.springframework.stereotype.Component;
     
    import mapper.BangMapper;
    import model.Bang;
     
    @Component
    public class BangDAO {
        BangMapper bangMapper;
     
        public BangMapper getBangMapper() {
            return bangMapper;
        }
        @Resource
        public void setBangMapper(BangMapper bangMapper) {
            this.bangMapper = bangMapper;
        }
        public ArrayList<Bang> get(){
            ArrayList<Bang> list=bangMapper.get();
            return list;
        }
    }
     
    4.mapper包
    mapper包用来放置DAO接口
    package mapper;
     
    import java.util.ArrayList;
     
    import model.Bang;
     
    public interface BangMapper {
        public ArrayList<Bang> get();
    }
    5.model包
    放置模型类,可以看做表
    package model;
     
    public class Bang {
         private int id;
         private String videoName;
         private int videoType;
         private String videoUrl;
         private String videoImage;
         private String videoExplain;
         public int getId() {
              return id;
         }
         public void setId(int id) {
              this.id = id;
         }
         public String getVideoName() {
              return videoName;
         }
         public void setVideoName(String videoName) {
              this.videoName = videoName;
         }
         public int getVideoType() {
              return videoType;
         }
         public void setVideoType(int videoType) {
              this.videoType = videoType;
         }
         public String getVideoUrl() {
              return videoUrl;
         }
         public void setVideoUrl(String videoUrl) {
              this.videoUrl = videoUrl;
         }
         public String getVideoImage() {
              return videoImage;
         }
         public void setVideoImage(String videoImage) {
              this.videoImage = videoImage;
         }
         public String getVideoExplain() {
              return videoExplain;
         }
         public void setVideoExplain(String videoExplain) {
              this.videoExplain = videoExplain;
         }
         @Override
         public String toString() {
              return "Bang [id=" + id + ", videoName=" + videoName + ", videoType=" + videoType + ", videoUrl=" + videoUrl
                       + ", videoImage=" + videoImage + ", videoExplain=" + videoExplain + "]";
         }
     
    }
    6.utility包
    MybatisUtils作为工具类读取配置文件 
    package utility;
     
    import java.io.IOException;
    import java.io.InputStream;
     
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
     
    public class MyBatisUtils {
        public static SqlSession openSession() throws IOException
        {
                String resource = "mybatis-cfg.xml";
                InputStream in = Resources.getResourceAsStream(resource);
                SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in,"kcat");  //这里要对应mybatis-cfg.xml的environment id
                return sessionFactory.openSession();
        }
    }
     
    SqlSessionFactoryBuilder().build(in,"kcat");后面的id位置要对应mybatis-cfg.xml的environment标签的id
     

    =========================================
    附件下载地址:
    SSM整合完整Jar包:链接:http://pan.baidu.com/s/1eSOfWmY  (10M)
  • 相关阅读:
    练习1-17 编写一个程序,打印长度大于80个字符的所有输入行.
    练习1-16 修改打印最长文本行的程序的主程序main, 使之可以打印任意长度的输入行的长度, 并尽可能多的打印文本。
    惠普Z620工作站用安装版装win7旗舰版64位结果找不到硬盘
    输入元素( Input Element)
    GradientStop
    qml关键字style
    opacity
    QT5-step-by-step-LayoutManagement
    QT5-step-by-step-BasicKnowledge
    Adeneo Embedded: Building Qt 5.1 for Freescale i.MX6Introduction on LTIB
  • 原文地址:https://www.cnblogs.com/pengjunhao/p/7193770.html
Copyright © 2020-2023  润新知