1.SpringMVC:是一个表现层框架,
作用:从请求中接收传入的参数,将处理后的结果数据返回给页面展示。
下图是SpringMVC的工作流程图:
下面示范一个入门案例:
2.ssm整合:
- Dao层
- pojo和映射文件以及接口使用逆向工程生成
- SqlMapConfig.xml mybatis核心配置文件
- ApplicationContext-dao.xml 整合后spring在dao层的配置
- 数据源
- 会话工厂
- 扫描Mapper
- service层
- 事务 ApplicationContext-trans.xml
- @Service注解扫描 ApplicationContext-service.xml
- controller层
- SpringMVC.xml
- 注解扫描 :扫描@Controller注解
- 注解驱动:替我们显示的配置了最新版本的处理器映射器和处理器适配器
- 视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径
- SpringMVC.xml
- web.xml
- springMVC前端控制器配置
- spring监听
下面是一个SSM整合的小案例。
一、程序的目录结构
二、依次配置ApplicationContext-dao.xml,ApplicationContext-service.xml,ApplicationContext-trans.xml
ApplicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd"><!-- 加载配置文件 -->
<context:property-placeholder
location="classpath:db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" /> <!-- 这个地方是引入db.properties里面的 -->
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean><!-- mapper配置 -->
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
</bean>
<!-- 配置Mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name = "basePackage"
value="com.dao" />
</bean></beans>
ApplicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- @Service扫描 -->
<context:component-scan base-package="com.service"></context:component-scan></beans>
ApplicationContext-trans.xml 事务配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 这里面是事务 -->
<!-- 事务管理器 -->
<bean id = "transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name = "dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id = "txAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name = "save*" propagation="REQUIRED" />
<tx:method name = "insert*" propagation="REQUIRED" />
<tx:method name = "delete*" propagation="REQUIRED" />
<tx:method name = "update*" propagation="REQUIRED" />
<tx:method name = "find*" propagation="SUPPORTS"
read-only="true" />
<tx:method name = "get*" propagation="SUPPORTS"
read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref = "txAdvice"
pointcut="execution(* com.service.*.*(..))" /> <!--这里是对service层-->
</aop:config>
</beans>
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
SpringMVC.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:dubbo="http://code.alibabatech.com/schema/dubbo"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- @Controller注解扫描 -->
<context:component-scan
base-package="com.controller"></context:component-scan><!-- 注解驱动 替我们显式地配置了最新版的注解处理器映射器和处理器适配器 -->
<mvc:annotation-driven></mvc:annotation-driven><!-- 配置视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 真正的页面路径=前缀+ 去掉后缀名的页面名 + 后缀 --> <!-- "/WEB-INF/jsp/itemList.jsp"); -->
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean></beans>
SqlMapConfig.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>
</configuration>
三、com.dao 与com.pojo是用的mybatis逆向工程产生的事例代码。
四、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监听 -->
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- *通配符 把config里面那三个都扫描进来 -->
<param-value>classpath:ApplicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc前端控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 如果web.xml 与SpringMVC.xml没放一起,就加这段 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringMVC.xml</param-value>
</init-param>
<!-- 在tomcat启动的时候就加载这个servlet -->
<load-on-startup>1</load-on-startup>
</servlet><servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping><!-- 解决乱码问题 -->
<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></web-app>
以上就是ssm框架整合所需要的配置。
五、itemList.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/search.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemList }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
六、ItemServiceImple 实现类:
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.ItemsMapper;
import com.pojo.Items;
import com.pojo.ItemsExample;
@Service
public class ItemsServiceImpl implements ItemsService{
//注入dao层
@Autowired
private ItemsMapper itemsMapper;
@Override
public List<Items> list() throws Exception {
//如果不需要任何查询条件,直接将example对象new出来即可
ItemsExample example=new ItemsExample();
List<Items> list = itemsMapper.selectByExampleWithBLOBs(example);
return list;
}
//通过id获取item
@Override
public Items findItemsById(Integer id) throws Exception {
Items items = itemsMapper.selectByPrimaryKey(id);
return items;
}
@Override
public void updateItems(Items items) throws Exception {
itemsMapper.updateByPrimaryKeyWithBLOBs(items);
}
}
七:ItemsController类
package com.controller;
@Controller
public class ItemsController {
// 注解 把service类注入
@Autowired
private ItemsService itemsService;
@RequestMapping("/list")
public ModelAndView itemsList() throws Exception {
List<Items> list = itemsService.list();
ModelAndView modelandview = new ModelAndView();
modelandview.addObject("itemList", list);
// 返回到itemList.jsp这个页面
modelandview.setViewName("itemList");
return modelandview;
}
/**
* 1.SpringMVC中默认支持的参数类型,在controller中加不加看自己的需要,看下面的response,session没用到可以不需
* HttpServletRequest
* HttpServletRequest
* HttpSession
* Model
*
*/
@RequestMapping("itemEdit")
public String itemEdit(HttpServletRequest request, HttpServletRequest response, HttpSession session, Model model)
throws Exception {
// 获取传过来的参数是id
String idStr = request.getParameter("id");
Items items = itemsService.findItemsById(Integer.parseInt(idStr));
// Model模型:模型中放入了返回给页面的数据
// model底层其实就是用的request域来传递数据,但对request域进行了扩展
model.addAttribute("item", items);
// 如果springMVC方法返回一个简单的string字符串,那么springmvc就会认识这个字符串就是页面的名称
return "editItem";
}
/**
* 2.还能接收基本数据类型,包括string,springmvc自动进行类型转换
* controller方法接收的参数的变量名称必须要等于页面上input框的name属性值
*/
@RequestMapping("/updateitem")
public String update(Integer id,String name,Float price,String detail) throws Exception{
Items items=new Items();
items.setId(id);
items.setName(name);
items.setPrice(price);
items.setDetail(detail);
items.setCreatetime(new Date());
itemsService.updateItems(items);
return "success";
}
}
八:运行Tomcat
数据查询成功!
总结:
整个运行过程:
当tomcat启动时,首先加载web.xml,在web.xml中加载ApplicationContext-*.xml的三个配置文件,在ApplicationContext-dao.xml里面又加载:db.properties,SqlMapConfig.xml. 之后扫描dao,把该创建的实例都创建出来后。最后通过前端控制器的方式加载SpringMVC.xml,这样的话所有的东西都加载出来了。