演示一个简单的SSM框架搭建流程,(所用内容:Spring+SpringMVC+Mybatis+Dbcp数据源+log4j(mybatis使用))
搭建好的框架:
http://pan.baidu.com/s/1ntY8iJf
主要用到以下包
1.Spring框架 + Springmvc包
2.Springmvc+mybatis整合包 (mybatis提供,之前由Spring提供) mybatis-spring.1.2.2.jar
3.Mybatis包
4.Dbcp包
5.Junit包
步骤
1.拷贝所需要的包到WEB-INF/lib 文件夹下面, 并Add classpath
2.配置数据库: 利用配置文件 db.properties
3.配置log4j 实用配置文件 log4j.properties
4.配置Mybatis (mybatis目录下SqlMapConfig.xml)
5.配置Spring与SpringMvc(spring目录下
(1)applicationContext-dao.xml, //配置Dao,数据连接池等。。
(2)applicationContext-service.xml, //配置service.利用配置文件的方式配置配置service
(3)applicationContext-transaction.xml. //在service进行事务控制
(4)springmvc.xml) //配置注解驱动(包含注解映射器,注解适配器..).Controller扫描器,视图解析器(前缀与后缀)
6.编写javaBean(与数据库表对应)可用generator自动生成, javaBean扩展类. vo类
7.利用mapper代理的开发方式,编写mapper.xml,mapper.java
8. 编写Junit测试类 测试Mybatis是否搭建成功9.配置web.xml(springmvc前端控制器,加载Spring容器等)
10.编写service,service-impl,
11.编写controller(Handler调用service)查询数据
12.编写jsp页面,将数据展示出来
13.数据库表 Items表设计
14.Items 中的测试数据
15.最终测试结果(web页面)
文档目录结构
1.拷贝所需要的包到WEB-INF/lib 文件夹下面
2.配置数据库: 利用配置文件 db.properties
db.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
- jdbc.username=root
- jdbc.password=123456
3.配置log4j 实用配置文件 log4j.properties
log4j.properties
- # Global logging configuration
- #\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
- log4j.rootLogger=DEBUG, stdout
- # Console output...
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4.配置Mybatis (mybatis目录下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>
<!-- <settings></settings> -->
<typeAliases>
<!--单个起别名的方法-->
<!-- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> -->
<!-- 批量定义别名 -->
<package name="cn.itcast.ssm.po"/>
</typeAliases>
<mappers>
<!-- Mybatis的包扫描器: 由Spring管理后, 在Spring中进行配置 -->
<!--<package name="cn.itcast.ssm.mapper" /> -->
</mappers>
</configuration>
5.配置Spring与SpringMvc(spring目录下
(1)applicationContext-dao.xml, //配置Dao,数据连接池等。。
(2)applicationContext-service.xml, //配置service.利用配置文件的方式配置配置service
(3)applicationContext-transaction.xml. //在service进行事务控制
(4)springmvc.xml) //配置注解驱动(包含注解映射器,注解适配器..).Controller扫描器,视图解析器(前缀与后缀)
(1)applicationContext-dao.xml, //配置Dao,数据连接池等。。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据源 ,dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="30" />
<property name="maxIdle" value="5" />
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
<property name="basePackage" value="cn.itcast.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
(2)applicationContext-service.xml, //配置service.利用配置文件的方式配置配置service
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 商品管理的service -->
<bean id="itemsService" class="cn.itcast.ssm.service.impl.ItemsServiceImpl" />
</beans>
(3)applicationContext-transaction.xml. //在service进行事务控制
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 dataSource在applicationContext-dao.xml中配置了 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="insert*" 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:method name="select*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* cn.itcast.ssm.service.impl.*.*(..))" />
</aop:config>
</beans>
(4)springmvc.xml) //配置注解驱动(包含注解映射器,注解适配器..).Controller扫描器,视图解析器(前缀与后缀)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 可以扫描controller、service、...
这里让扫描controller,指定controller的包
-->
<context:component-scan base-package="cn.itcast.ssm.controller"></context:component-scan>
<!--注解映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
<!--注解适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
<!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
mvc:annotation-driven默认加载很多的参数绑定方法,
比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
实际开发时使用mvc:annotation-driven
-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 视图解析器
解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包
-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
6.编写javaBean(与数据库表对应)可用generator自动生成, javaBean扩展类. vo类
Items,java
package cn.itcast.ssm.po;
import java.util.Date;
public class Items {
private Integer id;
private String name;
private Float price;
private String pic;
private Date createtime;
private String detail;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}
}
ItemsEx.java
package cn.itcast.ssm.po;
public class ItemsEx extends Items {
}
ItemsExVo
package cn.itcast.ssm.po;
public class ItemsExVo {
private ItemsEx itemsEx;
public ItemsEx getItemsEx() {
return itemsEx;
}
public void setItemsEx(ItemsEx itemsEx) {
this.itemsEx = itemsEx;
}
}
7.利用mapper代理的开发方式,编写mapper.xml,mapper.java
ItemsMapper.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="cn.itcast.ssm.mapper.ItemsExMapper">
<sql id="query_items_where">
<if test="itemsEx!=null">
<if test="itemsEx.name!=null and itemsEx.name!=''">
AND items.name LIKE '%${itemsEx.name}%'
</if>
<if test="itemsEx.price!=null and itemsEx.price!=''">
AND items.price = #{itemsEx.price}
</if>
</if>
</sql>
<!--
<if test="itemsEx.price!=null and itemsEx.price!=''">
AND items.price = #{itemsEx.price}
</if>
-->
<select id="findItemsExList" parameterType="cn.itcast.ssm.po.ItemsExVo" resultType="cn.itcast.ssm.po.ItemsEx">
SELECT items.* FROM items
<where>
<include refid="query_items_where"></include>
</where>
</select>
</mapper>
ItemsEx.java
package cn.itcast.ssm.mapper;
import java.util.List;
import cn.itcast.ssm.po.ItemsEx;
import cn.itcast.ssm.po.ItemsExVo;
public interface ItemsExMapper {
public List<ItemsEx> findItemsExList(ItemsExVo itemsExVo);
}
8.编写Junit测试类 测试Mybatis是否搭建成功
ItemsExMapperTest,java
package cn.itcast.ssm.mapper;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.ssm.po.ItemsEx;
import cn.itcast.ssm.po.ItemsExVo;
public class ItemsExMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext-dao.xml");
}
@Test
public void testFindItemsExList() {
ItemsExMapper itemsExMapper = (ItemsExMapper) applicationContext
.getBean("itemsExMapper");
ItemsExVo itemsExVo = new ItemsExVo();
ItemsEx itemsEx = new ItemsEx();
itemsEx.setPrice(200.0f);
// itemsEx.setName("笔记本");
itemsExVo.setItemsEx(itemsEx);
List<ItemsEx> list = itemsExMapper.findItemsExList(itemsExVo);
System.out.println(list);
}
}
9.配置web.xml(springmvc前端控制器,加载Spring容器等)
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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">
<display-name>Web_SSM_test</display-name>
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/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>
<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析
第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
使用此种方式可以实现 RESTful风格的url
第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- post乱码过虑器 -->
<!--
<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>
-->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
10.编写service,service-impl,(及Service及其实现)
ItemsService.java
package cn.itcast.ssm.service;
import java.util.List;
import cn.itcast.ssm.po.ItemsEx;
import cn.itcast.ssm.po.ItemsExVo;
public interface ItemsService {
public List<ItemsEx> findItemsExList(ItemsExVo itemsExVo) throws Exception;
}
ItemsServiceImpl.java
package cn.itcast.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import cn.itcast.ssm.mapper.ItemsExMapper;
import cn.itcast.ssm.po.ItemsEx;
import cn.itcast.ssm.po.ItemsExVo;
import cn.itcast.ssm.service.ItemsService;
public class ItemsServiceImpl implements ItemsService {
@Autowired
ItemsExMapper itemsExMapper;
@Override
public List<ItemsEx> findItemsExList(ItemsExVo itemsExVo) throws Exception {
return itemsExMapper.findItemsExList(itemsExVo);
}
}
11.编写controller(Handler调用service)查询数据
ItemsController.java
package cn.itcast.ssm.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.itcast.ssm.po.ItemsEx;
import cn.itcast.ssm.po.ItemsExVo;
import cn.itcast.ssm.service.ItemsService;
@Controller
@RequestMapping("/items/*")
public class ItemsController {
@Autowired
ItemsService itemsService;
@RequestMapping("queryItems")
public ModelAndView queryItems() throws Exception {
ItemsEx itemsEx = new ItemsEx();
// itemsEx.setName("本");
// itemsEx.setPrice(20.0f);
ItemsExVo itemsExVo = new ItemsExVo();
itemsExVo.setItemsEx(itemsEx);
List<ItemsEx> itemsList = itemsService.findItemsExList(itemsExVo);
// List<ItemsEx> itemsList = new ArrayList<>();
//
// ItemsEx items_1 = new ItemsEx();
// items_1.setName("联想笔记本");
// items_1.setPrice(6000f);
// items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
//
// ItemsEx items_2 = new ItemsEx();
// items_2.setName("苹果手机");
// items_2.setPrice(7000f);
// items_2.setDetail("iphone6苹果手机!");
//
// itemsList.add(items_1);
// itemsList.add(items_2);
// 新建ModelAndView
ModelAndView modelAndView = new ModelAndView();
// 相当于request 的 setAttribute, 在 jsp 页面中通过 itemList 取数据
modelAndView.addObject("itemsList", itemsList);
// 指定视图
modelAndView.setViewName("items/itemsList");
return modelAndView;
}
}
12.编写jsp页面,将数据展示出来
/Web_SSM_test/WebRoot/WEB-INF/jsp/items/itemsList.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 }/item/queryItem.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="${itemsList }" 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 }/item/editItem.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
13.数据库表 Items表设计
14.Items 中的测试数据
15.最终测试结果(web页面)