刚学SSM,踩过无数的坑,和大家分享一下如何从零搭建SSM框架,下面正式开始
本次使用的版本分别为
- 开发工具: IntelliJ IDEA 2018.1.4 x64
- maven : apache-maven-3.5.3
- jdk : jdk1.8.0_101
- tomcat : Tomcat9.0.8
在这里就不一一安装这些软件,网上的教程一大把,唯一注意的是maven设置本地仓库地址 在conf下找到setting.xml文件,修改路径:
step 1 创建一个空的maven项目 new-project
选中需要使用的SDK,下面是maven的一些模版暂时不用
填上需要的GroupId和ArtifactId,点击next
选择项目的地址,然后在新窗口打开
接下来可以在IDEA看到我们创建的maven项目
step 2 构建项目基本架构
项目基本的架构如下:
目录解释如下:
- controller:http(GET和POST等)请求的入口,调用Service,向客户端返回数据
- dao:定义了数据表映射成的对象,具有的操作
- mapping:具体是sql语句,以xml格式存在,即mybatis的语法文件
- pojo:实体类
- service:controller调用的服务,service调用dao里面定义的数据库行为方法,来执行对应mapping里的mybatis,从而完成与数据库完整的交互。
- service-impl:接口,定义了服务应该具有的函数方法(此处可以理解是提现软件的设计思想,你要是乐意,直接写service也可以)
step 3 修改POM文件
- 修改项目使用的maven,使其使用本地下载的 File -setting 然后搜索maven
修改Runner属性 在VM options 加上 -Dmaven.multiModuleProjectDirectory=$M2_HOME ($M2_HOME为配置的系统环境变量)
- 修改POM文件,在文件中加入以下代码,将项目所需要的jar导入
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HRMS</groupId>
<artifactId>HRMS</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号 -->
<spring.version>4.1.4.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.8</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<!-- jackson包版本 -->
<jackson.version>2.5.0</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</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.2.2</version>
</dependency>
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- springMVC核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</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-context-support</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<!--<dependency>-->
<!--<groupId>mysql</groupId>-->
<!--<artifactId>mysql-connector-java</artifactId>-->
<!--<version>5.1.30</version>-->
<!--</dependency>-->
<!-- 导入oracle数据库链接jar包-->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</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>
<!-- log end -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.1.0</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!--Spring test相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.15</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-core</artifactId>
<version>0.6.1</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-extension</artifactId>
<version>0.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
在这里需要注意的主要有2个地方
- 在这个demo我使用的是oracle数据库,由于Oracle授权问题,Maven3不提供oracle JDBC driver。所以需要我们自己手动配置,具体配置可以百度下,使用mysql数据库直接将mysql的注释打开即可。
- 在最后的 plugins 标签中使用的是mybatis自动生成代码的jar 在这里我也先把他加进来。
step 4 完善SSM的配置文件
jdbc.properties
在resources下新建个配置文件jdbc.properties,内容如下:
driver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@fmw:1521:orcl
user = osb
password = oracle
#定义初始连接数
initialSize= 0
#定义最大连接数
maxActive= 20
#定义最大空闲
maxIdle= 20
#定义最小空闲
minIdle= 1
#定义最长等待时间
maxWait= 60000
- spring-mvc.xml
在resources下新建个配置文件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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.springmvc.controller" />
<!--避免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>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<!--<property name="prefix" value="/WEB-INF/page/" />-->
<property name="prefix" value="/page/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</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>
<!--配置全局属性-->
<settings>
<setting name="logImpl" value="LOG4J" />
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
- spring-mybatis.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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.springmvc" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/springmvc/mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.springmvc.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
- log4j.xml
配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "http://toolkit.alibaba-inc.com/dtd/log4j/log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jakarta.apache.org/log4j/ ">
<!-- ===================================================================== -->
<!-- 定义全局输出适配器 -->
<!-- ===================================================================== -->
<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}]-[%c]-[%t] %x - %m%n"/>
</layout>
</appender>
<!-- Mybatis and SQL -->
<logger name="org.apache.ibatis" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="org.mybatis.spring" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql.Connection" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql.Statement" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<logger name="java.sql.PreparedStatement" additivity="true">
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</logger>
<!-- Spring -->
<logger name="org.springframework" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
</logger>
<!-- ActiveMQ -->
<logger name="org.apache.activemq" additivity="true">
<level value="ERROR"/>
<appender-ref ref="consoleAppender"/>
</logger>
<!-- ===================================================================== -->
<!-- 根日志记录器 -->
<!-- ===================================================================== -->
<root>
<level value="DEBUG"/>
<appender-ref ref="consoleAppender"/>
</root>
</log4j:configuration>
- log4j.properties
配置如下:
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
下面是配置文件的总截图:
step 5 配置项目工程
- 创建一个Spring Application Context
将配置文件集成进项目
最后的成果图如下:
step 5 配置webapp
- 在src下创建目录webapp
web,xml的配置如下:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<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_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!--Log4j配置-->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 编码过滤器 -->
<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>
<!--Spring监听器 ApplicationContext 载入 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC 核心配置开始 -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 可以通过contextConfigLocation来自定义SpringMVC配置文件的位置,如不指定,则默认在WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,
此时文件名必须为[<servlet-name>]-servlet.xml,否则会出错-->
<!--以下init-param是自定义SpringMVC的配置文件的位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<!-- 拦截设置 -->
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring MVC 核心配置结束 -->
<!-- 配置SESSION超时,单位是分钟 -->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
- 将web模块集成进项目
修改web.xml以及web目录
- 添加artifacts
点击OK,到这里所有的配置都完成了,如下:
- 配置tomcat服务器
step 6 测试
在controller中新建测试.
点击运行。
package com.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Test {
@RequestMapping("/test")
@ResponseBody
public String test(){
return "hello world";
}
}
运行结果如下:
在这个过程中 可能会出现这个异常
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [spring-mybatis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.core.io.Resource[]' for property 'mapperLocations'; nested exception is java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:com/springmvc/mapping/*.xml]: class path resource [com/springmvc/mapping/] cannot be resolved to URL because it does not exist
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:743)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4627)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5091)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:742)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:718)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:703)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1737)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:456)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:405)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:324)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.core.io.Resource[]' for property 'mapperLocations'; nested exception is java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:com/springmvc/mapping/*.xml]: class path resource [com/springmvc/mapping/] cannot be resolved to URL because it does not exist
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:480)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:511)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:505)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1515)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1474)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 56 more
Caused by: java.lang.IllegalArgumentException: Could not resolve resource location pattern [classpath:com/springmvc/mapping/*.xml]: class path resource [com/springmvc/mapping/] cannot be resolved to URL because it does not exist
at org.springframework.core.io.support.ResourceArrayPropertyEditor.setAsText(ResourceArrayPropertyEditor.java:140)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:450)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:423)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:195)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:460)
... 62 more
没有遇到直接跳过,这里我说下我的解决办法
- 第一种 我在POM文件结尾的build中加入resources节点的内容,完整的build节点数据如下:
<build>
<finalName>HRMS</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<!--<filtering>true</filtering>-->
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
- 第二种是在spring-mybatis.xml文件中的mapperLocations属性的classpath路径加上* 如下:
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/mybatis-config.xml"></property>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath*:com/springmvc/mapping/*.xml"></property>
</bean>
接下来 我们整合页面和数据库进行一个完整的测试,模拟用户登录的过程,用户在前面输入用户名和密码,返回这个用户具体的详细信息。
数据库配置:
-- Create table
create table HR_USER_IFNO
(
user_name VARCHAR2(40) not null,
user_password VARCHAR2(40),
user_role VARCHAR2(40),
user_code VARCHAR2(3),
user_id VARCHAR2(18),
user_phone VARCHAR2(200),
user_sex VARCHAR2(1),
user_birthdate DATE,
user_addr VARCHAR2(100),
user_mail VARCHAR2(40),
creation_date VARCHAR2(40),
creation_by VARCHAR2(40),
last_update_date DATE,
last_updated_by VARCHAR2(40),
attribue1 VARCHAR2(200),
attribue2 VARCHAR2(200),
attribue3 VARCHAR2(200),
attribue4 VARCHAR2(200),
attribue5 VARCHAR2(200)
)
insert into HR_USER_IFNO (USER_NAME, USER_PASSWORD, USER_ROLE, USER_CODE, USER_ID, USER_PHONE, USER_SEX, USER_BIRTHDATE, USER_ADDR, USER_MAIL, CREATION_DATE, CREATION_BY, LAST_UPDATE_DATE, LAST_UPDATED_BY, ATTRIBUE1, ATTRIBUE2, ATTRIBUE3, ATTRIBUE4, ATTRIBUE5)
values ('xiaoming', '123456', '1', '1', '1', '13111111111', '0', to_date('17-05-2018', 'dd-mm-yyyy'), '广州', '123@qq.com', '', '', null, '', '', '', '', '', '');
然后我们使用mybatis的自动生成工具mybatis-generator-core,生成pojo、mapping、dao
具体步骤如下:
- 在pom.xml导入mybatis-generator-core配置,这个上面已完成,在这里不做详细介绍
- 配置generatorConfig.xml
在resources创建generatorConfig.xml 特别注意其中的路径!!! 还有一个 在这里我读取不到JDBC文件中的内容,所以数据库连接信息是写死的,这个正在解决,具体的内容如下:
<?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>
<!-- 指定数据连接驱动jar地址 -->
<classPathEntry location="H:\MavenRepository\maven_jar\com\oracle\ojdbc7\12.1.0.2\ojdbc7-12.1.0.2.jar" />
<!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator >
<property name="suppressAllComments" value="false"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@fmw:1521:orcl" userId="osb"
password="oracle" />
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.springmvc.pojo"
targetProject="src" >
<!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="com.springmvc.mapping"
targetProject="src" >
<!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator targetPackage="com.springmvc.dao"
targetProject="src" type="XMLMAPPER" >
<!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 配置表信息 -->
<table tableName="HR_USER_IFNO"
domainObjectName="UserEntity" enableCountByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false">
<!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample
是否生成 example类 -->
</table>
</context>
</generatorConfiguration>
文件详细的配置信息可以参照官网 点我
- idea配置
点击“+”添加一个maven 在其命令行添加 mybatis-generator:generate -e
然后运行即可生成 pojo mapping 以及 dao 效果如下:
将其移到java目录下,即
- 接下来开始写sql
在mapping文件中加上我们自己的查询逻辑
- 在dao层将方法暴露出来,注意这里的方法名称需要和上面配置的mapping文件中的ID对应
List<UserEntity> selectInfoByUsername(@Param("userName")String userName, @Param("password")String password);
- 现在数据已经能获取到了,接下里我们开始写service层
新建一个Service接口 UsreLoginService
package com.springmvc.service;
import com.springmvc.pojo.UserEntity;
import java.util.List;
public interface UsreLoginService {
List<UserEntity> getUserInfo(String userName, String password);
}
它的实现类 UserLoginServiceImpl
package com.springmvc.service.impl;
import com.springmvc.dao.UserEntityMapper;
import com.springmvc.pojo.UserEntity;
import com.springmvc.service.UsreLoginService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserLoginServiceImpl implements UsreLoginService{
@Resource
private UserEntityMapper userEntityMapper;
public List<UserEntity> getUserInfo(String userName, String password){
return this.userEntityMapper.selectInfoByUsername(userName,password);
}
}
- 数据已经准备完成,现在开始写控制器,coltroler获取页面传输过来的用户名和密码,然后把用户的信息返回到页面。
package com.springmvc.controller;
import com.springmvc.pojo.UserEntity;
import com.springmvc.service.UserLoginService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@Controller
public class Test {
@Resource
private UserLoginService userLoginService;
@RequestMapping("/test")
public ModelAndView test(HttpServletRequest request){
String userName = request.getParameter("username");
String password = request.getParameter("password");
UserEntity userEntity = this.userLoginService.getUserInfo(userName,password).get(0);
ModelAndView retMap = new ModelAndView(); //返回新的ModelAndView
retMap.addObject("user",userEntity);
retMap.setViewName("login");
return retMap;
}
}
- 然后在page目录下新建一个简单的JSP做测试
<%--
Created by IntelliJ IDEA.
User: PrexAout
Date: 2018/5/28
Time: 14:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
这个只是简单的测试页面 用户信息为
用户名:${user.userName} 手机:${user.userPhone} 生日:${user.userBirthdate} 地址:${user.userAddr}
</body>
</html>
到这里 所有的准备工作已经OVER了 运行代码进行测试
到这里,项目的基本框架就已经搭建完了,日后也会把这个项目继续完善。欢迎大家留言一起交流学习
项目源码 https://download.csdn.net/download/prexanony/10442643;
【参考】
【java】intellij idea搭建SSM框架摘录
Intellij IDEA中使用MyBatis-generator 自动生成MyBatis代码