一、视频架构模式
- 自建模式(自己去搭建视频云服务器。因为占服务器的宽带,所以传统服务器不能做视频服务器,需要自己搭建视频服务器):
需要跟电信运营商拉专线,还要配置CDN(加速用,就是内容分发,大型网站的高并发解决方案的一个理念)、防盗链、缓存、提供给移动APP的接口(SDK)等,所以一般都是使用第三方视频接口,它们拥有成熟的视频解决方案, 解决拉专线和配置的问题。
PS:内容分发:其实就是将多台服务器部署在不同地区,就近进行访问。 - 第三方模式:
使用第三方云视频接口:阿里云、保利云(8毛)、乐视云(4毛G)。
二、SSM项目整合
- 分布式与分模块开发的区别?
分布式:一个项目拆分不同的项目进行部署开发,通过http协议进行通讯–微服务。
分模块开发:一个项目拆分成了子工程、父工程,通过jar包进行通讯。 - 整合思路:
- 引入jar包。
- Spring整合SpringMVC, 建立springmcv核心加载配置文件,配置包路径扫描、视图转发器、转换json格式、上传图片等,并在web.xml中加载springmvc.xml。
- Spring整合Mybatis,建立spring其它配置文件,配置包扫描、数据源等。
- 分模块开发,SSM环境搭建:
- 创建maven工程的父子依赖关系:
videowebsite-parent–父工程,打包方式pom,管理jar包的版本号,项目中所有工程都应该继承父工程。
videowebsite-commons–通用的工具类通用的pojo,打包方式jar。
videowebsite-dao–数据库访问层(持久化层),打包方式jar。
videowebsite-service–服务层,打包方式jar。
videowebsite-entity–实体类,打包方式jar。
videowebsite-web–表现层工程,打包方式war。 - 在videowebsite-parent父工程中为pom.xml添加maven依赖:
<!-- 集中定义依赖版本号 --> <properties> <junit.version>4.12</junit.version> <spring.version>5.1.6.RELEASE</spring.version> <mybatis.version>3.5.1</mybatis.version> <mybatis.spring.version>2.0.1</mybatis.spring.version> <mybatis.paginator.version>1.2.17</mybatis.paginator.version> <mysql.version>8.0.15</mysql.version> <slf4j.version>1.7.26</slf4j.version> <jackson.version>2.9.8</jackson.version> <druid.version>1.1.16</druid.version> <httpclient.version>4.5.8</httpclient.version> <jstl.version>1.2</jstl.version> <servlet-api.version>3.0-alpha-1</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <joda-time.version>2.10.1</joda-time.version> <commons-lang3.version>3.9</commons-lang3.version> <commons-io.version>2.6</commons-io.version> <commons-net.version>3.6</commons-net.version> <pagehelper.version>5.1.8</pagehelper.version> <jsqlparser.version>0.9.1</jsqlparser.version> <commons-fileupload.version>1.4</commons-fileupload.version> <jedis.version>3.1.0-m1</jedis.version> <solrj.version>4.10.3</solrj.version> </properties> <dependencyManagement> <dependencies> <!-- 时间操作组件 --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${joda-time.version}</version> </dependency> <!-- Apache工具组件 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>${commons-net.version}</version> </dependency> <!-- Jackson Json处理工具包 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 日志处理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <dependency> <groupId>com.github.miemiedev</groupId> <artifactId>mybatis-paginator</artifactId> <version>${mybatis.paginator.version}</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!-- JSP相关 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <!-- 文件上传组件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!-- Redis客户端 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <finalName>${project.artifactId}</finalName> <plugins> <!-- 资源文件拷贝插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- java编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> <pluginManagement> <plugins> <!-- 配置Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </pluginManagement> </build>
- Spring整合SpringMVC:
SpringMVC的执行流程:
SpringMVC的核心是DispatcherServlet类(通过这个类可知SpringMVC的底层就是servlet),任何请求都会先交给DispatcherServlet进行转发,转发后再分发到某一个请求中去,再拿到转换视图器到某一个页面。- 在表现层videowebsite-web工程中为pom.xml引入maven依赖:
<dependencies> <dependency> <groupId>chauncy</groupId> <artifactId>videowebsite-service</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- JSP相关 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <scope>provided</scope> </dependency> <!-- 文件上传组件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency> <!-- springwebmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>chauncy</groupId> <artifactId>videowebsite-entity</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.jr</groupId> <artifactId>jackson-jr-all</artifactId> <version>2.9.8</version> </dependency> </dependencies>
- 新增springmvc.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:p="http://www.springframework.org/schema/p" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- springmvc 扫包范围 --> <context:component-scan base-package="chauncy.controller" /> <!-- 开启springmvc注解 --> <mvc:annotation-driven /> <!-- 视图跳转类型 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
- web.xml加载SpringMVC配置文件:
<!-- 解决post乱码 --> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- springmvc的前端控制器 --> <servlet> <servlet-name>videowebsite-web</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>videowebsite-web</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
- 在表现层videowebsite-web工程中为pom.xml引入maven依赖:
- Spring整合Mybatis:
- 创建视频类型、视频详情表:
--视频类型表 CREATE TABLE `video_type` ( `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT COMMENT '主键(自增长)', `type_name` varchar(30) DEFAULT NULL COMMENT '视频类型' ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; --视频详情表 CREATE TABLE `video_info` ( `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT COMMENT '主键(自增长)', `video_name` varchar(150) DEFAULT NULL COMMENT '视频名称', `video_url` varchar(100) DEFAULT NULL COMMENT '封面图片', `video_html` varchar(500) DEFAULT NULL COMMENT '视频html执行元素', `video_type_id` int DEFAULT NULL COMMENT '关联typeID', `video_del` INT DEFAULT 0 COMMENT '是否显示 0显示 1隐藏' ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
- 在持久化层videowebsite-dao工程中为pom.xml引入maven依赖:
<!-- 依赖管理 --> <dependencies> <dependency> <groupId>chauncy</groupId> <artifactId>videowebsite-entity</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <dependency> <groupId>com.github.miemiedev</groupId> <artifactId>mybatis-paginator</artifactId> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> </dependency> <!-- MySql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> </dependencies> <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 --> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
- 在服务层videowebsite-service工程中为pom.xml引入maven依赖:
<dependencies> <dependency> <groupId>chauncy</groupId> <artifactId>videowebsite-dao</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <!-- 日志处理 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> </dependencies>
- 在表现层videowebsite-web工程中新增applicationContext-service.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 开启spring注解扫描范围,扫描service包下注解 --> <context:component-scan base-package="chauncy.service"></context:component-scan> </beans>
- 在表现层videowebsite-web工程中新增db.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.host=localhost jdbc.database=architect jdbc.userName=root jdbc.passWord=root jdbc.initialSize=0 jdbc.maxActive=20 jdbc.maxIdle=20 jdbc.minIdle=1 jdbc.maxWait=1000
- 在表现层videowebsite-web工程中新增applicationContext-dao.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 数据库连接池 --> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:properties/*.properties" /> <!-- 数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="jdbc:mysql://${jdbc.host}:3306/${jdbc.database}?serverTimezone=GMT&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull" /> <property name="username" value="${jdbc.userName}" /> <property name="password" value="${jdbc.passWord}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${jdbc.initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${jdbc.maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${jdbc.maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${jdbc.minIdle}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mappings/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="chauncy.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> </beans>
- 在表现层videowebsite-web工程中新增applicationContext-dao.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事务增强 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- name:标识哪些方法需要被被事务增强,propagation:配置事务传播行为,read-only:配置是否只是读操作 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- Aop配置: 拦截哪些方法(切入点表表达式) + 应用上面的事务增强配置 --> <aop:config> <!-- <aop:pointcut expression="execution(* chauncy.service.*.*(..))" id="pt" /> --> <aop:advisor advice-ref="txAdvice" pointcut="execution(* chauncy.service.*.*(..))" /> </aop:config> </beans>
- 使用Mybatis逆向工程生成器生成数据ORM映射文件,并放置到项目中。
- 实现查询所有视频类型:
package chauncy.controller; import java.util.List; 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.ResponseBody; import chauncy.entity.VideoType; import chauncy.service.VideoTypeServive; @Controller @RequestMapping("/VideoTypeController") public class VideoTypeController { private static final String TEST="test"; @Autowired private VideoTypeServive videoTypeService; @RequestMapping("/hello") public String hello(){ return TEST; } /** * @methodDesc: 功能描述(提供一个返回json格式的查询所有VideoType) * @author: ChauncyWang * @param: @return * @returnType: List<VideoType> */ @RequestMapping("/getVideoTypeList") @ResponseBody public List<VideoType> getVideoTypeList(){ List<VideoType> videoTypes = videoTypeService.getVideoTypes(null); for (VideoType videoType : videoTypes) { System.out.println(videoType.toString()); } return videoTypes; } }
package chauncy.service; import java.util.List; import chauncy.entity.VideoType; public interface VideoTypeServive { /** * @methodDesc: 功能描述(查询所有的视频类型) * @author: ChauncyWang * @param: @return * @returnType: List<VideoType> */ public List<VideoType> getVideoTypes(VideoType videoType); }
package chauncy.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import chauncy.dao.VideoTypeMapper; import chauncy.entity.VideoType; import chauncy.service.VideoTypeServive; @Service public class VideoTypeServiceImpl implements VideoTypeServive { @Autowired private VideoTypeMapper videoTypeMapper; @Override public List<VideoType> getVideoTypes(VideoType videoType) { return videoTypeMapper.selectList(videoType); } }
package chauncy.dao; import java.util.List; import chauncy.entity.VideoType; public interface VideoTypeMapper { int deleteByPrimaryKey(Integer id); int insert(VideoType record); int insertSelective(VideoType record); VideoType selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(VideoType record); int updateByPrimaryKey(VideoType record); List<VideoType> selectList(VideoType record); }
<?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="chauncy.dao.VideoTypeMapper"> <resultMap id="BaseResultMap" type="chauncy.entity.VideoType"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="type_name" property="typeName" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List"> id, type_name </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from video_type where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from video_type where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="chauncy.entity.VideoType"> insert into video_type (id, type_name) values (#{id,jdbcType=INTEGER}, #{typeName,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="chauncy.entity.VideoType"> insert into video_type <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="typeName != null"> type_name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="typeName != null"> #{typeName,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="chauncy.entity.VideoType"> update video_type <set> <if test="typeName != null"> type_name = #{typeName,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="chauncy.entity.VideoType"> update video_type set type_name = #{typeName,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <select id="selectList" resultMap="BaseResultMap" parameterType="chauncy.entity.VideoType"> select <include refid="Base_Column_List" /> from video_type where 1=1 <if test="id != null"> and #{id,jdbcType=INTEGER}, </if> <if test="typeName != null"> and #{typeName,jdbcType=VARCHAR}, </if> </select> </mapper>
- web.xml配置加载Spring:
<!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
- 运行结果解决406:
使用SpringMVC返回json格式,返回状态406,表示SpringMVC没有集成JSON转换器,解决办法:<!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --> </list> </property> </bean>
- 创建视频类型、视频详情表:
- Spring整合log4j:
注:以下配置只限于Spring4.0及以下版本可用,Spring5.0以上需要变更配置方式,在此不做列举。- 创建log4j.properties:
在resources/properties下创建log4j.properties文件### set log levels ### log4j.rootLogger =INFO,DEBUG, stdout , R log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D://EclipseWorkspace/EclipseMars2/ArchitectFirstPhase/AllProjectLogs/SSMIntegrationAndVideoWebsiteDevelop.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =D://EclipseWorkspace/EclipseMars2/ArchitectFirstPhase/AllProjectLogs/SSMIntegrationAndVideoWebsiteDevelopError.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
- web.xml加载log4j.properties:
<!--设置log4j的配置文件位置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/properties/log4j.properties</param-value> </context-param> <!--使用监听加载log4j的配置文件 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
- 在代码中需要日志管理的类使用API:
private static Logger logger = Logger.getLogger(类名.class);
- 创建log4j.properties:
- 创建maven工程的父子依赖关系:
三、视频网站后台管理系统开发实现
- 实现后台视频查询展示功能:
- 建立查询jsp页面:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>后台视频管理系统</title> </head> <body> <center> <h1>视频网站后台管理系统</h1> <a href="locaAddVideo">添加资源</a> <table style="BORDER-COLLAPSE: collapse; text-align: center;" borderColor=#000000 height=40 cellPadding=1 width="70%" align="center" border=1> <thead> <tr> <th>图片</th> <th>视频名称</th> <th>视频类型</th> <th>预览视频</th> </tr> </thead> <tbody> <c:forEach items="${listVideo}" var="p"> <tr style="font-size: 18px"> <td><img alt="" width="150px;" height="150px;" src="/static/imgs/${p.videoUrl}"></td> <td>${p.videoName}</td> <td>${p.typeName}</td> <td><a href="videoDetails?id=${p.id}" style='text-decoration: none;'>预览视频</a></td> </tr> </c:forEach> </tbody> </table> </center> </body> </html>
- 后台代码实现:
package chauncy.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import chauncy.service.VideoInfoService; @Controller @RequestMapping("/VideoInfoController") public class VideoInfoController { @Autowired private VideoInfoService videoInfoService; private static final String INDEXVIDEO="indexVideo"; /** * @methodDesc: 功能描述(查询所有视频) * @author: ChauncyWang * @param: @param httpServletRequest * @param: @param httpServletResponse * @param: @return * @returnType: String */ @RequestMapping("/indexVideo") public String indexVideo(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){ httpServletRequest.setAttribute("listVideo", videoInfoService.getVideoInfos(null)); return INDEXVIDEO; } }
package chauncy.service; import java.util.List; import chauncy.entity.VideoInfo; public interface VideoInfoService { public List<VideoInfo> getVideoInfos(VideoInfo videoInfo); }
package chauncy.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import chauncy.dao.VideoInfoMapper; import chauncy.entity.VideoInfo; import chauncy.service.VideoInfoService; @Service public class VideoInfoServiceImpl implements VideoInfoService { @Autowired private VideoInfoMapper videoInfoMapper; @Override public List<VideoInfo> getVideoInfos(VideoInfo videoInfo){ return videoInfoMapper.selectAll(videoInfo); } }
package chauncy.dao; import java.util.List; import chauncy.entity.VideoInfo; public interface VideoInfoMapper { List<VideoInfo> selectAll(VideoInfo record); }
<?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="chauncy.dao.VideoInfoMapper"> <resultMap id="BaseResultMap" type="chauncy.entity.VideoInfo"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="video_name" property="videoName" jdbcType="VARCHAR" /> <result column="video_url" property="videoUrl" jdbcType="VARCHAR" /> <result column="video_html" property="videoHtml" jdbcType="VARCHAR" /> <result column="video_type_id" property="videoTypeId" jdbcType="INTEGER" /> <result column="video_del" property="videoDel" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List"> id, video_name, video_url, video_html, video_type_id, video_del </sql> <select id="selectAll" parameterType="chauncy.entity.VideoInfo" resultType="chauncy.entity.VideoInfo"> select a.id as id,a.video_name as videoName, a.video_html as videoHtml ,a.video_url as videoUrl, a.video_del as videoDel , b.type_name as typeName from video_info as a inner join video_type as b on a.video_type_id=b.id; </select> </mapper>
- 静态资源访问404原因:
需要在springMVC配置文件中配置静态资源。<!-- 设置允许静态资源访问 --> <mvc:resources mapping="/static/imgs/**" location="static/imgs/" /> <mvc:resources mapping="/static/easyui/**" location="static/easyui/" /> <mvc:resources mapping="/static/js/**" location="static/js/" /> <mvc:resources mapping="/static/css/**" location="static/css/" />
- 建立查询jsp页面:
- 整合MybatisPageHelper分页插件:
- 新增mybatis-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> <!-- 配置分页插件 --> <plugins> <!-- interceptor的取值,在4.2版本以前:com.github.pagehelper.PageHelper,4.2版本以后,因为改变了实现,取值为:com.github.pagehelper.PageInterceptor --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库,PageHelper4.0版本后会自动识别,不用进行配置--> <!-- <property name="dialect" value="mysql" /> --> </plugin> </plugins> </configuration>
- 在applicationContext-dao.xml中Mybatis的Sql会话工厂加载mybatis-config.xml:
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:spring/mybatis-config.xml" /> </bean>
- 在Java代码中使用:
package chauncy.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import chauncy.service.VideoInfoService; @Controller @RequestMapping("/VideoInfoController") public class VideoInfoController { @Autowired private VideoInfoService videoInfoService; private static final String INDEXVIDEO="indexVideo"; /** * @methodDesc: 功能描述(查询所有视频) * @author: ChauncyWang * @param: @param httpServletRequest * @param: @param httpServletResponse * @param: @return * @returnType: String */ @RequestMapping("/indexVideo") public String indexVideo(HttpServletRequest httpServletRequest,Integer pageIndex){ //页数,一定要在dao方法之前使用,第一个参数:页数,不是limit默认起始值0,默认为1,代表limit的0,第二个参数:参数。分页公式:(页数-1)*长度。 if(pageIndex == null){ pageIndex=1; } Page page = PageHelper.startPage(pageIndex, 2); httpServletRequest.setAttribute("listVideo", videoInfoService.getVideoInfos(null)); //获取分页总数 httpServletRequest.setAttribute("pages", page.getPages()); return INDEXVIDEO; } }
- 在查询jsp页面中增加前端代码:
<a style="font-size: 20px;" href="indexVideo?pageIndex=1">首页</a> <c:forEach begin="1" end="${pages}" var="p"> <a style="font-size: 20px;" href="indexVideo?pageIndex=${p}">${p}</a> </c:forEach> <a style="font-size: 20px;" href="indexVideo?pageIndex=${pages}">尾页</a>
- 新增mybatis-config.xml文件:
- 实现后台视频详情展示功能:
- 查询jsp页面详情按钮造成请求:
<td><a href="getVideo?id=${p.id}" style='text-decoration: none;'>预览视频</a></td>
- java代码处理请求返回详情页:
package chauncy.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import chauncy.entity.VideoInfo; import chauncy.service.VideoInfoService; @Controller @RequestMapping("/VideoInfoController") public class VideoInfoController { @Autowired private VideoInfoService videoInfoService; private static final String INDEXVIDEO="indexVideo"; private static final String VIDEODETAIL="videoDetail"; /** * @methodDesc: 功能描述(展示视频详情信息) * @author: ChauncyWang * @param: @param request * @param: @param id * @param: @return * @returnType: String */ @RequestMapping("/getVideo") public String getVideo(HttpServletRequest request,Integer id){ VideoInfo videoInfo = videoInfoService.getVideoInfo(id); request.setAttribute("videoInfo", videoInfo); return VIDEODETAIL; } }
package chauncy.service; import java.util.List; import chauncy.entity.VideoInfo; public interface VideoInfoService { public VideoInfo getVideoInfo(int id); }
package chauncy.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import chauncy.dao.VideoInfoMapper; import chauncy.entity.VideoInfo; import chauncy.service.VideoInfoService; @Service public class VideoInfoServiceImpl implements VideoInfoService { @Autowired private VideoInfoMapper videoInfoMapper; @Override public VideoInfo getVideoInfo(int id) { return videoInfoMapper.selectByPrimaryKey(id); } }
- 详情页jsp嵌入第三方视频代码展示视频详情相关信息:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>${videoInfo.videoName}</title> </head> <body> <h1>${videoInfo.videoName}</h1> <iframe src="${videoInfo.videoHtml} }" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe> </body> </html>
- 查询jsp页面详情按钮造成请求:
- 实现SpringMVC的上传图片功能:
- 在springmvc.xml中添加上传文件配置:
<!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
- 查询jsp页面添加资源按钮造成请求:
<a href="jumpToAddVideoPage">添加资源</a>
- java代码处理请求返回添加视频页:
package chauncy.controller; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import chauncy.service.VideoTypeServive; @Controller @RequestMapping("/VideoInfoController") public class VideoInfoController { @Autowired private VideoTypeServive videoTypeServive; private static final String ADDVIDEO="addVideo"; @RequestMapping("/jumpToAddVideoPage") public String jumpToAddVideoPage(HttpServletRequest request){ request.setAttribute("listVideoType",videoTypeServive.getVideoTypes(null)); return ADDVIDEO; } }
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>添加视频资源</title> </head> <body> <center> <h1>后台添加视频资源</h1> <form action="addVideo" style="font-size: 14px;" method="post" ENCTYPE="multipart/form-data"> <table> <tr> <td>视频名称:</td> <td><input type="text" name=videoName></td> </tr> <tr> <td>视频类型:</td> <td><select name="videoTypeId" style="width: 170px;"> <c:forEach items="${listVideoType}" var="p"> <option value="${p.id}">${p.typeName}</option> </c:forEach> </select></td> </tr> <tr> <td>B站播放URL:</td> <td><textarea rows="10" cols="30" name="videoHtml"></textarea></td> </tr> <tr> <td>上传封面:</td> <td><input type="file" name="file"></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"></td></tr> </table> </form> </center> </body> </html>
- 添加视频频请求的实现:
package chauncy.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; 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.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import chauncy.entity.VideoInfo; import chauncy.service.VideoInfoService; import chauncy.service.VideoTypeServive; @Controller @RequestMapping("/VideoInfoController") public class VideoInfoController { private static Logger logger = Logger.getLogger(VideoInfoController.class); @Autowired private VideoInfoService videoInfoService; @Autowired private VideoTypeServive videoTypeServive; @RequestMapping("/addVideo") public String addVideo(@RequestParam(value="file",required=false)MultipartFile file,VideoInfo videoInfo,HttpServletRequest request){ //file.getOriginalFilename();//文件的原生名称 String imageName=System.currentTimeMillis()+".png";//时间戳只是在单个JVM保证不重复,但是在分布式JVM会重复 //项目环境地质 String path=request.getSession().getServletContext().getRealPath("/static/imgs"); logger.info("path:"+path); File targetFile = new File(path,imageName); if(!targetFile.exists()){ targetFile.mkdirs();//创建文件夹 } try { //保存图片 file.transferTo(targetFile); } catch (Exception e) { //打印日志一定要用e进行打印,不要用e.getMessage(),因为有时可能为空 logger.error("saveImagesError--------->"+e); request.setAttribute("result", "上传图片失败!"); return ADDVIDEO; } videoInfo.setVideoUrl(imageName); try { //videoInfo.toString()中videoInfo可以允许为空,不抛异常,直接打印空 logger.info("###videoInfoService start... addVideo()###videoInfo:"+videoInfo.toString()); int addVideoResult = videoInfoService.addVideo(videoInfo); //日志打印中={}表示对应一个参数,多个参数为:={},{}...逗号隔开 logger.info("###videoInfoService end... addVideo()###addVideoResult={}"+addVideoResult); if(addVideoResult<=0){ request.setAttribute("result", "保存数据错误!"); return ADDVIDEO; } return "redirect:/VideoInfoController/indexVideo"; } catch (Exception e) { //打印日志一定要用e进行打印,不要用e.getMessage(),因为有时可能为空 logger.error("videoInfoServiceAddVideoError--------->"+e); request.setAttribute("result", "保存数据错误!"); return ADDVIDEO; } } }
- 在springmvc.xml中添加上传文件配置:
四、扩展知识点:
- Mysql分页和Oracle分页有什么区别(SqlServer使用top分页,在此不列举)?
Mysql分页使用limit,Oracle分页使用伪列rownum分页。- limit分页
limit m,n m表示起始行,从0开始,n表示取几行。
例:
limit 0,2 表示从第0行开始取两行select * from stu limit m, n;
- rownum分页
rownum只能比较小于,不能比较大于,因为rownum是先查询后排序的,例如查询条件为rownum>1,当查询到第一条数据,rownum为1,则不符合条件。第2、3…类似,一直不符合条件,所以一直没有返回结果。所以查询的时候需要设置别名,然后查询完成之后再通过调用别名进行大于的判断。
例:
>= y,<= x表示从第y行(起始行)~x行(结束行) 。select * from ( select rownum rn,a.* from table_name a where rownum <= x //结束行,x = startPage*pageSize ) where rn >= y; //起始行,y = (startPage-1)*pageSize+1
- limit分页
- 开发工程中异常处理注意:如果为MVC分层架构,不要在Service层中做异常处理,把异常抛到Controller进行处理。