一、Maven创建项目
1. 在Eclipse中选择New -> Project -> Maven -> Maven Project
2. 选择默认workspace之后建立maven-webapp
3. 填写Group Id和Artifact Id(项目名称)
4. 建立工程后发现目录结构报错
5. 为了避免乱码,右键点击工程选择Properties -> Resource,选择编码方式为UTF-8
6. 在Properties中选择Java Build Path -> JRE System Library -> Edit,选择默认JRE
7. 引入java ee的jar包解决index.jsp报错的问题,在pom.xml中<dependencies>标签内添加如下代码,至此目录报错问题解决
1 <dependency> 2 <groupId>javax</groupId> 3 <artifactId>javaee-api</artifactId> 4 <version>7.0</version> 5 </dependency>
8. 在pom.xml中引入SSM框架所需的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.wwwsealss</groupId> 5 <artifactId>SSMFrameBuild</artifactId> 6 <packaging>war</packaging> 7 <version>0.0.1-SNAPSHOT</version> 8 <name>SSMFrameBuild 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 21 <dependencies> 22 23 <dependency> 24 <groupId>junit</groupId> 25 <artifactId>junit</artifactId> 26 <version>4.11</version> 27 <!-- 表示开发的时候引入,发布的时候不会加载此包 --> 28 <scope>test</scope> 29 </dependency> 30 31 <!-- spring核心包 --> 32 <dependency> 33 <groupId>org.springframework</groupId> 34 <artifactId>spring-core</artifactId> 35 <version>${spring.version}</version> 36 </dependency> 37 38 <dependency> 39 <groupId>org.springframework</groupId> 40 <artifactId>spring-web</artifactId> 41 <version>${spring.version}</version> 42 </dependency> 43 44 <dependency> 45 <groupId>org.springframework</groupId> 46 <artifactId>spring-oxm</artifactId> 47 <version>${spring.version}</version> 48 </dependency> 49 50 <dependency> 51 <groupId>org.springframework</groupId> 52 <artifactId>spring-tx</artifactId> 53 <version>${spring.version}</version> 54 </dependency> 55 56 <dependency> 57 <groupId>org.springframework</groupId> 58 <artifactId>spring-jdbc</artifactId> 59 <version>${spring.version}</version> 60 </dependency> 61 62 <dependency> 63 <groupId>org.springframework</groupId> 64 <artifactId>spring-webmvc</artifactId> 65 <version>${spring.version}</version> 66 </dependency> 67 68 <dependency> 69 <groupId>org.springframework</groupId> 70 <artifactId>spring-aop</artifactId> 71 <version>${spring.version}</version> 72 </dependency> 73 74 <dependency> 75 <groupId>org.springframework</groupId> 76 <artifactId>spring-context-support</artifactId> 77 <version>${spring.version}</version> 78 </dependency> 79 80 <dependency> 81 <groupId>org.springframework</groupId> 82 <artifactId>spring-test</artifactId> 83 <version>${spring.version}</version> 84 </dependency> 85 86 <!-- mybatis核心包 --> 87 <dependency> 88 <groupId>org.mybatis</groupId> 89 <artifactId>mybatis</artifactId> 90 <version>${mybatis.version}</version> 91 </dependency> 92 93 <!-- mybatis/spring包 --> 94 <dependency> 95 <groupId>org.mybatis</groupId> 96 <artifactId>mybatis-spring</artifactId> 97 <version>1.2.2</version> 98 </dependency> 99 100 <!-- 导入java ee jar 包 --> 101 <dependency> 102 <groupId>javax</groupId> 103 <artifactId>javaee-api</artifactId> 104 <version>7.0</version> 105 </dependency> 106 107 <!-- 导入Mysql数据库链接jar包 --> 108 <dependency> 109 <groupId>mysql</groupId> 110 <artifactId>mysql-connector-java</artifactId> 111 <version>5.1.30</version> 112 </dependency> 113 114 <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> 115 <dependency> 116 <groupId>commons-dbcp</groupId> 117 <artifactId>commons-dbcp</artifactId> 118 <version>1.2.2</version> 119 </dependency> 120 121 <!-- JSTL标签类 --> 122 <dependency> 123 <groupId>jstl</groupId> 124 <artifactId>jstl</artifactId> 125 <version>1.2</version> 126 </dependency> 127 128 <!-- 日志文件管理包 --> 129 <!-- log start --> 130 <dependency> 131 <groupId>log4j</groupId> 132 <artifactId>log4j</artifactId> 133 <version>${log4j.version}</version> 134 </dependency> 135 136 <!-- 格式化对象,方便输出日志 --> 137 <dependency> 138 <groupId>com.alibaba</groupId> 139 <artifactId>fastjson</artifactId> 140 <version>1.1.41</version> 141 </dependency> 142 143 <dependency> 144 <groupId>org.slf4j</groupId> 145 <artifactId>slf4j-api</artifactId> 146 <version>${slf4j.version}</version> 147 </dependency> 148 149 <dependency> 150 <groupId>org.slf4j</groupId> 151 <artifactId>slf4j-log4j12</artifactId> 152 <version>${slf4j.version}</version> 153 </dependency> 154 <!-- log end --> 155 156 <!-- 映入JSON --> 157 <dependency> 158 <groupId>org.codehaus.jackson</groupId> 159 <artifactId>jackson-mapper-asl</artifactId> 160 <version>1.9.13</version> 161 </dependency> 162 163 <!-- 上传组件包 --> 164 <dependency> 165 <groupId>commons-fileupload</groupId> 166 <artifactId>commons-fileupload</artifactId> 167 <version>1.3.1</version> 168 </dependency> 169 170 <dependency> 171 <groupId>commons-io</groupId> 172 <artifactId>commons-io</artifactId> 173 <version>2.4</version> 174 </dependency> 175 176 <dependency> 177 <groupId>commons-codec</groupId> 178 <artifactId>commons-codec</artifactId> 179 <version>1.9</version> 180 </dependency> 181 182 <dependency> 183 <groupId>org.mybatis.generator</groupId> 184 <artifactId>mybatis-generator-core</artifactId> 185 <version>1.3.2</version> 186 </dependency> 187 188 </dependencies> 189 190 <build> 191 <finalName>SSMFrameBuild</finalName> 192 </build> 193 </project>
二、Spring和MyBatis整合
1. 在工程目录src/main/resources下建立jdbc.properties文件,代码如下
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/jsp_db 3 username=root 4 password= 5 #定义初始连接数 6 initialSize=0 7 #定义最大连接数 8 maxActive=20 9 #定义最大空闲 10 maxIdle=20 11 #定义最小空闲 12 minIdle=1 13 #定义最长等待时间 14 maxWait=60000
2. 在工程目录src/main/resources下建立spring-mybatis.xml文件,代码如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 12 <!-- 自动扫描 --> 13 <context:component-scan base-package="com.wwwsealss" /> 14 <!-- 引入配置文件 --> 15 <bean id="propertyConfigurer" 16 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 17 <property name="location" value="classpath:jdbc.properties" /> 18 </bean> 19 20 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 21 destroy-method="close"> 22 <property name="driverClassName" value="${driver}" /> 23 <property name="url" value="${url}" /> 24 <property name="username" value="${username}" /> 25 <property name="password" value="${password}" /> 26 <!-- 初始化连接大小 --> 27 <property name="initialSize" value="${initialSize}"></property> 28 <!-- 连接池最大数量 --> 29 <property name="maxActive" value="${maxActive}"></property> 30 <!-- 连接池最大空闲 --> 31 <property name="maxIdle" value="${maxIdle}"></property> 32 <!-- 连接池最小空闲 --> 33 <property name="minIdle" value="${minIdle}"></property> 34 <!-- 获取连接最大等待时间 --> 35 <property name="maxWait" value="${maxWait}"></property> 36 </bean> 37 38 <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> 39 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 40 <property name="dataSource" ref="dataSource" /> 41 <!-- 自动扫描mapping.xml文件 --> 42 <property name="mapperLocations" value="classpath:com/wwwsealss/mapping/*.xml"></property> 43 </bean> 44 45 <!-- DAO接口所在包名,Spring会自动查找其下的类 --> 46 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 47 <property name="basePackage" value="com.wwwsealss.dao" /> 48 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 49 </bean> 50 51 <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> 52 <bean id="transactionManager" 53 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 54 <property name="dataSource" ref="dataSource" /> 55 </bean> 56 57 </beans>
3. 在工程目录src/main/resources下建立log4j.properties文件,代码如下
1 #定义LOG输出级别 2 log4j.rootLogger=INFO,Console,File 3 #定义日志输出目的地为控制台 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender 5 log4j.appender.Console.Target=System.out 6 #可以灵活地指定日志输出格式,下面一行是指定具体的格式 7 log4j.appender.Console.layout = org.apache.log4j.PatternLayout 8 log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n 9 10 #文件大小到达指定尺寸的时候产生一个新的文件 11 log4j.appender.File = org.apache.log4j.RollingFileAppender 12 #指定输出目录 13 log4j.appender.File.File = logs/ssm.log 14 #定义文件最大大小 15 log4j.appender.File.MaxFileSize = 10MB 16 # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 17 log4j.appender.File.Threshold = ALL 18 log4j.appender.File.layout = org.apache.log4j.PatternLayout 19 log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
4. 用MySQL Workbench创建测数据库jsp_db,并建立测试表user_t
5. 利用MyBatis Generator自动创建代码,需要目录中的三个jar包和一个生成器配置文件generatorConfig.xml,代码如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 <generatorConfiguration> 6 <!-- 数据库驱动--> 7 <classPathEntry location="mysql-connector-java-5.1.30.jar"/> 8 <context id="DB2Tables" targetRuntime="MyBatis3"> 9 <commentGenerator> 10 <property name="suppressDate" value="true"/> 11 <!-- 是否去除自动生成的注释 true:是 : false:否 --> 12 <property name="suppressAllComments" value="true"/> 13 </commentGenerator> 14 <!--数据库链接URL,用户名、密码 --> 15 <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/jsp_db" userId="root" password=""> 16 </jdbcConnection> 17 <javaTypeResolver> 18 <property name="forceBigDecimals" value="false"/> 19 </javaTypeResolver> 20 <!-- 生成模型的包名和位置--> 21 <javaModelGenerator targetPackage="com.wwwsealss.entity" targetProject="src"> 22 <property name="enableSubPackages" value="true"/> 23 <property name="trimStrings" value="true"/> 24 </javaModelGenerator> 25 <!-- 生成映射文件的包名和位置--> 26 <sqlMapGenerator targetPackage="com.wwwsealss.mapping" targetProject="src"> 27 <property name="enableSubPackages" value="true"/> 28 </sqlMapGenerator> 29 <!-- 生成DAO的包名和位置--> 30 <javaClientGenerator type="XMLMAPPER" targetPackage="com.wwwsealss.IDao" targetProject="src"> 31 <property name="enableSubPackages" value="true"/> 32 </javaClientGenerator> 33 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> 34 <table tableName="user_t" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> 35 </context> 36 </generatorConfiguration>
6. 在控制台中进入该目录并输入java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite即可生成相应的实体类、接口、配置文件,将生成的三个包复制到工程目录src/main/java下,并将dao包下的Mapper改为Dao
7. 在工程目录src/main/java下建立service接口和实现类,代码如下
IUserService代码
1 package com.wwwsealss.service; 2 3 import com.wwwsealss.entity.User; 4 5 public interface IUserService { 6 public User getUserById(int userId); 7 }
UserServiceImpl代码
1 package com.wwwsealss.service.impl; 2 3 import javax.annotation.Resource; 4 5 import org.springframework.stereotype.Service; 6 7 import com.wwwsealss.dao.IUserDao; 8 import com.wwwsealss.entity.User; 9 import com.wwwsealss.service.IUserService; 10 11 @Service("userService") 12 public class UserServiceImpl implements IUserService { 13 14 @Resource 15 private IUserDao iUserDao; 16 17 public User getUserById(int userId) { 18 return this.iUserDao.selectByPrimaryKey(userId); 19 } 20 21 public void saveNewUser(User user) { 22 this.iUserDao.insert(user); 23 } 24 25 }
8. 在工程目录src/test/java下建立测试类,代码如下
1 package com.wwwsealss.test; 2 3 import javax.annotation.Resource; 4 import javax.json.Json; 5 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.springframework.context.ApplicationContext; 9 import org.springframework.test.context.ContextConfiguration; 10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 11 12 import com.alibaba.fastjson.JSON; 13 import com.sun.glass.ui.Application; 14 import com.sun.istack.internal.logging.Logger; 15 import com.wwwsealss.entity.User; 16 import com.wwwsealss.service.IUserService; 17 18 @RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类 19 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) 20 21 public class TestMyBatis { 22 23 private static Logger logger = Logger.getLogger(TestMyBatis.class); 24 @Resource 25 private IUserService userService = null; 26 27 @Test 28 public void test() { 29 User user = userService.getUserById(1); 30 logger.info(JSON.toJSONString(user)); 31 } 32 33 }
9. 右键TestMyBatis.java选择Run As -> JUnit Test,得到测试结果如下,说明Spring和MyBatis整合成功
三、整合SpringMVC
1. 在工程目录src/main/resources下建立spring-mvc.xml文件,代码如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 12 <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> 13 <context:component-scan base-package="com.wwwsealss.controller" /> 14 <!--避免IE执行AJAX时,返回JSON出现下载文件 --> 15 <bean id="mappingJacksonHttpMessageConverter" 16 class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 17 <property name="supportedMediaTypes"> 18 <list> 19 <value>text/html;charset=UTF-8</value> 20 </list> 21 </property> 22 </bean> 23 <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> 24 <bean 25 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 26 <property name="messageConverters"> 27 <list> 28 <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> 29 </list> 30 </property> 31 </bean> 32 <!-- 定义跳转的文件的前后缀 ,视图模式配置--> 33 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 34 <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> 35 <property name="prefix" value="/WEB-INF/jsp/" /> 36 <property name="suffix" value=".jsp" /> 37 </bean> 38 39 <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> 40 <bean id="multipartResolver" 41 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 42 <!-- 默认编码 --> 43 <property name="defaultEncoding" value="utf-8" /> 44 <!-- 文件大小最大值 --> 45 <property name="maxUploadSize" value="10485760000" /> 46 <!-- 内存中的最大值 --> 47 <property name="maxInMemorySize" value="40960" /> 48 </bean> 49 50 </beans>
2. 配置web.xml文件,代码如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 version="3.0"> 6 <display-name>Archetype Created Web Application</display-name> 7 <!-- Spring和mybatis的配置文件 --> 8 <context-param> 9 <param-name>contextConfigLocation</param-name> 10 <param-value>classpath:spring-mybatis.xml</param-value> 11 </context-param> 12 <!-- 编码过滤器 --> 13 <filter> 14 <filter-name>encodingFilter</filter-name> 15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 16 <async-supported>true</async-supported> 17 <init-param> 18 <param-name>encoding</param-name> 19 <param-value>UTF-8</param-value> 20 </init-param> 21 </filter> 22 <filter-mapping> 23 <filter-name>encodingFilter</filter-name> 24 <url-pattern>/*</url-pattern> 25 </filter-mapping> 26 <!-- Spring监听器 --> 27 <listener> 28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 29 </listener> 30 <!-- 防止Spring内存溢出监听器 --> 31 <listener> 32 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 33 </listener> 34 35 <!-- Spring MVC servlet --> 36 <servlet> 37 <servlet-name>SpringMVC</servlet-name> 38 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 39 <init-param> 40 <param-name>contextConfigLocation</param-name> 41 <param-value>classpath:spring-mvc.xml</param-value> 42 </init-param> 43 <load-on-startup>1</load-on-startup> 44 <async-supported>true</async-supported> 45 </servlet> 46 <servlet-mapping> 47 <servlet-name>SpringMVC</servlet-name> 48 <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> 49 <url-pattern>/</url-pattern> 50 </servlet-mapping> 51 <welcome-file-list> 52 <welcome-file>/index.jsp</welcome-file> 53 </welcome-file-list> 54 55 </web-app>
3. 新建showUser.jsp文件,代码如下
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <head> 5 <title>测试</title> 6 </head> 7 8 <body> 9 用户名:${user.userName} 10 <br/> 11 年龄:${user.age} 12 </body> 13 </html>
4. 在工程目录src/main/java下建立UserController类,代码如下
1 package com.wwwsealss.controller; 2 3 import javax.annotation.Resource; 4 import javax.servlet.http.HttpServletRequest; 5 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 10 import com.wwwsealss.entity.User; 11 import com.wwwsealss.service.IUserService; 12 13 @Controller 14 @RequestMapping("/user") 15 public class UserController { 16 @Resource 17 private IUserService userService; 18 19 @RequestMapping("/showUser") 20 public String toIndex(HttpServletRequest request,Model model){ 21 int userId = Integer.parseInt(request.getParameter("id")); 22 User user = this.userService.getUserById(userId); 23 24 User user1 = new User(); 25 user1.setUserName("小明"); 26 27 model.addAttribute("user", user); 28 return "showUser"; 29 } 30 }
5. 右键点击工程,Run As -> Run on Server,输入http://localhost:8080/SSMFrameBuild/user/showUser?id=1,得到如下测试结果说明SSM框架已经整合成功!
6. 最终目录结构