SSM框架
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。
Spring
Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。
Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new一个对象,而是让Spring框架帮你来完成这一切。
SpringMVC
SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
mybatis
mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。
SSM框架运行原理
页面发送请求给控制器,控制器调用业务层处理逻辑,逻辑层向持久层发送请求,持久层与数据库交互,后将结果返回给业务层,业务层将处理逻辑发送给控制器,控制器再调用视图展现数据。
SSM框架搭建一个简单的测试项目
1. 配置SpringMVC文件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"
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.xsd">
<context:component-scan base-package="com.senchen"> <!-- 只管理 @Controller -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 试图解析器 springMVC管理的jsp文件位置应该在 /WEB-INF/meto/ -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/meto/"/>
<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="200000000"/>
</bean>
</beans>
2. 配置SpringMVC文件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"
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.xsd">
<context:component-scan base-package="com.senchen"> <!-- 只管理 @Controller -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 试图解析器 springMVC管理的jsp文件位置应该在 /WEB-INF/meto/ -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/meto/"/>
<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="200000000"/>
</bean>
</beans>
3. 加入mybatis配置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="logImpl" value="log4j" />
</settings>
<typeAliases>
<typeAlias alias="Users" type="com.senchen.shop.entity.Users"/> <!-- User类 别名 -->
</typeAliases>
</configuration>
4.加入Log4j配置log4j.properties
### Console ###
log4j.appender.AA=org.apache.log4j.ConsoleAppender
log4j.appender.AA.Target=System.out
log4j.appender.AA.layout=org.apache.log4j.PatternLayout
log4j.appender.AA.layout.ConversionPattern=%p [%C{1}:%L] %m%n
### File ###
log4j.appender.D=org.apache.log4j.FileAppender
log4j.appender.D.File=D://logs/log.log
log4j.appender.D.Append=true
log4j.appender.D.Threshold=DEBUG
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### root level ###
log4j.rootLogger=debug,AA
### spring level ###
log4j.logger.org.springframework=WARN
### your package level ###
log4j.logger.com.senchen=WARN
### your sub package level ###
log4j.logger.com.senchen.shop=debug
log4j.logger.apache.ibatis=debug
5.加入Spring配置app.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:aop="http://www.springframework.org/schema/aop"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.senchen"> <!-- 避免 spring-mvc 再次创建一个Controller 实例 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan> <!-- 只管理 @Component, @Service, @Repository -->
<aop:aspectj-autoproxy/>
<!-- 代替mybatis配置 读取 数据库连接配置 -->
<context:property-placeholder location="classpath:dbConfig.properties"/>
<!-- 代替mybatis配置 spring管理数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${myDriver}"/>
<property name="url" value="${myUrl}"/>
<property name="username" value="${myUname}"/>
<property name="password" value="${myPwd}"/>
</bean>
<!-- 代替mybatis配置 spring管理 mybatis SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:myBatis.cfg.xml"/>
<property name="mapperLocations" value="classpath:com/senchen/shop/mapper/*.xml"/>
</bean>
<!-- 代替mybatis配置 spring管理 mybatis Dao的实现类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.senchen.shop.dao" />
</bean>
</beans>
6.加入数据源文件dbConfig.properties
myDriver=com.mysql.jdbc.Driver
myUrl=jdbc:mysql://localhost:3306/elm
myUname=root
myPwd=root
7.项目配置web.xml加入Spring,Spring MVC
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<!-- spring文档位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app*.xml</param-value>
</context-param>
<!-- 读spring文档位置 相对于 ioc = new ClassPathXMLApplicationContext( contextConfigLocation )
application.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ioc);
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>xxyyzz</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>
</servlet>
<servlet-mapping>
<servlet-name>xxyyzz</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
8.创建控制器SsmTestController.java,调用业务层接口SsmTestService.java
package com.senchen.shop.controller;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.senchen.shop.entity.Users;
import com.senchen.shop.svs.SsmTestService;
@Controller
public class SsmTestController {
Logger log = Logger.getLogger( SsmTestController.class);
@Resource
SsmTestService tSvs;
//测试URL /ssm.do
@RequestMapping("/ssm")
public String m1(Model md){
log.debug("访问到spring mvc...");
List<Users> list = tSvs.findAllUser();
log.debug("\tspring 已注入service 查询出 " +( null!=list?list.size():-1 ));
md.addAttribute("datas", list);
return "ssm_test";
}//m1
}
9. 创建业务层接口SsmTestService.java,和业务层实现类SsmTestServiceImpl.java,业务层实现类调用数据访问层接口SsmTestDao.java
package com.senchen.shop.svs;
import java.util.List;
import org.springframework.stereotype.Service;
import com.senchen.shop.entity.Users;
public interface SsmTestService {
public List<Users> findAllUser()throws RuntimeException;
}
package com.senchen.shop.svs.impl;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.senchen.shop.dao.SsmTestDao;
import com.senchen.shop.entity.Users;
import com.senchen.shop.svs.SsmTestService;
@Service
public class SsmTestServiceImpl implements SsmTestService{
Logger log = Logger.getLogger( this.getClass());
@Resource
SsmTestDao tdao;
@Override
public List<Users> findAllUser() throws RuntimeException {
log.debug("\tspring 已注入tdao ");
return tdao.selectTest();
}
}
10. 建立数据访问层接口SsmTestDao.java
package com.senchen.shop.dao;
import java.util.List;
import com.senchen.shop.entity.Users;
public interface SsmTestDao {
public List<Users> selectTest()throws RuntimeException;
}
11. 建立实体类Users和其专属映射文件SsmTestMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.senchen.shop.dao.SsmTestDao">
<select id="selectTest" resultType="Users">
select * from users
</select>
</mapper>
12.建立测试跳转的页面ssm_test.jsp在MVC定义的跳转路径WEB-INF/meto下,接收Controller存入的数据并显示
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page.111 <br>
<table border="1">
<tr>
<th>序号</th>
<th>姓名</th>
<th>手机号</th>
<th>邮箱</th>
</tr>
<c:if test="${ !empty datas }">
<c:forEach items="${datas}" var="u" varStatus="st">
<tr>
<td>${st.count}</td>
<td>${u.uname}</td>
<td>${u.uphone}</td>
<td>${u.uemail}</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
13.在浏览器地址栏输入测试URL进行测试
控制台显示查到七行数据:
页面显示: