商品添加功能中会用到商品分类选择, 这个时候就需要从商品列表中把分类展示出来选择一个分类, 展示商品分类列表,使用EasyUI的tree控件展示
初始化tree请求的url:/item/cat/list
参数:
初始化tree时只需要把第一级节点展示,子节点异步加载。
long id(父节点id)
返回值:json。数据格式
[{
“id”: 1,
“text”: “Node 1”,
“state”: “closed”
},{
“id”: 2,
“text”: “Node 2”,
“state”: “closed”
}]
state:如果节点下有子节点“closed”,如果没有子节点“open”
创建一个pojo来描述tree的节点信息,包含三个属性id、text、state。放到e3-common工程中
public class EasyUITreeNode implements Serializable{
private long id;
private String text;
private String state;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
功能实现
dao层
由于只需要查询一个表, 单表查询就可以使用逆向工程生成的代码, dao层就不用写mapper了
service层
定义接口
public interface ItemCatService {
//根据parentId查询节点列表
List<EasyUITreeNode> getItemCatList(long parentId);
}
接口的实现类
@Service
@Repository("itemCatService")
public class ItemCatServiceImpl implements ItemCatService {
@Autowired
private TbItemCatMapper itemCatMapper;
@Override
public List<EasyUITreeNode> getItemCatList(long parentId) {
//根据parentId查询子节点列表
TbItemCatExample example = new TbItemCatExample();
Criteria criteria = example.createCriteria();
//设置查询条件
criteria.andParentIdEqualTo(parentId);
//执行查询
List<TbItemCat> list = itemCatMapper.selectByExample(example);
//创建返回结果List
List<EasyUITreeNode> resultList = new ArrayList<EasyUITreeNode>();
//把列表转换成EasyUITreeNode
for (TbItemCat tbItemCat : list) {
EasyUITreeNode node = new EasyUITreeNode();
//设置属性
node.setId(tbItemCat.getId());
node.setText(tbItemCat.getName());
node.setState(tbItemCat.getIsParent()?"closed":"open");
//添加到结果列表
resultList.add(node);
}
return resultList;
}
}
表现层
@Controller
public class ItemCatController {
@Autowired
private ItemCatService itemCatService;
@RequestMapping("/item/cat/list")
@ResponseBody
public List<EasyUITreeNode> getItemCatList(
@RequestParam(name="id" ,defaultValue="0") Long parentId){
//调用服务查询节点列表
List<EasyUITreeNode> list = itemCatService.getItemCatList(parentId);
return list;
}
}