11、基本概念
1.1、Spring
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
1.2、SpringMVC
Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
1.3、MyBatis
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
2、SSM整合
1.完整目录结构如下(创建的是Maven-web工程):
2.Maven中需要添加的依赖(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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sxt</groupId> <artifactId>mybatis.12.ssm</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.21.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.21.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.21.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.21.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>test</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.4</version> </dependency> </dependencies> <build> <plugins> <!-- tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!-- 端口号 --> <port>80</port> <!-- /表示访问路径 省略项目名 --> <path>/</path> <!-- 设置编码方式 --> <uriEncoding>utf-8</uriEncoding> </configuration> </plugin> </plugins> </build> </project>
3.配置web.xml文件(文件路径:/mybatis.12.ssm/src/main/webapp/WEB-INF/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_2_5.xsd" id="WebApp_ID" version="2.5" > <!-- 配置spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <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> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</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> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> </web-app>
4.配置spring-mvc.xml文件
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <context:component-scan base-package="com.sxt.controller"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> </beans>
5.配置applicationContext.xml文件
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 关联数据属性文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 开启扫描 --> <context:component-scan base-package="com.sxt.service.impl"/> <!-- 配置数据源 --> <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource" > <property name="driverClass" value="${driverName}"></property> <property name="jdbcUrl" value="${url}"></property> <property name="user" value="${names}"></property> <property name="password" value="${password}"></property> </bean> <!-- 整合mybatis --> <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactoryBean" > <!-- 关联数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 关联mybatis的配置文件 --> <property name="configLocation" value="classpath:mybatis-cfg.xml"/> <!-- 添加别名设置 --> <property name="typeAliasesPackage" value="com.sxt.pojo"/> </bean> <!-- 配置扫描的路径 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" > <property name="basePackage" value="com.sxt.mapper"/> </bean> </beans>
6.配置db.properties文件(本人数据库名称是j0325,用户名是root,密码是123)
# 开发环境
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/j0325?characterEncoding=utf-8
names=root
password=123
# 测试环境
#driverName=com.mysql.jdbc.Driver
#url=jdbc:mysql://localhost:3306/j0325?characterEncoding=utf-8
#userName=root
#password=123456
# 生产环境
#driverName=com.mysql.jdbc.Driver
#url=jdbc:mysql://localhost:3306/j0325?characterEncoding=utf-8
#userName=root
#password=123456
7.配置mybatis-cfg.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="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings> </configuration>
8.配置mybatis-generator.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="C: oolsmaven-repositorymysqlmysql-connector-java5.1.27mysql-connector-java-5.1.27.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <!-- 去掉生成文件中的注释 --> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库链接URL、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/j0325" userId="root" password="123"> </jdbcConnection> <!-- <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:XE" userId="car" password="car"> </jdbcConnection> --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="com.sxt.pojo" targetProject="mybatis.13.springsrcmainjava"> <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的映射文件包名和位置 --> <sqlMapGenerator targetPackage="com.sxt.mapper" targetProject="mybatis.13.springsrcmainjava"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.sxt.mapper" targetProject="mybatis.13.springsrcmainjava"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <table tableName="t_user" domainObjectName="UserBean" ></table> </context> </generatorConfiguration>
9.配置log4j.properties日志信息文件
log4j.rootCategory=INFO, stdout , R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=C:\tools\logs\dpb.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n
3、数据测试
1.创建IUserService接口
package com.sxt.service; import java.util.List; import com.sxt.pojo.UserBean; public interface IUserService { public List<UserBean> query(); public Integer insert(UserBean user); public Integer update(UserBean user); public Integer delete(Integer id); }
2.创建UserServiceImpl
package com.sxt.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sxt.mapper.UserBeanMapper; import com.sxt.pojo.UserBean; import com.sxt.pojo.UserBeanExample; import com.sxt.service.IUserService; @Service public class UserServiceImpl implements IUserService{ @Resource private UserBeanMapper mapper; @Override public List<UserBean> query() { // TODO Auto-generated method stub UserBeanExample example = new UserBeanExample(); return mapper.selectByExample(example); } @Override public Integer insert(UserBean user) { // TODO Auto-generated method stub return mapper.insertSelective(user); } @Override public Integer update(UserBean user) { // TODO Auto-generated method stub return mapper.updateByPrimaryKeySelective(user); } @Override public Integer delete(Integer id) { // TODO Auto-generated method stub return mapper.deleteByPrimaryKey(id); } }
3.创建UserController(本人简单实现了下查询功能,需要实现其他功能请自行添加)
package com.sxt.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.sxt.service.IUserService; @Controller public class UserController { @Resource private IUserService userService; @RequestMapping("/query") public String query(Model m) { m.addAttribute("list", userService.query()); return "/user.jsp"; } }
4.创建user.jsp(WEB-INF下面创建)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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>用户管理</h1> <c:forEach items="${list }" var="u"> ${u.id } -- ${u.name }--${u.age }<br> </c:forEach> </body> </html>
5.运行
6.浏览器输入localhost:80/query