在Eclipse中利用maven整合搭建ssm框架
首先说明用到的框架: spring + springMVC + mybatis
构建工具:maven
开发工具:eclipse
开发环境:win10 java版本:jdk1.8 tomcat版本:tomcat8.0
一、创建web项目
|
先整体看下项目的目录结构
二、maven需要引入的jar包,pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>com.cjk</groupId> 5 <artifactId>ssm</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>ssm Maven Webapp</name> 9 <url>http://maven.apache.org</url> 10 11 <properties> 12 <!-- spring版本号 --> 13 <spring.version>4.0.2.RELEASE</spring.version> 14 <!-- mybatis版本号 --> 15 <mybatis.version>3.2.6</mybatis.version> 16 <!-- log4j日志文件管理包版本 --> 17 <slf4j.version>1.7.7</slf4j.version> 18 <log4j.version>1.2.17</log4j.version> 19 </properties> 20 <dependencies> 21 <dependency> 22 <groupId>junit</groupId> 23 <artifactId>junit</artifactId> 24 <version>3.8.1</version> 25 <scope>test</scope> 26 </dependency> 27 <!-- 导入java ee jar包(可以去除index.jsp报错) --> 28 <dependency> 29 <groupId>javax</groupId> 30 <artifactId>javaee-api</artifactId> 31 <version>7.0</version> 32 </dependency> 33 <dependency> 34 <groupId>junit</groupId> 35 <artifactId>junit</artifactId> 36 <version>4.11</version> 37 <!-- 表示开发的时候引入,发布的时候不会加载此包 --> 38 <scope>test</scope> 39 </dependency> 40 <!-- spring核心包 --> 41 <dependency> 42 <groupId>org.springframework</groupId> 43 <artifactId>spring-core</artifactId> 44 <version>${spring.version}</version> 45 </dependency> 46 <dependency> 47 <groupId>org.springframework</groupId> 48 <artifactId>spring-web</artifactId> 49 <version>${spring.version}</version> 50 </dependency> 51 <dependency> 52 <groupId>org.springframework</groupId> 53 <artifactId>spring-oxm</artifactId> 54 <version>${spring.version}</version> 55 </dependency> 56 <dependency> 57 <groupId>org.springframework</groupId> 58 <artifactId>spring-tx</artifactId> 59 <version>${spring.version}</version> 60 </dependency> 61 <dependency> 62 <groupId>org.springframework</groupId> 63 <artifactId>spring-jdbc</artifactId> 64 <version>${spring.version}</version> 65 </dependency> 66 <dependency> 67 <groupId>org.springframework</groupId> 68 <artifactId>spring-webmvc</artifactId> 69 <version>${spring.version}</version> 70 </dependency> 71 <dependency> 72 <groupId>org.springframework</groupId> 73 <artifactId>spring-aop</artifactId> 74 <version>${spring.version}</version> 75 </dependency> 76 <dependency> 77 <groupId>org.springframework</groupId> 78 <artifactId>spring-context-support</artifactId> 79 <version>${spring.version}</version> 80 </dependency> 81 <dependency> 82 <groupId>org.springframework</groupId> 83 <artifactId>spring-test</artifactId> 84 <version>${spring.version}</version> 85 </dependency> 86 <!-- mybatis核心包 --> 87 <dependency> 88 <groupId>org.mybatis</groupId> 89 <artifactId>mybatis</artifactId> 90 <version>${mybatis.version}</version> 91 </dependency> 92 <!-- mybatis/spring包 --> 93 <dependency> 94 <groupId>org.mybatis</groupId> 95 <artifactId>mybatis-spring</artifactId> 96 <version>1.2.2</version> 97 </dependency> 98 <!-- 导入Mysql数据库链接jar包 --> 99 <dependency> 100 <groupId>mysql</groupId> 101 <artifactId>mysql-connector-java</artifactId> 102 <version>5.1.30</version> 103 </dependency> 104 <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> 105 <dependency> 106 <groupId>commons-dbcp</groupId> 107 <artifactId>commons-dbcp</artifactId> 108 <version>1.2.2</version> 109 </dependency> 110 <!-- JSTL标签类 --> 111 <dependency> 112 <groupId>jstl</groupId> 113 <artifactId>jstl</artifactId> 114 <version>1.2</version> 115 </dependency> 116 <!-- 日志文件管理包 --> 117 <!-- log start --> 118 <dependency> 119 <groupId>log4j</groupId> 120 <artifactId>log4j</artifactId> 121 <version>${log4j.version}</version> 122 </dependency> 123 <!-- 格式化对象,方便输出日志 --> 124 <dependency> 125 <groupId>com.alibaba</groupId> 126 <artifactId>fastjson</artifactId> 127 <version>1.1.41</version> 128 </dependency> 129 <dependency> 130 <groupId>org.slf4j</groupId> 131 <artifactId>slf4j-api</artifactId> 132 <version>${slf4j.version}</version> 133 </dependency> 134 <dependency> 135 <groupId>org.slf4j</groupId> 136 <artifactId>slf4j-log4j12</artifactId> 137 <version>${slf4j.version}</version> 138 </dependency> 139 <!-- log end --> 140 <!-- 映入JSON --> 141 <dependency> 142 <groupId>org.codehaus.jackson</groupId> 143 <artifactId>jackson-mapper-asl</artifactId> 144 <version>1.9.13</version> 145 </dependency> 146 <!-- 上传组件包 --> 147 <dependency> 148 <groupId>commons-fileupload</groupId> 149 <artifactId>commons-fileupload</artifactId> 150 <version>1.3.1</version> 151 </dependency> 152 <dependency> 153 <groupId>commons-io</groupId> 154 <artifactId>commons-io</artifactId> 155 <version>2.4</version> 156 </dependency> 157 <dependency> 158 <groupId>commons-codec</groupId> 159 <artifactId>commons-codec</artifactId> 160 <version>1.9</version> 161 </dependency> 162 <!-- 自动生成 --> 163 <dependency> 164 <groupId>org.mybatis.generator</groupId> 165 <artifactId>mybatis-generator-core</artifactId> 166 <version>1.3.6</version> 167 </dependency> 168 169 170 </dependencies> 171 <build> 172 <finalName>ssm</finalName> 173 <plugins> 174 <plugin> 175 <groupId>org.apache.maven.plugins</groupId> 176 <artifactId>maven-compiler-plugin</artifactId> 177 <version>3.5.1</version> 178 <configuration> 179 <source>1.8</source> 180 <target>1.8</target> 181 <encoding>UTF-8</encoding> 182 </configuration> 183 </plugin> 184 </plugins> 185 </build> 186 </project>
三、建立JDBC属性配置文件,jdbc.properties
#数据库驱动
driver=com.mysql.jdbc.Driver
#数据库连接
url=jdbc:mysql://localhost:3306/cjk_ssm?useUnicode=true&characterEncoding=UTF-8
#用户名
username=root
#用户密码
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
四、log4j日志配置文件 , 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/springmvcMybist/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
五、建立spring-mybatis.xml配置文件
这个文件就是用来完成spring和mybatis的整合的,包含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: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-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.cjk" /> <!-- 引入配置文件 --> <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="${username}" /> <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" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/cjk/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cjk.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>
六、整合springMVC,spring-mvc.xml
上面已经完成了2大框架的整合,SpringMVC的配置文件单独放,然后在web.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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<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>
<!-- JSON转换器 -->
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<!-- 对静态资源的访问 -->
<!-- <mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" /> -->
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.cjk.controller" />
<!-- 添加注解驱动 -->
<mvc:annotation-driven enable-matrix-variables="true" />
<!-- 允许对静态资源文件的访问 -->
<mvc:default-servlet-handler />
<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<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>
七、配置web.xml
这里面是对spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前2框架整合不需要在此处进行任何配置。
<?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_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-*.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <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监听器 --> <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> <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-mvc.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> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.html</welcome-file> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
到目前为止,所有的整合已经完成,配置文件也搞好了,接下来就利用mybatis来自动生成一些java代码:
首先,我们建立数据库:下面是建库建表的语句
CREATE DATABASE `cjk_ssm`
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(40) NOT NULL, `password` varchar(255) NOT NULL, `age` int(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user_t` VALUES (1,'测试ssm','123',24);
1.利用MyBatis Generator自动创建代码
在桌面上建立一个文件夹(本文用到的文件夹不包含中文字符),然后在里面建个src文件夹,里面的东西如下图:
其中jar包是需要下载的,下面附上下载地址:
Mybatis-Generator的下载可以到这个地址:https://github.com/mybatis/generator/releases
Mysql-connector-java的下载可以到这个地址:https://dev.mysql.com/downloads/connector/j/
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> <!-- 数据库驱动 --> <classPathEntry location="mysql-connector-java-5.1.45-bin.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true" /> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库链接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/cjk_ssm" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="com.cjk.bean" targetProject="src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成映射文件的包名和位置 --> <sqlMapGenerator targetPackage="com.cjk.mapping" targetProject="src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.cjk.dao" targetProject="src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 --> <table tableName="user_t" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
注:一般jar包下载下来的zip文件可直接用,但是我这儿出现了问题,所以我把两个下载下来的zip文件解压,然后把两个jar包提取出来;
还有就是下载的jar包的版本,如果不是上文师范的版本,下载之后在配置文件中修改;
需要修改的我用颜色标示出来了,可自行修改;
最后,打开cmd,进入该文件夹(也可以在这个文件夹中按住 shift + 右击,选择"在此处打开命令窗口"),复制粘贴以下代码+回车
Java -jar mybatis-generator-core-1.3.6.jar -configfile generatorConfig.xml -overwrite
完成后,到该文件夹下打开src,如下
然后复制进eclipse相应的文件夹中,
接着我们手动创建service
package com.cjk.service; import com.cjk.bean.User; public interface UserService { public User getUserById(int userId); }
手动创建serviceImpl
package com.cjk.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjk.bean.User; import com.cjk.dao.UserMapper; import com.cjk.service.UserService; @Service("userService") public class UserServiceImpl implements UserService{ @Autowired private UserMapper userDao; @Override public User getUserById(int userId) { return this.userDao.selectByPrimaryKey(userId); } }
手动创建jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>ssm测试</title> </head> <body> <h1>${user.userName}</h1> </body> </html>
手动创建controller
package com.cjk.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.cjk.bean.User; import com.cjk.service.impl.UserServiceImpl; @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private UserServiceImpl userServiceImpl; @RequestMapping(value = "/test") public String Index(HttpServletRequest request, Model model){ int userId = Integer.parseInt(request.getParameter("id")); User user = userServiceImpl.getUserById(userId); model.addAttribute("user",user); return "User"; } }
至此,所有的代码已经完成了,最后我们看看总体的项目结构
然后将项目部署到tomcat中,这里就不再示范部署,直接给截图:
然后启动:
启动成功,没有报错,然后访问一下:
到这里项目就完成了!