PS:初学,想使用Maven配置一个SpringMVC的开发环境,照着网上的各种图文解说,配置了好久都没成功,有些写的不够详细,有些只有写一半,走了不少弯弯绕绕,踩了不少的坑,此文将正确配置成功的步骤全部记录下来。
1、环境
- IDEA 2017.3
- Maven 使用了 IDEA自带Maven,亦可以不用自带的(没什么大区别),不用IDEA自带的可以先去下载maven安装并设置。
Maven 安装配置 http://www.cnblogs.com/yangdaxian/p/8676373.html
- JDK 1.8 JDK需要先下载安装配置好
- Spring
- Mybatis
- MySQL 5.1.41 MySQL需要保证可用
- Tomcat 8
2、SSM整合
新建数据库表
CREATE TABLE `user` ( `id` varchar(10) NOT NULL, `name` varchar(20) DEFAULT NULL, `sex` varchar(5) DEFAULT NULL, `age` varchar(3) DEFAULT NULL, `address` varchar(100) DEFAULT NULL, `phone` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO mytest.`user`(id, name, sex, age, address, phone) VALUES('1', '张三', '男', '18', '共住地球村', '18888888881'); INSERT INTO mytest.`user`(id, name, sex, age, address, phone) VALUES('2', '李四', '男', '16', '共住地球村', '18888888882'); INSERT INTO mytest.`user`(id, name, sex, age, address, phone) VALUES('3', '洪五', '女', '22', '共住地球村', '18888888883'); INSERT INTO mytest.`user`(id, name, sex, age, address, phone) VALUES('4', '马六', '女', '17', '共住地球村', '18888888884'); INSERT INTO mytest.`user`(id, name, sex, age, address, phone) VALUES('5', '孙七', '女', '23', '共住地球村', '18888888885'); INSERT INTO mytest.`user`(id, name, sex, age, address, phone) VALUES('6', '赵八', '男', '38', '共住地球村', '18888888886');
新建maven项目
- 选择好自己的JDK路径
- 设置项目的group id, artifactid, version等信息
- 设置maven仓库路径,我这边偷懒直接使用了idea自带的
- 项目名设置,然后Finish
- 等待后生成结构如下,右下角选择 Enable Auto-import 自动导入;
- 如果没有自动导入这个选项,pom.xml配置完成后可以在右侧边缘找到 Maven Projects 打开后点击第一个类似刷新的按钮进行下载
- 新建结构目录如下(若想要包分层结构显示在,上面齿轮那的第二行菜单,【Hide Empty Middle Packages】,将以选中的勾去掉就行)
- 新建的 java 文件 需要对它转一下, java文件夹上 右击 --> Make Diretorys as --> Sources Root (蓝色) /Test Sources Root (绿色)
【pom.xml 配置】
- 在<build>中添加如下信息
<!--plugins添加逆向工程插件-->
<plugins>
... 默认信息
<!--mybatis逆向工程插件--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <!-- 设置JDK版本 --> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> <finalName>springmvc</finalName> <!--若不配置,可能会发送打包不全--> <resources> <resource> <!--需要打包的目录--> <directory>src/main/java</directory> <!--目录中的文件类型--> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> <resource> <!--需要打包的目录--> <directory>src/main/resources</directory> <!--目录中的文件类型--> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources>
- 在 <dependencies>之前设置变量参数
<!-- 设置变量参数 --> <properties> <!-- 设置项目编码编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- spring版本号 --> <spring.version>4.3.5.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.4.1</mybatis.version> <!--log4j 版本号--> <log4j.version>1.2.17</log4j.version> </properties>
- 在 <dependencies>内添加需要的依赖包
<!-- java ee --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- 实现slf4j接口并整合 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.2</version> </dependency> <!-- JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.7</version> </dependency> <!-- 数据库 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> <scope>runtime</scope> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!--添加Hibernate Validator依赖,不加此项会报错,但不影响项目运行--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <!-- Spring 依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</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-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-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- log4j日志 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies>
- 【pom.xml 配置】 最终配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!-- 3 Licensed to the Apache Software Foundation (ASF) under one 4 or more contributor license agreements. See the NOTICE file 5 distributed with this work for additional information 6 regarding copyright ownership. The ASF licenses this file 7 to you under the Apache License, Version 2.0 (the 8 "License"); you may not use this file except in compliance 9 with the License. You may obtain a copy of the License at 10 11 http://www.apache.org/licenses/LICENSE-2.0 12 13 Unless required by applicable law or agreed to in writing, 14 software distributed under the License is distributed on an 15 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 KIND, either express or implied. See the License for the 17 specific language governing permissions and limitations 18 under the License. 19 --> 20 <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> 21 <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"> 22 23 <modelVersion>4.0.0</modelVersion> 24 <packaging>war</packaging> 25 26 <name>springmvc</name> 27 <groupId>com.yq</groupId> 28 <artifactId>springmvc</artifactId> 29 <version>1.0-SNAPSHOT</version> 30 31 <build> 32 <plugins> 33 <plugin> 34 <groupId>org.mortbay.jetty</groupId> 35 <artifactId>maven-jetty-plugin</artifactId> 36 <version>6.1.7</version> 37 <configuration> 38 <connectors> 39 <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> 40 <port>8888</port> 41 <maxIdleTime>30000</maxIdleTime> 42 </connector> 43 </connectors> 44 <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory> 45 <contextPath>/</contextPath> 46 </configuration> 47 </plugin> 48 49 <!--mybatis逆向工程插件--> 50 <plugin> 51 <groupId>org.mybatis.generator</groupId> 52 <artifactId>mybatis-generator-maven-plugin</artifactId> 53 <version>1.3.2</version> 54 </plugin> 55 56 <plugin> 57 <groupId>org.apache.maven.plugins</groupId> 58 <artifactId>maven-compiler-plugin</artifactId> 59 <configuration> 60 <!-- 设置JDK版本 --> 61 <source>1.8</source> 62 <target>1.8</target> 63 </configuration> 64 </plugin> 65 </plugins> 66 67 <finalName>springmvc</finalName> 68 69 <!--若不配置,可能会发送打包不全--> 70 <resources> 71 <resource> 72 <!--需要打包的目录--> 73 <directory>src/main/java</directory> 74 <!--目录中的文件类型--> 75 <includes> 76 <include>**/*.xml</include> 77 <include>**/*.properties</include> 78 </includes> 79 </resource> 80 <resource> 81 <!--需要打包的目录--> 82 <directory>src/main/resources</directory> 83 <!--目录中的文件类型--> 84 <includes> 85 <include>**/*.xml</include> 86 <include>**/*.properties</include> 87 </includes> 88 </resource> 89 </resources> 90 </build> 91 92 <!-- 设置变量参数 --> 93 <properties> 94 <!-- 设置项目编码编码 --> 95 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 96 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 97 <!-- spring版本号 --> 98 <spring.version>4.3.5.RELEASE</spring.version> 99 <!-- mybatis版本号 --> 100 <mybatis.version>3.4.1</mybatis.version> 101 <!--log4j 版本号--> 102 <log4j.version>1.2.17</log4j.version> 103 </properties> 104 105 <dependencies> 106 <!-- java ee --> 107 <dependency> 108 <groupId>javax</groupId> 109 <artifactId>javaee-api</artifactId> 110 <version>7.0</version> 111 </dependency> 112 113 <!-- 单元测试 --> 114 <dependency> 115 <groupId>junit</groupId> 116 <artifactId>junit</artifactId> 117 <version>4.12</version> 118 </dependency> 119 120 <!-- 实现slf4j接口并整合 --> 121 <dependency> 122 <groupId>ch.qos.logback</groupId> 123 <artifactId>logback-classic</artifactId> 124 <version>1.2.2</version> 125 </dependency> 126 127 <!-- JSON --> 128 <dependency> 129 <groupId>com.fasterxml.jackson.core</groupId> 130 <artifactId>jackson-databind</artifactId> 131 <version>2.8.7</version> 132 </dependency> 133 134 135 <!-- 数据库 --> 136 <dependency> 137 <groupId>mysql</groupId> 138 <artifactId>mysql-connector-java</artifactId> 139 <version>5.1.41</version> 140 <scope>runtime</scope> 141 </dependency> 142 143 <!-- 数据库连接池 --> 144 <dependency> 145 <groupId>com.mchange</groupId> 146 <artifactId>c3p0</artifactId> 147 <version>0.9.5.2</version> 148 </dependency> 149 150 <!-- MyBatis --> 151 <dependency> 152 <groupId>org.mybatis</groupId> 153 <artifactId>mybatis</artifactId> 154 <version>${mybatis.version}</version> 155 </dependency> 156 157 <!-- mybatis/spring整合包 --> 158 <dependency> 159 <groupId>org.mybatis</groupId> 160 <artifactId>mybatis-spring</artifactId> 161 <version>1.3.1</version> 162 </dependency> 163 164 <!--添加Hibernate Validator依赖,不加此项会报错,但不影响项目运行--> 165 <dependency> 166 <groupId>org.hibernate</groupId> 167 <artifactId>hibernate-validator</artifactId> 168 <version>5.2.4.Final</version> 169 </dependency> 170 171 <!-- Spring 依赖--> 172 <dependency> 173 <groupId>org.springframework</groupId> 174 <artifactId>spring-core</artifactId> 175 <version>${spring.version}</version> 176 </dependency> 177 <dependency> 178 <groupId>org.springframework</groupId> 179 <artifactId>spring-beans</artifactId> 180 <version>${spring.version}</version> 181 </dependency> 182 <dependency> 183 <groupId>org.springframework</groupId> 184 <artifactId>spring-context</artifactId> 185 <version>${spring.version}</version> 186 </dependency> 187 <dependency> 188 <groupId>org.springframework</groupId> 189 <artifactId>spring-jdbc</artifactId> 190 <version>${spring.version}</version> 191 </dependency> 192 <dependency> 193 <groupId>org.springframework</groupId> 194 <artifactId>spring-tx</artifactId> 195 <version>${spring.version}</version> 196 </dependency> 197 <dependency> 198 <groupId>org.springframework</groupId> 199 <artifactId>spring-web</artifactId> 200 <version>${spring.version}</version> 201 </dependency> 202 <dependency> 203 <groupId>org.springframework</groupId> 204 <artifactId>spring-webmvc</artifactId> 205 <version>${spring.version}</version> 206 </dependency> 207 <dependency> 208 <groupId>org.springframework</groupId> 209 <artifactId>spring-test</artifactId> 210 <version>${spring.version}</version> 211 </dependency> 212 213 <!-- log4j日志 --> 214 <dependency> 215 <groupId>log4j</groupId> 216 <artifactId>log4j</artifactId> 217 <version>${log4j.version}</version> 218 </dependency> 219 </dependencies> 220 221 </project>
配置 log4j.properties
- 在resources下新建,根据实际路径更改输出日志路径(D:/WorkSpace/idea_workSpase/springmvc/src/main/webapp/WEB-INF/log/log.txt)
#日志输出级别 log4j.rootLogger=debug,stdout,D,E #设置stdout的日志输出控制台 log4j.appender.stdout=org.apache.log4j.ConsoleAppender #输出日志到控制台的方式,默认为System.out log4j.appender.stdout.Target = System.out #设置使用灵活布局 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout #灵活定义输出格式 log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%c (%rms)] - %m%n #每天产生一个日志文件 log4j.appender.D=org.apache.log4j.DailyRollingFileAppender #设置的输出日志 log4j.appender.D.File=D:/WorkSpace/idea_workSpase/springmvc/src/main/webapp/WEB-INF/log/log.txt #设置的日志最大限制 log4j.appender.D.MaxFileSize=6000KB #最多只保存20个备份文件 log4j.appender.D.MaxBackupIndex=20 #输出INFO级别以上的日志 og4j.appender.D.Threshold=debug log4j.appender.D.Append = true log4j.appender.D.ImmediateFlush = true #log4j.appender.D.DatePattern ='.'yyyy-MM-dd #设置使用灵活布局 log4j.appender.D.layout=org.apache.log4j.PatternLayout #灵活定义输出格式 log4j.appender.D.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%l (%rms)] - %m%n log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =D:/WorkSpace/idea_workSpase/springmvc/src/main/webapp/WEB-INF/log/error/error.txt log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR #log4j.appender.E.DatePattern = '_'yyyyMMdd'.log' log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%l (%rms)] - %m%n
配置 jdbc.properties
- 在resources下新建;需要更改本地驱动路径与数据库连接信息
jdbc.driverLocation=C:\\Users\\yq\\.m2\\repository\\mysql\\mysql-connector-java\\5.1.41\\mysql-connector-java-5.1.41.jar jdbc.driverClasss=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.56.107:3306/mytest?useUnicode=true&characterEncoding=UTF-8 #声明使用username可能会与系统jvm冲突 jdbc.username=demo jdbc.password=demo
- 驱动包路径查看方式:找到对应驱动后 右击 --> copy path
配置generatorConfig.xml
- mybatis逆向工程配置文件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"></properties> <!--指定特定数据库的jdbc驱动jar包的位置--> <classPathEntry location="${jdbc.driverLocation}"/> <context id="default" targetRuntime="MyBatis3"> <!-- optional,旨在创建class时,对注释进行控制 --> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--jdbc的数据库连接 --> <jdbcConnection driverClass="${jdbc.driverClasss}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制--> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类 targetPackage 指定生成的model生成所在的包名 targetProject 指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.yq.model" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- 是否对model添加 构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否对类CHAR类型的列的数据进行trim操作 --> <property name="trimStrings" value="true"/> <!-- 建立的Model对象是否 不可改变,即生成的Model对象不会有 getter/setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 --> <sqlMapGenerator targetPackage="com.yq.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码 type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator targetPackage="com.yq.dao" targetProject="src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 配置需要生成model的数据库表,此项<table> 必须存在,没有需要生成的表的话直接设置为""即可--> <table tableName="user"></table> </context> </generatorConfiguration>
- 在这边你可能遭遇 (没遇到请跳过)
http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd 识别不到的问题,可进行如下操作,File --> Setting 添加未识别的项
- 配置完成后的目录结构如下
测试逆向生成是否成功
配置完成后,可以测试逆向生成是否配置成功了~
点击左上角绿色的 + ,设置好 Name(自定义) 与 Command line
选中刚才设置的,点击执行,如果正确配置了能看到在 dao 与 model中均生成了如下文件,这个User表是在generatorConfig.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="com.yq.service"/> <!-- 配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath*:jdbc.properties"/> <!-- 数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClasss}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描model包 使用别名 --> <property name="mapperLocations" value="classpath:com/yq/dao/*.xml" /> </bean> <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.yq.dao"/> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
配置spring-mvc
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描web相关的bean --> <context:component-scan base-package="com.yq.controller"/> <!-- 开启SpringMVC注解模式 --> <mvc:annotation-driven/> <!-- 静态资源默认servlet配置 --> <mvc:default-servlet-handler/> <!-- 配置jsp 显示ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </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"> <display-name>springmvc</display-name> <description>springmvc_0.0.1</description> <!-- 编码过滤器 --> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- log4j 配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- 配置log4j 日志监听 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- 配置DispatcherServlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springMVC需要加载的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 匹配所有请求--> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
测试查询数据库是否成功
在test --> dao 目录下新建一个测试类,测试下现在能否读取到数据库内容
package com.yq.dao; import com.yq.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mybatis.xml"}) public class UserQueryTest { @Autowired private UserMapper userMapper; @Test public void queryUserName() { String id = "1"; User user = userMapper.selectByPrimaryKey(id); System.out.println(user.getName()); } }
- webapp文件下创建index.jsp文件
<%-- Created by IntelliJ IDEA. User: yq Date: 2018/3/29 Time: 14:56 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>测试标题</title> </head> <body> Hello World! 你的配置是正确哒!!!~~~ </body> </html>
配置Tomcat
配置完成 ,启动看看~~
从数据库取数据来展示
- 现在上面已经配置成功了,接下去就要试试从数据库取数据来展示了
- 创建UserService
package com.yq.service; import com.yq.dao.UserMapper; import com.yq.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(String id){ return userMapper.selectByPrimaryKey(id); } }
- 创建UserController
package com.yq.controller; import com.yq.model.User; import com.yq.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/userInfo") public class UserController { @Autowired private UserService userService; @RequestMapping("/getUser") public ModelAndView getUser(String id){ ModelAndView modelAndView = new ModelAndView(); User user = userService.getUserById(id); modelAndView.addObject("userInfo",user); modelAndView.setViewName("userInfo/getUser"); return modelAndView; } }
- 创建jsp文件,我们在spring-mvc.xml中配置了目录
因此我们要在 WEB-INF下新建个jsp文件夹
- getUser.jsp
<%-- Created by IntelliJ IDEA. User: yq Date: 2018/4/2 Time: 14:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>测试getUser</title> </head> <body> <p>编号: ${userInfo.id}</p> <p>姓名:${userInfo.name}</p> </body> </html>
访问 http://localhost:8080/springmvc/userInfo/getUser?id=2
完成,没毛病; 配置期间如果由于环境问题会出现一些异常错误,一般拷贝错误度娘下都能解决掉,都不是什么大问题。共勉~
项目下载地址: