视频地址: https://www.bilibili.com/video/av44673048
一. maven相关知识点回顾
功能特点:
- 依赖管理
- 一键构建
基本命令:
- mvn clean
- mvn compile
- mvn test
- mvn package
- mvn clean
- mvn install
坐标:
- groupId:所需Jar包的项目名
- artifactId:所需Jar包的模块名
- version:所需Jar包的版本号
排除依赖:
<exclusions>
<exclusion>
<groupId>cn.missbe.web.search</groupId>
<artifactId>resource-search</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
</exclusion>
</exclusions>
依赖范围scope:
- compile :默认范围,用于编译
- provided:提供,告诉mevan这个jar包服务器有
- runtime: 在执行时需要使用
- test: 用于test任务时使用 ,不会被打包
- system: 需要外在提供相应的元素,通过systemPath来取得
- systemPath: 仅用于范围为system,提供相应的路径
- optional: 当项目自身被依赖时,标注依赖是否传递。用于连续依赖时使用
依赖冲突:
- 短路优先(就近原则)
谁的路径就近引用谁 - 声明优先
在1的情况下,谁先在pom.xml中声明谁优先
聚合:
-
概念
将多个项目同时运行,即所有项目同时进行install、packet等命令,不需要根据依赖关系必须先运行依赖的项目 -
实现
使用module标签<modules> <module>../bean</module> <module>../common</module> <module>../web</module> <module>../manager-api</module> <module>../manager-impl</module> <module>../potal-api</module> <module>../potal-impl</module> </modules>
继承:
-
概念
在聚合多个项目时,如果这些被聚合的项目中需要引入相同的Jar,那么可以将这些Jar写入父pom中,各个子项目继承该pom即可 -
实现
-
父工程统一管理jar包,打包方式必须为pom。小技巧:可以使用properties标签进行同一版本管理
<groupId>com.itstudy</groupId> <artifactId>parent</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging>
使用dependencyManagement 标签对所有依赖进行管理
<dependencyManagement> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope><!-- 注意!!!! --> </dependency> <!-- 省略 ... -- > </dependencyManagement>
-
子工程只需使用parent标签声明父工程,后引用父工程依赖即可,不需要带version。注意:web工程打包方式为war,其它工程打包方式为jar。不需要带version
<parent> <artifactId>parent</artifactId> <groupId>com.itstudy</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>manager-api</artifactId> <packaging>jar</packaging> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </dependency> <!-- 省略 ... -- > </dependencies>
-
二. 环境搭建
1.new一个空工程,创建8个项目。分别为
-
parent - 父工程 :聚合其它工程(打包方式为: war)
-
web - web工程:存放所有页面,框架配置文件(jar)
-
manager -impl:后台管理系统,存放控制器类,业务层实现类(jar)
-
manager-api 后台管理系统,存放业务层接口和DAO层接口(jar)
-
potal-impl 前台系统,存放控制器类,业务层实现类(jar)
-
potal-api 前台系统,存放业务层接口和DAO层接口(jar)
-
common 存放所有模块所需要的公共类(jar)
-
bean 存放所有模块的实体类(jar)
2.根据图示依赖关系,建立各项目之间的依赖关系
实例:由图项目manager-api依赖项目bean和项目common(依赖谁就将谁的坐标放在pom文件)
<dependency>
<groupId>com.itstudy</groupId>
<artifactId>bean</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.itstudy</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
3. 构建ssm框架
-
在web项目中进行如下配置
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" id="WebApp_ID" version="2.5"> <display-name>crw</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring/spring-*.xml</param-value> </context-param> <!-- 监听器 创建spring框架的IOC容器 将IOC容器对象存放在application域 ApplicationContext ioc = WebApplicationContextUtils.getApplicationContext(application); ServletContextListener监听器接口: 监听ServletContext的创建和销毁 如果监听到ServletContext创建(服务器启动),就会创建IOC容器(XmlWebApplicationContext ); 如果监听到ServletContext销毁(服务器停止或卸载项目),就会销毁IOC容器。 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 字符编码过滤器 只负责解决post请求乱码问题。get需要修改tomcat配置文件 --> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> <!-- 开启内部请求过滤 --> <!--<dispatcher>FORWARD</dispatcher>--> <!--<dispatcher>REQUEST</dispatcher>--> </filter-mapping> <!--支持restful风格,将post请求转换为put或delete请求--> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <servlet-name>springmvc</servlet-name> </filter-mapping> <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:spring/springmvc-context.xml</param-value> </init-param> <!--服务器在一启动的时候就创建这个对象, 数字越小级别越高--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!--扩展匹配--> <url-pattern>*.htm</url-pattern> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 会话超时时间 --> <session-config> <session-timeout>60</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
log4j:
# ##设置日志级别 # log4j.rootLogger=info,debug,CONSOLE,file log4j.rootLogger=debug,CONSOLE,file # ## 指定输出信息到控制台 log4j.addivity.org.apache=true log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender # thread属性,指定日志level.根据日志的重要程度,可以分为off,fatal,error,warn,info,debug。 log4j.appender.CONSOLE.Threshold=info log4j.appender.CONSOLE.Target=System.out log4j.appender.CONSOLE.Encoding= UTF-8 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.appender1.MaxFileSize=100KB # ##输出Debug级别以上的日志到log文件夹下。 log4j.appender.file=org.apache.log4j.DailyRollingFileAppender log4j.appender.file.DatePattern=yyyyMMdd log4j.appender.file.File=../logs/teachingManagementService.log # 每天的日志打印就不需要设置大小属性 # log4j.appender.file.MaxFileSize=20MB # log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d [%X{uuid}] [%X{ip}] [%X{userId}] %-5p %l - %m%n log4j.logger.com.alibaba.dubbo=error
springmvc-context.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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 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.0.xsd"> <!-- 启用注解功能 --> <context:annotation-config /> <!-- 字符串字符编码转换 处理json数据,将数据返回给客服端的时候进行处理 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <context:component-scan base-package="com.itstudy.*" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--异常解析器。遇到的所有异常都往错误页面进行跳转--> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">error/error</prop> </props> </property> </bean> <!--处理文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8"> <property name="maxUploadSize" value="2097152"/> <property name="resolveLazily" value="true"/> </bean> </beans>
spring-context.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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.itstudy.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 加载外部属性配置文件 --> <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:config/jdbc.properties" /> </bean> <!-- 配置C3P0数据源 --> <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.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations"> <list> <value>classpath*:mybatis/mapper-*.xml</value> </list> </property> </bean> <!-- 扫描Mapper映射配置 --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--<property name="basePackage" value="com.itstudy.crw.manager.dao,com.itstudy.crw.potal.dao"/>--> <property name="basePackage" value="com.itstudy.crw.*.dao"/> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.Exception"/> <tx:method name="query*" read-only="true"/> </tx:attributes> </tx:advice> <!--给service绑定事务,设定切面范围--> <aop:config> <aop:advisor advice-ref="transactionAdvice" pointcut="execution(* com.itstudy.crw..*Service.*(..))"/> </aop:config> </beans>
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> <!--<typeAliases>--> <!--<typeAlias type="User" alias="user"/>--> <!--</typeAliases>--> </configuration>
jdbc.properties:
jdbc.user=root jdbc.password=123456 jdbc.url=jdbc:mysql://192.168.0.105:3306/2019-8-04?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8 jdbc.driver=com.mysql.jdbc.Driver
-
在其余除父工程外均创建如下类,切记包名一定要相同
4.测试环境
-
在manger-api和manger-impl工程中按如图所示构建
TestDao:package com.itstudy.crw.manager.dao; import org.springframework.stereotype.Repository; import java.util.Map; @Repository public interface TestDao { public void insert(Map map); }
TestService:
package com.itstudy.crw.manager.service; public interface TestService { public void insert(); }
TestController:
package com.itstudy.crw.manager.controller; import com.itstudy.crw.manager.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class TestController { @Autowired private TestService testService; @RequestMapping("/test") public String test(){ testService.insert(); System.out.println("testController执行了"); return "success"; } }
TestServiceImpl:
package com.itstudy.crw.manager.serviceImpl; import com.itstudy.crw.manager.dao.TestDao; import com.itstudy.crw.manager.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class TestServiceImpl implements TestService { @Autowired private TestDao testDao; public void insert() { Map map = new HashMap(); map.put("name","lisi"); testDao.insert(map); } }
mapper-user.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.itstudy.crw.manager.dao.TestDao"> <insert id="insert"> insert into t_student ( name ) values ( #{name} ) </insert> <!-- <select id="queryRolePermissionByUser" resultType="permission"> select * from t_permission where id in ( select rp.permissionid from t_role_permission rp join t_user_role ur on ur.roleid = rp.roleid and ur.userid = #{id} ) and id != pid order by seqno </select> <insert id="insertUser"> insert into t_user ( name,userpswd,sex,email,loginacct ) values ( #{name},#{userpswd},#{sex},#{email},#{loginacct} ) <selectKey keyProperty="id" resultType="int"> select @@identity as id </selectKey> </insert> <update id="updateUser"> update t_user set name = #{name}, sex = #{sex}, email = #{email}, loginacct = #{loginacct} where id = #{id} </update> <delete id="deleteUserRole"> delete from t_user_role where userid = #{userid} and roleid = #{roleid} </delete> --> </mapper>
-
配置tomcat并启动
-
运行成功