1、下载Maven
http://maven.apache.org/download.cgi
2、安装Maven配置环境变量
解压maven文件到指定目录,创建本地创库文件夹
配置maven –> conf 下的settings.xml文件指向创建好的创库文件夹localrepository,配置阿里云仓库(自动创库下载太慢)。
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- | This is the configuration file for Maven. It can be specified at two levels: | | 1. User Level. This settings.xml file provides configuration for a single user, | and is normally provided in ${user.home}/.m2/settings.xml. | | NOTE: This location can be overridden with the CLI option: | | -s /path/to/user/settings.xml | | 2. Global Level. This settings.xml file provides configuration for all Maven | users on a machine (assuming they're all using the same Maven | installation). It's normally provided in | ${maven.conf}/settings.xml. | | NOTE: This location can be overridden with the CLI option: | | -gs /path/to/global/settings.xml | | The sections in this sample file are intended to give you a running start at | getting the most out of your Maven installation. Where appropriate, the default | values (values used when the setting is not specified) are provided. | |--> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <!--本地仓库。该值表示构建系统本地仓库的路径。其默认值为~/.m2/repository。 --> <localRepository>D:\developer\maven\localrepository</localRepository> <!--Maven是否需要和用户交互以获得输入。如果Maven需要和用户交互以获得输入,则设置成true,反之则应为false。默认为true。 <interactiveMode>true</interactiveMode> --> <mirrors> <!-- mirror | Specifies a repository mirror site to use instead of a given repository. The repository that | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. | --> <mirror> <id>nexus-aliyun</id> <mirrorOf>central</mirrorOf> <name>Nexus aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> </mirror> <mirror> <id>net-cn</id> <mirrorOf>central</mirrorOf> <name>Nexus net</name> <url>http://maven.net.cn/content/groups/public/</url> </mirror> </mirrors> <profiles> <profile> <id>jdk-1.7</id> <activation> <jdk>1.7</jdk> </activation> <repositories> <repository> <id>nexus</id> <name>local private nexus</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus</id> <name>local private nexus</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </profile> </profiles> <activeProfiles> <activeProfile>nexus</activeProfile> </activeProfiles> </settings>
更改完成之后配置环境变量
3、配置IDEA Maven创建Maven项目
打开-File-Settings
打开-File-New-Project
点击NEXT
点击NEXT
点击NEXT
我们可以看到,目录结构并不是严格的maven格式,因为少了java源码文件夹
首先在main文件夹下创建一个文件夹,名称为java.将java文件夹标识为Source Root
在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 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ssm</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ssm Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- spring版本号 --> <spring.version>4.3.13.RELEASE</spring.version> <!-- mybatis-plus版本 --> <mybatis-plus.version>2.1.5</mybatis-plus.version> <!-- mybatis-generator版本 --> <mybatis-generator.version>1.3.5</mybatis-generator.version> <!-- mysql驱动版本号 --> <!-- <mysql-driver.version>6.0.6</mysql-driver.version>--> <mysql-driver.version>5.1.44</mysql-driver.version> <!-- 阿里数据库连接池版本号 --> <druid.version>1.1.5</druid.version> <!-- fastjson版本号 --> <fastjson.version>1.2.41</fastjson.version> <!-- log4j日志包版本号 --> <slf4j.version>1.7.18</slf4j.version> <log4j.version>1.2.17</log4j.version> <!-- freemarker前端模块引擎版本 --> <freemarker.version>2.3.23</freemarker.version> <!-- JSP相关 --> <jstl.version>1.2</jstl.version> <servlet-api.version>2.5</servlet-api.version> <javax.servlet-apiversion>3.1.0</javax.servlet-apiversion> <!-- log4j日志包版本号 --> <slf4j.version>1.7.18</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker.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> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- 添加mysql驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-driver.version}</version> </dependency> <!-- 添加数据库连接池依赖 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- mybatis generator --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>${mybatis-generator.version}</version> </dependency> <!-- 添加日志相关jar包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies> <build> <finalName>ssm</finalName> <pluginManagement> <plugins> <!-- 配置Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>80</port> </configuration> </plugin> <!-- MyBatis Generator --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>${mybatis-generator.version}</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
创建目录和文件包
配置jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8 jdbc.username=root jdbc.password=dida123456 jdbc.initialSize=1 jdbc.maxActive=5 jdbc.minIdle=1 jdbc.maxWait=60000 jdbc.filters=stat jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.minEvictableIdleTimeMillis=300000
配置generatorConfig.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!-- 配置文件 --> <properties resource="jdbc.properties"/> <classPathEntry location="D:\developer\maven\localrepository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar" /> <context id="context1" targetRuntime="MyBatis3"> <!-- 序列化生成实体,添加实体生成的tostring方法 --> <plugin type="org.mybatis.generator.plugins.SerializablePlugin" /> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!-- 生成没有注释 --> <commentGenerator> <property name="suppressDate" value="true" /> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- SQL Server数据库链接URL、用户名、密码 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}" /> <!-- javaModelGenerator是模型的生成信息,这里将指定这些Java model类的生成路径 --> <javaModelGenerator targetPackage="com.ssm.model" targetProject="src\main\java"> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成Mapper 配置文件 --> <sqlMapGenerator targetPackage="mapper" targetProject="src\main\resources" /> <!-- javaClientGenerator是应用接口的生成信息 --> <javaClientGenerator targetPackage="com.ssm.mapper" targetProject="src\main\java" type="XMLMAPPER" /> <!-- 生成器配置 enableCountByExample(默认true):指定是否生成动态查询总条数语句(用于分页的总条数查询) enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句 enableUpdateByExample(默认true):指定是否生成动态修改语句(只修改对象中不为空的属性) selectByExampleQueryId:这个值将被添加到选择列表中选择通过例子的声明在本表格:“' <值>作为QUERYID”。这可以用于识别查询在DBA在运行时跟踪工具。如果你需使用,你应该指定一个唯一的id为每个不同的查询生成MBG。 enableSelectByExample:是否应该生成通过example的选择语句。这个声明使得许多不同的动态查询是在运行时生成。 useActualColumnNames用于指定生成实体类时是否使用实际的列名作为实体类的属性名。取值true或false: true MyBatis Generator会使用数据库中实际的字段名字作为生成的实体类的属性名。 false 这是默认值。如果设置为false,则MyBatis Generator会将数据库中实际的字段名字转换为Camel Case风格作为生成的实体类的属性名。 generatedKey用于生成生成主键的方法, 如果设置了该元素,MBG会在生成的<insert>元素中生成一条正确的<selectKey>元素,该元素可选 column:主键的列名; sqlStatement:要生成的selectKey语句,有以下可选项: Cloudscape:相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL() DB2 :相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL() DB2_MF :相当于selectKey的SQL为:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1 Derby :相当于selectKey的SQL为:VALUES IDENTITY_VAL_LOCAL() HSQLDB :相当于selectKey的SQL为:CALL IDENTITY() Informix :相当于selectKey的SQL为:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1 MySql :相当于selectKey的SQL为:SELECT LAST_INSERT_ID() SqlServer :相当于selectKey的SQL为:SELECT SCOPE_IDENTITY() SYBASE :相当于selectKey的SQL为:SELECT @@IDENTITY JDBC :相当于在生成的insert元素上添加useGeneratedKeys="true"和keyProperty属性 --> <table schema="test" tableName="t_user" domainObjectName="User" enableCountByExample="false" enableDeleteByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false" enableSelectByExample="false"> <property name="enab" value=""/> <!-- 实体类中的成员变量和表的列明一一对应 --> <property name="useActualColumnNames" value="true"/> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> </context> </generatorConfiguration>
配置IDEA generator
mybatis-generator:generate -e
设置完成点击运行
在成功生成map和model等文件后配置springxml文件
mybatis-config.xml文件配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- | plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下: | properties?, settings?, | typeAliases?, typeHandlers?, | objectFactory?,objectWrapperFactory?, | plugins?, | environments?, databaseIdProvider?, mappers? |--> <configuration> <!-- | 全局配置设置 | | 可配置选项 默认值, 描述 | | aggressiveLazyLoading true, 当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 | multipleResultSetsEnabled true, 允许和不允许单条语句返回多个数据集(取决于驱动需求) | useColumnLabel true, 使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。 | useGeneratedKeys false, 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 | autoMappingBehavior PARTIAL, 指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。 | defaultExecutorType SIMPLE, 配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。 | defaultStatementTimeout null, 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时 | --> <settings> <!-- 这个配置使全局的映射器启用或禁用缓存 --> <setting name="cacheEnabled" value="true"/> <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="defaultExecutorType" value="REUSE"/> <setting name="defaultStatementTimeout" value="25000"/> <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 --> <!-- <setting name="useGeneratedKeys" value="true" />--> <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} --> <!--<setting name="mapUnderscoreToCamelCase" value="true" />--> </settings> <!-- <!– 引入自定义 mapper 文件 –> <mappers> <!– 引入mapper文件 –> <mapper resource="mapper/UserMapper.xml"/> </mappers>--> </configuration>
spring-mybatis.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: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:jdbc.properties"/> <!-- 数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}" /> <!-- 初始化连接大小 --> <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="validationQuery" value="select 1"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000"/> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true"/> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800"/> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true"/> </bean> <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <!-- 配置数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描 Xml 文件位置 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <!-- 配置 Mybatis 配置文件(可无) --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!-- 配置包别名,支持通配符 * 或者 ; 分割 --> <property name="typeAliasesPackage" value="com.ssm.model"/> <!-- 枚举属性配置扫描,支持通配符 * 或者 ; 分割 --> <!-- <property name="typeEnumsPackage" value="com.baomidou.springmvc.entity.*.enums"/>--> <!-- 以上配置和传统 Mybatis 一致 --> <!-- 插件配置 --> <property name="plugins"> <array> <!-- 分页插件配置, 参考文档分页插件部分!! --> <bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"> <property name="dialectType" value="mysql"/> </bean> <!-- 如需要开启其他插件,可配置于此 --> </array> </property> <!-- MP 全局配置注入 --> <property name="globalConfig" ref="globalConfig"/> </bean> <!-- 定义 MP 全局策略 --> <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!-- 主键策略配置 --> <!-- 可选参数 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") --> <property name="idType" value="2"/> <!-- 数据库类型配置 --> <!-- 可选参数(默认mysql) MYSQL->`mysql` ORACLE->`oracle` DB2->`db2` H2->`h2` HSQL->`hsql` SQLITE->`sqlite` POSTGRE->`postgresql` SQLSERVER2005->`sqlserver2005` SQLSERVER->`sqlserver` --> <property name="dbType" value="mysql"/> <!-- 全局表为下划线命名设置 true --> <property name="dbColumnUnderline" value="true"/> </bean> <!-- 配置事务管理 --> <bean name="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="add*" propagation="REQUIRED"/> <tx:method name="append*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="modify*" propagation="REQUIRED"/> <tx:method name="edit*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED"/> <tx:method name="repair" propagation="REQUIRED"/> <tx:method name="get*" propagation="REQUIRED" read-only="true"/> <tx:method name="find*" propagation="REQUIRED" read-only="true"/> <tx:method name="load*" propagation="REQUIRED" read-only="true"/> <tx:method name="search*" propagation="REQUIRED" read-only="true"/> <tx:method name="datagrid*" propagation="REQUIRED" read-only="true"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置切面 --> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.ssm.service..*.*(..))"/> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/> </aop:config> <!-- MyBatis 动态实现 --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 对Dao 接口动态实现,需要知道接口在哪 --> <property name="basePackage" value="com.ssm.mapper"/> </bean> </beans>
spring-mvc.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"> <!-- 配置包扫描器 --> <context:component-scan base-package="com.ssm"/> <!-- 配置注解驱动 --> <mvc:annotation-driven/> <!-- 扫描service、dao --> <context:component-scan base-package="com.ssm"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置freeMarker的模板路径 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="WEB-INF/views/" /> <property name="defaultEncoding" value="UTF-8" /> </bean> <!-- freemarker视图解析器 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" /> <property name="suffix" value=".ftl" /> <property name="contentType" value="text/html;charset=UTF-8" /> <property name="order" value="10"></property> <!--是否开放request属性--> <property name="exposeRequestAttributes" value="true" /> <!-- 此变量值为pageContext.request, 页面使用方法:rc.contextPath --> <property name="requestContextAttribute" value="rc" /> </bean> </beans>
applicationContext.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:util="http://www.springframework.org/schema/util" 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/util http://www.springframework.org/schema/util/spring-util.xsd"> <!-- Service包(自动注入) --> <context:component-scan base-package="com.baomidou"/> <import resource="classpath:spring/spring-mybatis.xml"/> </beans>
web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <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"> <!-- 初始化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> <display-name>ssm</display-name> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
webapp创建文件夹view创建user.ftl
user.ftl文件
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>test</title>
</head>
<body>
user ${user.name}
</body>
</html>
创建UserService接口
package com.ssm.service;
import com.ssm.model.User;
public interface UserService {
User findBrandById(String id);
}
创建UserServiceImpl实现类
package com.ssm.service.impl;
import com.ssm.mapper.UserMapper;
import com.ssm.model.User;
import com.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findBrandById(String id) {
return userMapper.selectByUserLogin(user);
}
}
创建UserController控制器
package com.ssm.controller;
import com.ssm.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@Controller
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
/**Freemarker模板的Controller*/
@RequestMapping(value="/user/{id}")
public ModelAndView getUserById(@PathVariable("id") String id,HttpServletRequest request) {
ModelAndView mv = new ModelAndView("user");
mv.addObject("user", userService.findBrandById(id));
return mv;
}
}
添加tomcat编译