1. SSM框架整合
数据库
备份sql
Mybatis逆向工程
使用mybatis官方提供的mybatis-generator生成pojo、mapper接口及映射文件。
并且将pojo放到toatao-manager-pojo工程中。
将mapper接口及映射文件放到taotao-manager-dao工程中
整合思路
1、Dao层:
mybatis整合spring,通过spring管理SqlSessionFactory、mapper代理对象。需要mybatis和spring的整合包。
2、Service层:
所有的service实现类都放到spring容器中管理。由spring创建数据库连接池,并有spring管理实务。
3、表现层:
Springmvc框架,由springmvc管理controller。
taotao-manager-web(springMvc\Spring)
<!-- 配置注解驱动 -->
<mvc:annotation-driven />
<!-- 配置包扫描器,扫描@Controller注解的类 -->
<context:component-scan base-package="com.taotao.controller"/>
引用dubbo服务
<!-- 引用dubbo服务 -->
<dubbo:application name="taotao-manager-web"/>
<!-- 192.168.93.88:2181 -->
<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"/>
<dubbo:reference interface="com.taotao.service.ItemService" id="itemService" />
<dubbo:reference interface="com.taotao.service.ItemCatService" id="itemCatService" />
<dubbo:reference interface="com.taotao.content.service.ContentCategoryService" id="contentCategoryService" />
<dubbo:reference interface="com.taotao.content.service.ContentService" id="contentService" />
<dubbo:reference interface="com.taotao.search.service.SearchItemService" id="searchItemService" />
web.xml 初始化spring容器
<!-- 初始化spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
taotao-manager-service (mybatis-spring(service\trans))
<!-- 配置包扫描器,扫描所有带@Service注解的类 -->
<context:component-scan base-package="com.taotao.service"/>
发布dubbo服务
<!-- 发布dubbo服务 -->
<!-- 提供方应用信息,用于计算依赖关系 -->
<dubbo:application name="taotao-manager" />
<!-- 注册中心的地址 192.168.93.88 -->
<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181" />
<!-- 用dubbo协议在20880端口暴露服务 -->
<dubbo:protocol name="dubbo" port="20880" />
<!-- 声明需要暴露的服务接口 -->
<dubbo:service interface="com.taotao.service.ItemService" ref="itemServiceImpl" timeout="300000"/>
<dubbo:service interface="com.taotao.service.ItemCatService" ref="itemCatServiceImpl" timeout="300000"/>
web.xml 前端控制器
<!-- 前端控制器 -->
<servlet>
<servlet-name>taotao-manager-web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>taotao-manager-web</servlet-name>
<!-- 拦截所有请求jsp除外 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
2. 系统间通信
如何实现远程通信?
1、Webservice:效率不高基于soap协议。项目中不推荐使用。
2、使用restful形式的服务:http+json。很多项目中应用。如果服务太多,服务之间调用关系混乱,需要治疗服务。
3、使用dubbo。使用rpc协议进行远程调用,直接使用socket通信。传输效率高,并且可以统计出系统之间的调用关系、调用次数。
dubbo介绍
Dubbo就是资源调度和治理中心的管理工具。
随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,亟需一个治理系统确保架构有条不紊的演进。
单一应用架构
当网站流量很小时,只需一个应用,将所有功能都部署在一起,以减少部署节点和成本。
此时,用于简化增删改查工作量的 数据访问框架(ORM) 是关键。
垂直应用架构
当访问量逐渐增大,单一应用增加机器带来的加速度越来越小,将应用拆成互不相干的几个应用,以提升效率。
此时,用于加速前端页面开发的 Web框架(MVC) 是关键。
分布式服务架构
当垂直应用越来越多,应用之间交互不可避免,将核心业务抽取出来,作为独立的服务,逐渐形成稳定的服务中心,使前端应用能更快速的响应多变的市场需求。
此时,用于提高业务复用及整合的 分布式服务框架(RPC) 是关键。
流动计算架构
当服务越来越多,容量的评估,小服务资源的浪费等问题逐渐显现,此时需增加一个调度中心基于访问压力实时管理集群容量,提高集群利用率。
此时,用于提高机器利用率的 资源调度和治理中心(SOA) 是关键。
Dubbo的架构
节点角色说明:
Provider: 暴露服务的服务提供方。
Consumer: 调用远程服务的服务消费方。
Registry: 服务注册与发现的注册中心。
Monitor: 统计服务的调用次调和调用时间的监控中心。
Container: 服务运行容器。
调用关系说明:
- 服务容器负责启动,加载,运行服务提供者。
- 服务提供者在启动时,向注册中心注册自己提供的服务。
- 服务消费者在启动时,向注册中心订阅自己所需的服务。
- 注册中心返回服务提供者地址列表给消费者,如果有变更,注册中心将基于长连接推送变更数据给消费者。
- 服务消费者,从提供者地址列表中,基于软负载均衡算法,选一台提供者进行调用,如果调用失败,再选另一台调用。
- 服务消费者和提供者,在内存中累计调用次数和调用时间,定时每分钟发送一次统计数据到监控中心。
注册中心 zookeeper
注册中心负责服务地址的注册与查找,相当于目录服务,服务提供者和消费者只在启动时与注册中心交互,注册中心不转发请求,压力较小。使用dubbo-2.3.3以上版本,建议使用zookeeper注册中心。
Zookeeper是Apacahe Hadoop的子项目,是一个树型的目录服务,支持变更推送,适合作为Dubbo服务的注册中心,工业强度较高,可用于生产环境,并推荐使用
Zookeeper的安装:
第一步:安装jdk
第二步:解压缩zookeeper压缩包
第三步:将conf文件夹下zoo_sample.cfg复制一份,改名为zoo.cfg
第四步:修改配置dataDir属性,指定一个真实目录
第五步:
启动zookeeper:bin/ start
关闭zookeeper:bin/ stop
查看zookeeper状态:bin/ status
注意要关闭linux的防火墙。
Dubbo监控中心
http://localhost:8083/dubbo-admin/
3. 商城后台管理系统
1. 功能分析
商品管理
新增(商品分类选择树形图、图片服务器上传、富文本编辑框)
查询
商品分类
网站内容管理content
内容分类管理
内容发布
索引库管理
导入索引库
2.技术点
easyui
kindeditor
图片上传
3. 代码实现及问题
解决mapper映射文件不发布问题
taotao-manage-dao pom.xml
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!-- <resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource> -->
</resources>
</build>
商品列表 功能代码示例
taotao-manager-web Controller
ItemController
@Controller
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("/item/list")
@ResponseBody
public EasyUIDataGridResult getItemList(Integer page, Integer rows) {
EasyUIDataGridResult result = itemService.getItemList(page, rows);
return result;
}
}
client.conf
tracker_server=192.168.25.175:22122
PictureController 上传到图片服务器
@Controller
public class PictureController {
@Value("${IMAGE_SERVER_URL}")
private String IMAGE_SERVER_URL;
@RequestMapping("/pic/upload")
@ResponseBody
public String picUpload(MultipartFile uploadFile) {
try {
//接收上传的文件
//取扩展名
String originalFilename = uploadFile.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
//上传到图片服务器
FastDFSClient fastDFSClient = new FastDFSClient("classpath:resource/client.conf");
String url = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
url = IMAGE_SERVER_URL + url;
//响应上传图片的url
Map result = new HashMap<>();
result.put("error", 0);
result.put("url", url);
return JsonUtils.objectToJson(result);
} catch (Exception e) {
e.printStackTrace();
Map result = new HashMap<>();
result.put("error", 1);
result.put("message", "图片上传失败");
return JsonUtils.objectToJson(result);
}
}
}
taotao-manager-service ServiceImpl
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private TbItemMapper itemMapper;
@Autowired
private TbItemDescMapper itemDescMapper;
@Autowired
private JmsTemplate jmsTemplate;
@Resource(name="itemAddtopic")
private Destination destination;
@Autowired
private JedisClient jedisClient;
@Value("${ITEM_INFO}")
private String ITEM_INFO;
@Value("${TIEM_EXPIRE}")
private Integer TIEM_EXPIRE;
@Override
public EasyUIDataGridResult getItemList(int page, int rows) {
//设置分页信息
PageHelper.startPage(page, rows);
//执行查询
TbItemExample example = new TbItemExample();
List<TbItem> list = itemMapper.selectByExample(example);
//取查询结果
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
EasyUIDataGridResult result = new EasyUIDataGridResult();
result.setRows(list);
result.setTotal(pageInfo.getTotal());
//返回结果
return result;
}
}
taotao-manager-interface Service
public interface ItemService {
TbItem getItemById(long itemId);
EasyUIDataGridResult getItemList(int page, int rows);
TaotaoResult addItem(TbItem item, String desc);
TbItemDesc getItemDescById(long itemId);
}
taotao-manager-interface Mapper Mapper.xml
public interface TbItemMapper {
int countByExample(TbItemExample example);
int deleteByExample(TbItemExample example);
int deleteByPrimaryKey(Long id);
int insert(TbItem record);
int insertSelective(TbItem record);
List<TbItem> selectByExample(TbItemExample example);
TbItem selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TbItem record, @Param("example") TbItemExample example);
int updateByExample(@Param("record") TbItem record, @Param("example") TbItemExample example);
int updateByPrimaryKeySelective(TbItem record);
int updateByPrimaryKey(TbItem record);
}
TbItemMapper.xml
<mapper namespace="com.taotao.mapper.TbItemMapper" >
<sql id="Base_Column_List" >
id, title, sell_point, price, num, barcode, image, cid, status, created, updated
</sql>
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.taotao.pojo.TbItemExample" >
select
<if test="distinct" >
distinct
</if>
<include refid="Base_Column_List" />
from tb_item
<if test="_parameter != null" >
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null" >
order by ${orderByClause}
</if>
</select>
</mapper>
taotao-manage-pojo pojo Example
TbItem
public class TbItem implements Serializable{
private Long id;
private String title;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
TbItemExample
public class TbItemExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public TbItemExample() {
oredCriteria = new ArrayList<Criteria>();
}
}
view datagrid控件 EasyUIDataGridResult
Datagrid默认请求参数:
1、page:当前的页码,从1开始。
2、rows:每页显示的记录数。
响应的数据:json数据。EasyUIDataGridResult
Easyui中datagrid控件要求的数据格式为:
{total:”2”,rows:[{“id”:”1”,”name”:”张三”},{“id”:”2”,”name”:”李四”}]}
public class EasyUIDataGridResult implements Serializable{
private long total;
private List rows;
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
}
SqlMapConfig.xml mybatis 分页插件 PageHelper
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 配置数据库的方言 -->
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
菜单 商品管理
index.jsp
<li>
<span>商品管理</span>
<ul>
<li data-options="attributes:{'url':'item-add'}">新增商品</li>
<li data-options="attributes:{'url':'item-list'}">查询商品</li>
<li data-options="attributes:{'url':'item-param-list'}">规格参数</li>
</ul>
</li>
商品管理 查询商品 item-list
item-list.jsp
<table class="easyui-datagrid" id="itemList" title="商品列表"
data-options="singleSelect:false,collapsible:true,pagination:true,url:'/item/list',method:'get',pageSize:30,toolbar:toolbar">
<thead>
<tr>
<th data-options="field:'ck',checkbox:true"></th>
<th data-options="field:'id',width:60">商品ID</th>
<th data-options="field:'title',width:200">商品标题</th>
<th data-options="field:'cid',width:100">叶子类目</th>
<th data-options="field:'sellPoint',width:100">卖点</th>
<th data-options="field:'price',width:70,align:'right',formatter:TAOTAO.formatPrice">价格</th>
<th data-options="field:'num',width:70,align:'right'">库存数量</th>
<th data-options="field:'barcode',width:100">条形码</th>
<th data-options="field:'status',width:60,align:'center',formatter:TAOTAO.formatItemStatus">状态</th>
<th data-options="field:'created',width:130,align:'center',formatter:TAOTAO.formatDateTime">创建日期</th>
<th data-options="field:'updated',width:130,align:'center',formatter:TAOTAO.formatDateTime">更新日期</th>
</tr>
</thead>
</table>
<div id="itemEditWindow" class="easyui-window" title="编辑商品" data-options="modal:true,closed:true,iconCls:'icon-save',href:'/rest/page/item-edit'" style="width:80%;height:80%;padding:10px;">
</div>
http://localhost:8088/item/list?page=1&rows=30
添加商品 选择类目
item-add.jsp
<tr>
<td>商品类目:</td>
<td>
<a href="javascript:void(0)" class="easyui-linkbutton selectItemCat">选择类目</a>
<input type="hidden" name="cid" style="width: 280px;"></input>
</td>
</tr>
common.js
// 初始化选择类目组件
initItemCat : function(data){
$(".selectItemCat").each(function(i,e){
var _ele = $(e);
if(data && data.cid){
_ele.after("<span style='margin-left:10px;'>"+data.cid+"</span>");
}else{
_ele.after("<span style='margin-left:10px;'></span>");
}
_ele.unbind('click').click(function(){
$("<div>").css({padding:"5px"}).html("<ul>")
.window({
width:'500',
height:"450",
modal:true,
closed:true,
iconCls:'icon-save',
title:'选择类目',
onOpen : function(){
var _win = this;
$("ul",_win).tree({
url:'/item/cat/list',
animate:true,
onClick : function(node){
if($(this).tree("isLeaf",node.target)){
// 填写到cid中
_ele.parent().find("[name=cid]").val(node.id);
_ele.next().text(node.text).attr("cid",node.id);
$(_win).window('close');
if(data && data.fun){
data.fun.call(this,node);
}
}
}
});
},
onClose : function(){
$(this).window("destroy");
}
}).window('open');
});
});
},
商品添加 图片上传
item-add.jsp
<tr>
<td>商品图片:</td>
<td>
<a href="javascript:void(0)" class="easyui-linkbutton picFileUpload">上传图片</a>
<input type="hidden" name="image"/>
</td>
</tr>
common.js
// 初始化图片上传组件
var TT = TAOTAO = {
// 编辑器参数
kingEditorParams : {
//指定上传文件参数名称
filePostName : "uploadFile",
//指定上传文件请求的url。
uploadJson : '/pic/upload',
//上传类型,分别为image、flash、media、file
dir : "image"
},
initPicUpload : function(data){
$(".picFileUpload").each(function(i,e){
var _ele = $(e);
_ele.siblings("div.pics").remove();
_ele.after('\
<div class="pics">\
<ul></ul>\
</div>');
// 回显图片
if(data && data.pics){
var imgs = data.pics.split(",");
for(var i in imgs){
if($.trim(imgs[i]).length > 0){
_ele.siblings(".pics").find("ul").append("<li><a href='"+imgs[i]+"' target='_blank'><img src='"+imgs[i]+"' width='80' height='50' /></a></li>");
}
}
}
//给“上传图片按钮”绑定click事件
$(e).click(function(){
var form = $(this).parentsUntil("form").parent("form");
//打开图片上传窗口
KindEditor.editor(TT.kingEditorParams).loadPlugin('multiimage',function(){
var editor = this;
editor.plugin.multiImageDialog({
clickFn : function(urlList) {
var imgArray = [];
KindEditor.each(urlList, function(i, data) {
imgArray.push(data.url);
form.find(".pics ul").append("<li><a href='"+data.url+"' target='_blank'><img src='"+data.url+"' width='80' height='50' /></a></li>");
});
form.find("[name=image]").val(imgArray.join(","));
editor.hideDialog();
}
});
});
});
});
},
商品详情 富文本编辑框
item-add.jsp
<link href="/js/kindeditor-4.1.10/themes/default/default.css" type="text/css" rel="stylesheet">
<script type="text/javascript" charset="utf-8" src="/js/kindeditor-4.1.10/kindeditor-all-min.js"></script>
<script type="text/javascript" charset="utf-8" src="/js/kindeditor-4.1.10/lang/zh_CN.js"></script>
<tr>
<td>商品描述:</td>
<td>
<textarea style="width:800px;height:300px;visibility:hidden;" name="desc"></textarea>
</td>
</tr>
item-add.jsp
var itemAddEditor ;
//页面初始化完毕后执行此方法
$(function(){
//创建富文本编辑器
itemAddEditor = TAOTAO.createEditor("#itemAddForm [name=desc]");
//初始化类目选择和图片上传器
TAOTAO.init({fun:function(node){
//根据商品的分类id取商品 的规格模板,生成规格信息。第四天内容。
//TAOTAO.changeItemParam(node, "itemAddForm");
}});
});
//提交表单
function submitForm(){
//有效性验证
if(!$('#itemAddForm').form('validate')){
$.messager.alert('提示','表单还未填写完成!');
return ;
}
//取商品价格,单位为“分”
$("#itemAddForm [name=price]").val(eval($("#itemAddForm [name=priceView]").val()) * 100);
//同步文本框中的商品描述
itemAddEditor.sync();
//取商品的规格
/*
var paramJson = [];
$("#itemAddForm .params li").each(function(i,e){
var trs = $(e).find("tr");
var group = trs.eq(0).text();
var ps = [];
for(var i = 1;i<trs.length;i++){
var tr = trs.eq(i);
ps.push({
"k" : $.trim(tr.find("td").eq(0).find("span").text()),
"v" : $.trim(tr.find("input").val())
});
}
paramJson.push({
"group" : group,
"params": ps
});
});
//把json对象转换成字符串
paramJson = JSON.stringify(paramJson);
$("#itemAddForm [name=itemParams]").val(paramJson);
*/
//ajax的post方式提交表单
//$("#itemAddForm").serialize()将表单序列号为key-value形式的字符串
alert($("#itemAddForm").serialize());
$.post("/item/save",$("#itemAddForm").serialize(), function(data){
if(data.status == 200){
$.messager.alert('提示','新增商品成功!');
}
});
}
function clearForm(){
$('#itemAddForm').form('reset');
itemAddEditor.html('');
}