三大框架介绍
ssm框架是由Spring springmvc和Mybatis共同组成的框架。Spring和Springmvc都是spring公司开发的,因此他们之间不需要整合。也可以说是无缝整合。mybatis公司开发的mybatis,因为需要和Spring整合,但是他们之间是有缝的。因此mybatis公司就做出了jar包 mybatis-spring的核心整合包。
Q:什么叫无缝整合,有缝整合?
A:最方便的理解就是有Jar包就是有缝,没有jar包就是无缝。
整合准备条件
三个文件:applicationContext.xml springmvc.xml mybatis.xml (名字一般都这样起,因为我们还需要对他们进行配置,需要用文件名,同时也能让其他人明白)
下图是项目的架构图
applicationContext.xml配置文件
里面包含数据源的读取properties,配置dataSource,事务管理对象transactionManager、
sqlsession工厂SqlSessionFactory 以及Mapper扫描(xml名和接口名相同)。主要负责与mybatis整合
<?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">
<!-- 配置 读取properties文件 jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置 数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置SqlSessionFactory -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 设置MyBatis核心配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml" />
<!-- 设置数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置Mapper扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 设置Mapper扫描包 -->
<property name="basePackage" value="cn.tsu.ssm.dao" />
</bean>
</beans>
Springmvc.xml
主要负责注解,springmvc的三大组件(处理器映射器、处理器适配器、视图解析器,这三个有默认的类,但是已经过时了。)
<?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: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://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置Controller扫描 -->
<context:component-scan base-package="cn.tsu.ssm" />
<!-- 配置注解驱动 ,自动对处理器映射器和处理器适配器寻找最新的类-->
<mvc:annotation-driven />
<!--对静态资源放行 -->
<mvc:default-servlet-handler/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
mybatis.xml
mybatis可以只配一个别名,大小写不敏感,可以不配置,但是不配置的话必须使用包名+类名。
<?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>
<typeAliases>
<package name="cn.tsu.ssm.pojo"/>
</typeAliases>
</configuration>
web.xml
ssm配置完了,但是tomcat启动后并不会对Spring的框架进行读取,因此我们还需要配置一个监听器。
<?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">
<display-name>ssmDemo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器加载spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置过滤器,解决post的乱码问题 -->
<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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC -->
<servlet>
<servlet-name>ssm-crm</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 配置springmvc什么时候启动,参数必须为整数 -->
<!-- 如果为0或者大于0,则springMVC随着容器启动而启动 -->
<!-- 如果小于0,则在第一次请求进来的时候启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssm-crm</servlet-name>
<!-- 所有的请求都进入springMVC -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
在这里ssm的三大框架基本上就整合完毕了。
下面这个案例是一个客户的增删改查的分页小Demo
CustomerMapper.xml(写sql文件的,必须和CustomerMapper.java的接口文件在一个包下,并且名字相同)
<?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.tsu.ssm.dao.CustomerMapper">
<!-- 根据类别代码查询数据 -->
<select id="findBaseDictByCode" parameterType="String"
resultType="BaseDict">
SELECT * FROM base_dict WHERE dict_type_code =
#{dict_type_code}
</select>
<select id="findCustomerByPage" parameterType="queryvo" resultType="customer">
SELECT
a.cust_id,
a.cust_name,
a.cust_user_id,
a.cust_create_id,
b.dict_item_name cust_source,
c.dict_item_name cust_industry,
d.dict_item_name cust_level,
a.cust_linkman,
a.cust_phone,
a.cust_mobile,
a.cust_zipcode,
a.cust_address,
a.cust_createtime
FROM
customer a
LEFT JOIN base_dict b ON a.cust_source = b.dict_id
LEFT JOIN base_dict c ON a.cust_industry = c.dict_id
LEFT JOIN base_dict d ON a.cust_level = d.dict_id
<include refid="ifyuju"/>
<if test="start !=null">
limit #{start},#{rows}
</if>
</select>
<select id="findCustomerCount" parameterType="queryvo" resultType="Integer">
select count(*) from customer a
<include refid="ifyuju"/>
</select>
<!--
private Long cust_id;
private String cust_name;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_linkman;
private String cust_phone;
private String cust_mobile;
private String cust_zipcode;
private String cust_address;
private Date cust_createtime;
-->
<update id="editCustomer" parameterType="customer">
update customer set cust_name = #{cust_name} ,
cust_source = #{cust_source} ,
cust_industry = #{cust_industry} ,
cust_level = #{cust_level} ,
cust_linkman = #{cust_linkman} ,
cust_phone = #{cust_phone} ,
cust_mobile = #{cust_mobile} ,
cust_zipcode = #{cust_zipcode} ,
cust_address = #{cust_address} ,
cust_createtime = #{cust_createtime}
<where>
cust_id = #{cust_id}
</where>
</update>
<select id="edit" parameterType="Integer" resultType="customer">
select * from customer
<where>
cust_id = #{cust_id}
</where>
</select>
<delete id="deleteByid" parameterType="Integer">
delete from customer
<where>
cust_id = #{cust_id}
</where>
</delete>
<sql id="ifyuju">
<where>
<if test="custName != null and custName != ''">
AND a.cust_name LIKE '%${custName}%'
</if>
<if test="custSource != null and custSource != ''">
AND a.cust_source = #{custSource}
</if>
<if test="custIndustry != null and custIndustry != ''">
AND a.cust_industry = #{custIndustry}
</if>
<if test="custLevel != null and custLevel != ''">
AND a.cust_level = #{custLevel}
</if>
</where>
</sql>
</mapper>
CustomerMapper.java(接口文件)(写sql文件的,必须和CustomerMapper.xml文件在一个包下,并且名字相同,两个文件遵循4大原则{名字相同,xml的mapper namespace属性指向接口,入参类型相同,出参类型相同})
package cn.tsu.ssm.dao;
import java.util.List;
import cn.tsu.common.utils.Page;
import cn.tsu.ssm.pojo.Customer;
import cn.tsu.ssm.pojo.Queryvo;
public interface CustomerMapper {
public List<Customer> findBaseDictByCode(String code);
public List<Customer> findCustomerByPage(Queryvo vo);
public Integer findCustomerCount(Queryvo vo);
public void editCustomer(Customer customer);
public Customer edit(Integer id );
public void deleteByid (Integer id);
}
service层接口略
…
…
…
service实现类
service层主要写了分页的业务
package cn.tsu.ssm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.tsu.common.utils.Page;
import cn.tsu.ssm.dao.CustomerMapper;
import cn.tsu.ssm.pojo.Customer;
import cn.tsu.ssm.pojo.Queryvo;
@Service
@Transactional(readOnly=false,isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED)
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerMapper cm;
public List<Customer> findCustomer(String code) {
return cm.findBaseDictByCode(code);
}
public Page<Customer> findCustomerByPage(Queryvo vo) {
// TODO Auto-generated method stub
vo.setStart((vo.getPage()-1)*vo.getRows());
List<Customer> findCustomerByPage = cm.findCustomerByPage(vo);
Integer total = cm.findCustomerCount(vo);
Page<Customer> page = new Page<Customer>(total,findCustomerByPage,vo.getPage(),vo.getRows());
return page;
}
public void editCustomer(Customer customer) {
cm.editCustomer(customer);
}
public Customer edit(Integer id) {
// TODO Auto-generated method stub
return cm.edit(id);
}
public void deleteByid(Integer id) {
cm.deleteByid(id);
}
}
DemoController层
主要写了web层,接收前端传递过来的数据,post,get,json等
package cn.tsu.ssm.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.tsu.common.utils.Page;
import cn.tsu.ssm.pojo.Customer;
import cn.tsu.ssm.pojo.Queryvo;
import cn.tsu.ssm.service.CustomerService;
@Controller
public class DemoController {
@Autowired
private CustomerService cs;
@RequestMapping("listUi")
public String listUi(Model model,Queryvo vo) {
List<Customer> fromType = cs.findCustomer("002");
List<Customer> industryType = cs.findCustomer("001");
List<Customer> levelType = cs.findCustomer("006");
model.addAttribute("fromType", fromType);
model.addAttribute("industryType", industryType);
model.addAttribute("levelType", levelType);
//分页查询
Page<Customer> page = cs.findCustomerByPage(vo);
model.addAttribute("page", page);
model.addAttribute("custName", vo.getCustName());
model.addAttribute("custSource", vo.getCustSource());
model.addAttribute("custIndustry", vo.getCustIndustry());
model.addAttribute("custLevel", vo.getCustLevel());
return "customer";
}
@RequestMapping("edit")
public @ResponseBody
Customer edit(Model model, Integer id) {
Customer customer = cs.edit(id);
return customer;
}
@RequestMapping("update")
public @ResponseBody
String update(Customer customer) {
cs.editCustomer(customer);
return "ok";//这里回复null前端也有响应
}
@RequestMapping(value="delete")
public @ResponseBody
String delete (Integer id) {
System.out.println(id);
cs.deleteByid(id);
return null;
}
}
下面把工具类的代码也写出来
page.java
package cn.tsu.common.utils;
import java.util.List;
import cn.tsu.ssm.pojo.Customer;
public class Page<T> {
//一共有多少数据
private int total;
//当前页
private int page;
//当页显示多少数据
private int size;
//数据
private List<Customer> rows;
public Page(Integer total2, List<Customer> findCustomerByPage, Integer page2, Integer rows2) {
this.total=total2;
this.rows=findCustomerByPage;
this.page = page2;
this.size=rows2;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Customer> getRows() {
return rows;
}
public void setRows(List<Customer> rows) {
this.rows = rows;
}
}
NavigationTag.java
package cn.tsu.common.utils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* 显示格式 上一页 1 2 3 4 5 下一页
*/
public class NavigationTag extends TagSupport {
static final long serialVersionUID = 2372405317744358833L;
/**
* request 中用于保存Page<E> 对象的变量名,默认为“page”
*/
private String bean = "page";
/**
* 分页跳转的url地址,此属性必须
*/
private String url = null;
/**
* 显示页码数量
*/
private int number = 5;
@Override
public int doStartTag() throws JspException {
JspWriter writer = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
Page page = (Page)request.getAttribute(bean);
if (page == null)
return SKIP_BODY;
url = resolveUrl(url, pageContext);
try {
//计算总页数
int pageCount = page.getTotal() / page.getSize();
if (page.getTotal() % page.getSize() > 0) {
pageCount++;
}
writer.print("<nav><ul class=\"pagination\">");
//显示“上一页”按钮
if (page.getPage() > 1) {
String preUrl = append(url, "page", page.getPage() - 1);
preUrl = append(preUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + preUrl + "\">上一页</a></li>");
} else {
writer.print("<li class=\"disabled\"><a href=\"#\">上一页</a></li>");
}
//显示当前页码的前2页码和后两页码
//若1 则 1 2 3 4 5, 若2 则 1 2 3 4 5, 若3 则1 2 3 4 5,
//若4 则 2 3 4 5 6 ,若10 则 8 9 10 11 12
int indexPage = (page.getPage() - 2 > 0)? page.getPage() - 2 : 1;
for(int i=1; i <= number && indexPage <= pageCount; indexPage++, i++) {
if(indexPage == page.getPage()) {
writer.print( "<li class=\"active\"><a href=\"#\">"+indexPage+"<span class=\"sr-only\">(current)</span></a></li>");
continue;
}
String pageUrl = append(url, "page", indexPage);
pageUrl = append(pageUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + pageUrl + "\">"+ indexPage +"</a></li>");
}
//显示“下一页”按钮
if (page.getPage() < pageCount) {
String nextUrl = append(url, "page", page.getPage() + 1);
nextUrl = append(nextUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + nextUrl + "\">下一页</a></li>");
} else {
writer.print("<li class=\"disabled\"><a href=\"#\">下一页</a></li>");
}
writer.print("</nav>");
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
private String append(String url, String key, int value) {
return append(url, key, String.valueOf(value));
}
/**
* 为url 参加参数对儿
*
* @param url
* @param key
* @param value
* @return
*/
private String append(String url, String key, String value) {
if (url == null || url.trim().length() == 0) {
return "";
}
if (url.indexOf("?") == -1) {
url = url + "?" + key + "=" + value;
} else {
if(url.endsWith("?")) {
url = url + key + "=" + value;
} else {
url = url + "&" + key + "=" + value;
}
}
return url;
}
/**
* 为url 添加翻页请求参数
*
* @param url
* @param pageContext
* @return
* @throws javax.servlet.jsp.JspException
*/
private String resolveUrl(String url, javax.servlet.jsp.PageContext pageContext) throws JspException{
//UrlSupport.resolveUrl(url, context, pageContext)
Map params = pageContext.getRequest().getParameterMap();
for (Object key:params.keySet()) {
if ("page".equals(key) || "rows".equals(key)) continue;
Object value = params.get(key);
if (value == null) continue;
if (value.getClass().isArray()) {
url = append(url, key.toString(), ((String[])value)[0]);
} else if (value instanceof String) {
url = append(url, key.toString(), value.toString());
}
}
return url;
}
/**
* @return the bean
*/
public String getBean() {
return bean;
}
/**
* @param bean the bean to set
*/
public void setBean(String bean) {
this.bean = bean;
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
public void setNumber(int number) {
this.number = number;
}
}
commons.tlb
自己写的标签库,只需要在jsp页面引入即可使用,主要用在jsp页面的分页。
该文件放到WEB-INF下即可
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>2.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>common</short-name>
<uri>http://cn.tsu.xiaofeng/common/</uri>
<display-name>Common Tag</display-name>
<description>Common Tag library</description>
<tag>
<name>page</name>
<tag-class>cn.tsu.common.utils.NavigationTag</tag-class>
<body-content>JSP</body-content>
<description>create navigation for paging</description>
<attribute>
<name>bean</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>number</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
完 我把资源上传到文件库中,如果大家有需要代码的,可以自行下载。因为需要设置分,因此就设置1分啦。!!!下载