1、创建一个Maven Web项目
2、pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.alex</groupId><artifactId>webdemo</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>webdemo Maven Webapp</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><junit.version>4.12</junit.version><spring.version>4.0.0.RELEASE</spring.version><mybatis.version>3.4.1</mybatis.version><mybatis-generator.version>1.3.2</mybatis-generator.version><mybatis-spring.version>1.3.0</mybatis-spring.version><mysql.version>5.1.37</mysql.version><c3p0.version>0.9.5.2</c3p0.version><fastjson.version>1.2.31</fastjson.version><slf4j.version>1.7.7</slf4j.version><log4j.version>1.2.17</log4j.version><taglibs.version>1.1.2</taglibs.version><jack.version>2.7.3</jack.version><aglibs-standard.version>1.2.1</aglibs-standard.version></properties><dependencies> <dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>4.0.6.RELEASE</version></dependency><dependency><groupId>net.sourceforge.cglib</groupId><artifactId>com.springsource.net.sf.cglib</artifactId><version>2.2.0</version></dependency><dependency><groupId>org.aopalliance</groupId><artifactId>com.springsource.org.aopalliance</artifactId><version>1.0.0</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>com.springsource.org.aspectj.weaver</artifactId><version>1.6.8.RELEASE</version></dependency><dependency><groupId>net.sf.jsqlparser</groupId><artifactId>jsqlparser</artifactId><version>0.9.5</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1.3</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.0.0</version></dependency><dependency><groupId>org.apache.taglibs</groupId><artifactId>taglibs-standard-impl</artifactId><version>${aglibs-standard.version}</version></dependency><dependency><groupId>org.apache.taglibs</groupId><artifactId>taglibs-standard-spec</artifactId><version>${aglibs-standard.version}</version></dependency><!-- 单元测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version></dependency><!-- 反向生成 --><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>${mybatis-generator.version}</version></dependency><!-- 验证 --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>5.2.4.Final</version></dependency><!--json所需要的依赖 开始 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jack.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jack.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>${jack.version}</version></dependency><!--json所需要的依赖 结束 --><dependency><groupId>javax.validation</groupId><artifactId>validation-api</artifactId><version>2.0.1.Final</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.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-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-expression</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</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-orm</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-beans</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</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-test</artifactId><version>${spring.version}</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>${mybatis-spring.version}</version></dependency><!-- 导入Mysql数据库链接jar包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</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.mchange</groupId><artifactId>c3p0</artifactId><version>${c3p0.version}</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>${taglibs.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j.version}</version></dependency></dependencies><build><finalName>ssmajaxmaven</finalName><plugins><!-- Run As → Maven Build → tomcat7:run -Dmaven.tomcat.port=8080 --><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version><configuration><!-- 指定端口 --><port>8080</port><!-- 请求路径 --><path>/ssmajaxmaven</path><ignorePackaging>true</ignorePackaging></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-dependency-plugin</artifactId><version>2.10</version><executions><execution><id>copy</id><phase>install</phase><goals><goal>copy-dependencies</goal></goals><configuration><outputDirectory>${project.build.directory}/lib</outputDirectory></configuration></execution></executions></plugin></plugins></build>
</project>
3、log4j.properties
log4j.rootLogger = info,stdout,R
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} %5p --- [%t] %-c(line:%L) : %m%n# log4j.appender.R = org.apache.log4j.RollingFileAppender
log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File = spring.log
log4j.appender.R.Append = true
# 输出DEBUG级别以上的日志
log4j.appender.R.Threshold = debug
#log4j.appender.R.MaxFileSize = 1024KB
#log4j.appender.R.MaxBackupIndex = 50
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
4、mybatis.sql
/*
Navicat MySQL Data TransferSource Server : localhost
Source Server Version : 50515
Source Host : localhost:3306
Source Database : mybatisTarget Server Type : MYSQL
Target Server Version : 50515
File Encoding : 65001Date: 2019-10-16 14:38:06
*/SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for tbl_dept
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (`id` int(11) NOT NULL AUTO_INCREMENT,`department_name` varchar(50) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of tbl_dept
-- ----------------------------
INSERT INTO `tbl_dept` VALUES ('1', '开发部');
INSERT INTO `tbl_dept` VALUES ('2', '测试部');
INSERT INTO `tbl_dept` VALUES ('3', '财务部');
INSERT INTO `tbl_dept` VALUES ('4', '人事部');-- ----------------------------
-- Table structure for tbl_employee
-- ----------------------------
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (`id` int(11) NOT NULL AUTO_INCREMENT,`last_name` varchar(50) DEFAULT NULL,`email` varchar(50) DEFAULT NULL,`gender` char(1) DEFAULT NULL,`d_id` int(11) DEFAULT NULL,PRIMARY KEY (`id`),KEY `fk_emp_dept` (`d_id`),CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of tbl_employee
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('1001', 'Tom', 'Tom@aliyun.com', '1', '1');
INSERT INTO `tbl_employee` VALUES ('1002', 'Rose', 'rose@aliyun.com', '0', '2');
INSERT INTO `tbl_employee` VALUES ('1003', 'Alex', 'alex@qq.com', '1', '3');
INSERT INTO `tbl_employee` VALUES ('1004', 'Thone', 'Thone@aliyun.com', '0', '4');
INSERT INTO `tbl_employee` VALUES ('1005', 'Jerry', 'jerry@aliyun.com', '1', '2');
5、generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><!-- targetRuntime: 指定生成的逆向工程的版本MyBatis3: 生成带条件的增删改查.MyBatis3Simple: 生成基本的增删改查.--><context id="DB2Tables" targetRuntime="MyBatis3"><!-- 数据库的连接 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis"userId="root"password="YingGu2020!"></jdbcConnection><!-- 指定javabean的生成策略 targetPackage: 指定包targetProject: 指定工程--><javaModelGenerator targetPackage="com.alex.ssm.entity" targetProject=".\src\main\java"><!-- 是否对model添加 构造函数 --><property name="constructorBased" value="true"/><!-- TODO 是否允许子包,即targetPackage.schemaName.tableName --><property name="enableSubPackages" value="true"/><!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --><!--<property name="immutable" value="true"/>--><!-- 给Model添加一个父类 --><!-- <property name="rootClass" value="com.foo.louis.Hello"/>--><!-- TODO 是否对类CHAR类型的列的数据进行trim操作 --><property name="trimStrings" value="true"/></javaModelGenerator><!-- sql映射的生成策略 --><sqlMapGenerator targetPackage="com.alex.ssm.mapper" targetProject=".\src\main\resources"><property name="enableSubPackages" value="true" /></sqlMapGenerator><!-- mapper接口的生成策略 --><javaClientGenerator type="XMLMAPPER" targetPackage="com.alex.ssm.mapper" targetProject=".\src\main\java"><property name="enableSubPackages" value="true" /></javaClientGenerator><!-- 指定逆向分析的表 --><table tableName="tbl_dept" domainObjectName="Department"></table><table tableName="tbl_employee" domainObjectName="Employee"></table></context>
</generatorConfiguration>
6、MyBatisTestMBG.java
package com.alex.ssm.test;import java.io.File;
import java.util.ArrayList;
import java.util.List;import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;public class MyBatisTestMBG {@Testpublic void createMBG() throws Exception {List<String> warnings = new ArrayList<String>();boolean overwrite = true;File configFile = new File("src/main/resources/generatorConfig.xml");ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(configFile);DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);myBatisGenerator.generate(null);}
}
7、mybatis-configmbg.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- MyBatis的全局配置文件 -->
<configuration><!-- properties: 引入外部化的配置文件resource: 加载类路径下的资源文件url: 加载网络路径或者是磁盘路径下的资源文件--><properties resource="db.properties" ></properties><!-- settings:包含很多重要的设置项,可以改变MyBatis框架的运行行为setting:具体的一个设置项name: 设置项的名称value:设置项的取值--><settings><!-- 映射下划线到驼峰命名 last_name ==> lastName --><setting name="mapUnderscoreToCamelCase" value="true"/><!-- 开启延迟加载 --><setting name="lazyLoadingEnabled" value="true"/><!-- 指定加载的属性是按需加载. --><setting name="aggressiveLazyLoading" value="false"/><!-- 二级缓存 --><setting name="cacheEnabled" value="true"/></settings><!-- typeAliases别名处理,给java类型取别名(简短)typeAlias:给单个的java类型取别名type:指定java类型(全类名)alias:指定别名。默认的别名是类名的首字母小写. 别名不区分大小写.package:批量取别名,给指定的包下的所有的类取默认的别名name:指定包名--><typeAliases><!-- <typeAlias type="com.alex.mybatis.entity.Employee" alias="employee"/> --><package name="com.alex.ssm.entity"/></typeAliases><!-- environments: 环境们。 支持配置多个环境. 通过default来指定具体使用的环境.environment: 具体的一个环境配置,必须包含transactionManager,dataSource。id: 当前环境的唯一标识.transactionManager: 事务管理器.JDBC: JdbcTransactionFactory将来事务管理会交给Spring的声明式事务.@TrancationdataSource:数据源.POOLED: PooledDataSourceFactory将来数据源交给Spring管理,使用c3p0或者dbcp等--><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></dataSource></environment><environment id="test"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></dataSource></environment></environments><!-- mappers:引入sql映射文件mapper:引入单个的sql映射文件package: 批量引入sql映射文件 要求: sql映射文件的名字与Mapper接口的名字一致.并且在同一目录下.--><mappers><!-- <mapper resource="EmployeeMapper.xml" /> --><package name="com.alex.ssm.mapper"/></mappers></configuration>
8、db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/blue?allowMultiQueries=true
jdbc.username=root
jdbc.password=YingGu2020!
jdbc.initialPoolSize=30
jdbc.minPoolSize=10
jdbc.maxPoolSize=100
jdbc.acquireIncrement=5
jdbc.maxStatements=1000
jdbc.maxStatementsPerConnection=10
9、MyBatisTestMBGCRUD
package com.alex.ssm.test;import java.io.InputStream;
import java.util.List;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import com.alex.ssm.entity.Employee;
import com.alex.ssm.entity.EmployeeExample;
import com.alex.ssm.entity.EmployeeExample.Criteria;
import com.alex.ssm.mapper.EmployeeMapper;public class MyBatisTestMBGCRUD {public SqlSessionFactory getSqlSessionFactory() throws Exception {String resource = "mybatis-configmbg.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);System.out.println(sqlSessionFactory);return sqlSessionFactory;}// 根据id查询@Testpublic void testMBG01() throws Exception {SqlSessionFactory ssf = getSqlSessionFactory();SqlSession session = ssf.openSession();try {EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);Employee employee = mapper.selectByPrimaryKey(1001);System.out.println(employee);} finally {session.close();}}// 没有条件的情况,查询全部信息@Testpublic void testMBG02() throws Exception {SqlSessionFactory ssf = getSqlSessionFactory();SqlSession session = ssf.openSession();try {EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);List<Employee> emps = mapper.selectByExample(null);for (Employee employee : emps) {System.out.println(employee);}} finally {session.close();}}// 按照条件查询@Testpublic void testMBG03() throws Exception {SqlSessionFactory ssf = getSqlSessionFactory();SqlSession session = ssf.openSession();try {EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);// 查询员工名字中带有e字母 和员工性别是2的 或者email中带有y字母的EmployeeExample example = new EmployeeExample();Criteria criteria = example.createCriteria();criteria.andLastNameLike("%e%");criteria.andGenderEqualTo("0");// or的条件需要重新使用一个Criteria对象Criteria criteria2 = example.createCriteria();criteria2.andEmailLike("%y%");// 对于封装or条件的criteria,需要or到exampleexample.or(criteria2);List<Employee> emps = mapper.selectByExample(example);for (Employee employee : emps) {System.out.println(employee);}} finally {session.close();}}
}
10、web.xml
<?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"><!-- name --><display-name>Archetype Created Web Application</display-name><!-- 加载上下文 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context.xml</param-value></context-param><!-- 监听 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 编码过滤器 --><filter><filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 支持 rest 风格 --><filter><filter-name>HiddenHttpMethodFilter</filter-name><filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class></filter><filter-mapping><filter-name>HiddenHttpMethodFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 视图解析 --><servlet><servlet-name>springDispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc-context.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springDispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- welcome --><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>
11、mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- MyBatis的全局配置文件 -->
<configuration> <settings><!-- 映射下划线到驼峰命名 last_name ==> lastName --><setting name="mapUnderscoreToCamelCase" value="true"/><!-- 开启延迟加载 --><setting name="lazyLoadingEnabled" value="true"/><!-- 指定加载的属性是按需加载. --><setting name="aggressiveLazyLoading" value="false"/><!-- 二级缓存 --><setting name="cacheEnabled" value="true"/></settings> <typeAliases><package name="com.alex.ssm.entity"/></typeAliases> <plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"><property name="helperDialect" value="mysql"/><!-- 使用下面的方式配置参数,后面会有所有的参数介绍 --><property name="pageSize" value="true"/></plugin></plugins></configuration>
12、spring-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"><!-- 开启注解扫描 --><context:component-scan base-package="com.alex.ssm"><!-- Springmvc管理的,Spring就不管理 --><context:exclude-filter type="annotation"expression="org.springframework.stereotype.Controller" /></context:component-scan><!-- 读取外部文件 --><context:property-placeholder location="classpath:/db.properties" /><!-- C3P0 数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="jdbcUrl" value="${jdbc.url}" /><property name="driverClass" value="${jdbc.driver}" /><property name="initialPoolSize" value="${jdbc.initialPoolSize}" /><property name="minPoolSize" value="${jdbc.minPoolSize}" /><property name="maxPoolSize" value="${jdbc.maxPoolSize}" /><property name="acquireIncrement" value="${jdbc.acquireIncrement}" /><property name="maxStatements" value="${jdbc.maxStatements}" /><property name="maxStatementsPerConnection" value="${jdbc.maxStatementsPerConnection}" /></bean><!-- 事务切面 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 开启基于注解的声明式事务 transaction-manager="transactionManager" 默认值,可以省略. --><tx:annotation-driven transaction-manager="transactionManager" /><!-- 整合 MyBatis MyBatis的配置都可以在Spring里面配置,但是尽量把MyBatis独有的还是放在MyBatis配置文件里--><bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入数据源 --><property name="dataSource" ref="dataSource" ></property><!-- 指定MyBatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis-config.xml"></property><!-- 指定sql映射文件 --><property name="mapperLocations" value="classpath:com/alex/ssm/mapper/*.xml"></property></bean><!-- 扫描所有mapper接口,批量生成代理实现类,交给Spring容器来管理 --><!-- 这是老版本的配置方式,没办法指定ID,ID默认是类的首字母小写 --><!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.alex.ssm.mapper"></property></bean>--><!-- 扫描所有mapper接口,批量生成代理实现类,交给Spring容器来管理 --><!-- 新方式 , 两种方式,使用哪一种都可以--><mybatis-spring:scan base-package="com.alex.ssm.mapper"/></beans>
13、springmvc-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:jdbc="http://www.springframework.org/schema/jdbc"xmlns:util="http://www.springframework.org/schema/util"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"><!-- TODO 注解扫描 --><context:component-scan base-package="com.alex.ssm" use-default-filters="false"><!-- TODO 只扫描SpringMVC相关的组件 --><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!-- TODO 视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"></property><property name="suffix" value=".jsp"></property></bean><!-- TODO @ResponseBody 转化json --><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><!-- TODO json视图拦截器,读取到@ResponseBody的时候去配置它 --><ref bean="mappingJacksonHttpMessageConverter" /></list></property></bean><!-- TODO json转化器,它可以将结果转化 --><bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="supportedMediaTypes"><list><value>application/json;charset=UTF-8</value></list></property></bean><mvc:default-servlet-handler/><mvc:annotation-driven/>
</beans>
14、EmployeeController
package com.alex.ssm.controller;import java.util.List;
import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;import com.alex.ssm.entity.Employee;
import com.alex.ssm.service.EmployeeService;@Controller
@RequestMapping("/emp")
public class EmployeeController {@Autowiredprivate EmployeeService employeeService ;@RequestMapping(value="/emplist",method=RequestMethod.GET)public String listEmps(Map<String,Object> map) {List<Employee> emps = employeeService.getAllEmps();map.put("emps",emps);return "list";}@RequestMapping("/emplistview")public ModelAndView listEmpsview() {ModelAndView mv = new ModelAndView();List<Employee> emps = employeeService.getAllEmps();mv.addObject("emps", emps);mv.setViewName("list"); return mv;}@RequestMapping("/emplistjson")@ResponseBodypublic List<Employee> listEmpsJson() {List<Employee> emps = employeeService.getAllEmps();return emps;}@RequestMapping("/emplistajax")public ModelAndView listEmpsajax(String id) {System.err.println("id ---->" + id);ModelAndView mv = new ModelAndView();List<Employee> emps = employeeService.getAllEmps();mv.addObject("emps", emps);mv.setViewName("list"); return mv;}@RequestMapping("/empaaa")public String listEmpsajax1(Map<String,Object> map) {map.put("name", "alex");return "a";}
}
15、EmployeeService
package com.alex.ssm.service;import java.util.List;import com.alex.ssm.entity.Employee;public interface EmployeeService {public List<Employee> getAllEmps();
}
16、EmployeeServiceImpl
package com.alex.ssm.serviceimpl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.alex.ssm.entity.Employee;
import com.alex.ssm.entity.EmployeeExample;
import com.alex.ssm.mapper.EmployeeMapper;
import com.alex.ssm.service.EmployeeService;@Service
public class EmployeeServiceImpl implements EmployeeService{@Autowiredprivate EmployeeMapper employeeMapper ;@Overridepublic List<Employee> getAllEmps() {List<Employee> example = employeeMapper.selectByExample(new EmployeeExample());return example;}}
17、FastJsonUtil
package com.alex.ssm.util;import java.util.List;import com.alibaba.fastjson.JSON;//针对泛型不能封装Map
public class FastJsonUtil {/*** 任意对象转json字符串*/public static String object_to_json(Object object) {return JSON.toJSONString(object);}/*** json字符串转普通java对象*/public static <T> T json_to_object(String json, Class<T> clazz) {return JSON.parseObject(json, clazz);}/*** json字符串转List对象* @param <T>*/public static <T> List<T> json_to_list(String json, Class<T> clazz) {return JSON.parseArray(json, clazz);}
}
18、index.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>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<style type="text/css">.local_courseList {color: red;}
</style>
</head>
<body><a href="${pageContext.request.contextPath}/emp/emplist">List ALL Emps Map</a><br/><br/><br/><a href="emp/emplistview">List ALL Emps ModelAndView</a><br/><br/><br/><a href="emp/emplistjson">List ALL Emps Json</a><br/><br/><br/><a href="emp/empaaa">List ALL Emps AAAA</a><br/><br/><br/><a href="#" onclick="ajaxview();">显示信息 jquery ajax view 写法</a><br/><br/><br/><a href="#" id="showData">显示信息 jquery ajax json 写法</a><br/><br/><br/><div id="empdata"></div><br/><br/><br/><script type="text/javascript">function ajaxview() {var empdata = "id=1";$.ajax({url : "emp/emplistajax",data : empdata,type : "post",success : function(result) {$("#empdata").html(result);},error : function(result) {$("#empdata").html("error");}});}$(document).ready(function() {$("#showData").click(function() {var empdata = "id=1";$.ajax({url : "emp/emplistjson",data : empdata,type : "post",success : function(result) {console.info(result);console.info(result[0].lastName);var kyhtml = '';kyhtml += '<div class="local_courseList">';kyhtml += result[0].lastName;kyhtml += '</div>';$("#empdata").html(kyhtml);},error : function(result) {$("#empdata").html("error");}});});});</script>
</body>
</html>
19、list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 导入JSTL标签库 -->
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body><h1 align="center" >员工信息列表</h1><table border="1px" width="70%" cellspacing="0px" align="center"><tr><th>ID</th><th>LastName</th><th>Email</th><th>Gender</th><!-- <th>DeptName</th> --><th>Operation</th></tr><!-- items:指定要迭代的集合 var:代表当前迭代出的对象--> <c:forEach items="${requestScope.emps}" var="emp"><tr align="center"><td>${emp.id }</td><td>${emp.lastName }</td><td>${emp.email }</td><td>${emp.gender==0?'女':'男' }</td><%-- <td>${emp.dept.departmentName}</td> --%><td><a href="#">Edit</a> <a href="#">Delete</a></td></tr></c:forEach></table>
</body>
</html>
20、a.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>Insert title here</title>
</head>
<body>${name}
</body>
</html>