电商项目之多功能增删改查案例

先构建框架

Controller层

@Controller
@RequestMapping("/brand")
public class BrandController {
    @Reference
    private BrandService brandService;
}

Service层接口

public interface BrandService {}

Service层接口实现类

@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandDao brandDao;
}

1:查

先从数据库中查询所有得数据

Controller层
    @RequestMapping("/findAll")
    @ResponseBody
    public List<Brand> fingAllBrand(){
        return brandService.findAllBrand();
    }

Service接口
List<Brand> findAllBrand();

Service接口实现类
    @Override
    public List<Brand> findAllBrand() {
        BrandQuery query = new BrandQuery();
        BrandQuery.Criteria criteria = query.createCriteria();
        List<Brand> brands = brandDao.selectByExample(query);
        return brands;
    }

html页面模块

修改brand.html ,引入JS

<script type="text/javascript" src="../plugins/angularjs/angular.min.js"></script>

指定模块和控制器,并指定初始化方法

<body class="hold-transition skin-red sidebar-mini" ng-app="youlexuan"   ng-controller="brandController" ng-init="findAll()">

ng-controller 指令用于为你的应用添加控制器。ng-app 指令中定义的就是模块的名称  ng-init指定初始化

在控制器中,你可以编写代码,制作函数和变量,并使用 scope 对象来访问。

编写JS代码

<script type="text/javascript">
    var app=angular.module('youlexuan', ['pagination']);//定义模块
    app.controller('brandController' ,function($scope,$http){
    //读取列表数据绑定到表单中
    $scope.findAll=function(){
        $http.get('../brand/findAll.do').success(
            function(response){
                $scope.list=response;
           }
        );
    }
  })
</script>

循环显示表格数据

<tbody>
    <tr ng-repeat="entity in list">
        <td><input ng-click="updateSelection($event,entity.id)" type="checkbox" ></td>
    <td>{{entity.id}}</td>
    <td>{{entity.name}}</td>
    <td>{{entity.firstChar}}</td>
    <td class="text-center">
    <button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" ng-click="findOne(entity.id)">修改</button>
    </td>
    </tr>
</tbody>

下面是带分页的列表展示

注意:需要将上面的初始化 ng-init="findAll()" 去掉

实体类:注意需要实现序列化接口

public class PageResult implements Serializable {
    private Long total;
    private List rows;
    //省略set,get,构造方法和toString     
}

html模块

brand.html引入分页组件

<!-- 分页组件开始 -->
<script src="../plugins/angularjs/pagination.js"></script>
<link rel="stylesheet" href="../plugins/angularjs/pagination.css">
<!-- 分页组件结束 -->

构建app模块时引入pagination模块 

var app=angular.module('youlexuan',['pagination']);//定义模块,增加分页模块

页面的表格下放置分页组件 

 <!-- 分页 -->
<tm-pagination conf="paginationConf"></tm-pagination>

在brandController中添加如下 JS代码

//分页控件配置
$scope.paginationConf = {
    currentPage: 1,
    totalItems: 5,     //总记录数
    itemsPerPage: 5, //每页显示的数据量
    perPageOptions: [5, 10, 20, 30, 50],
    onChange: function(){
        $scope.reloadList();//重新加载
    }
};
//重新加载列表 数据
$scope.reloadList=function(){
    //切换页码,获取当前页面和数据量
    $scope.findPage( $scope.paginationConf.currentPage, $scope.paginationConf.itemsPerPage);
}
//分页
$scope.findPage=function(page,rows){
    $http.get('../brand/findPage.do?page='+page+'&rows='+rows).success(
        function(response){
            //重新给list值,重新遍历
            $scope.list=response.rows;
            $scope.paginationConf.totalItems=response.total;//更新总记录数
        }
    );
}

paginationConf 变量各属性的意义:在页面的body元素上去掉ng-init指令的调用

currentPage:当前页码

totalItems:总条数

itemsPerPage:

perPageOptions:页码选项

onChange:更改页面时触发事件

后台代码

Controller代码
    @RequestMapping("/findPage")
    @ResponseBody
    public PageResult findPage(Integer page,Integer rows){
        return brandService.findPage(page,rows);
    }

Service接口
    PageResult findPage(Integer page, Integer rows);

Service接口实现类
    @Override
    public PageResult findPage(Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        Page<Brand> pages = (Page<Brand>) brandDao.selectByExample(null);
        return new PageResult(pages.getTotal(),pages.getResult());
    }

2:增

 HTML模块

在绑定表单元素,我们用ng-model指令,绑定按钮的单击事件我们用ng-click

<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">品牌编辑</h3>
</div>
<div class="modal-body">
 <table class="table table-bordered table-striped"  width="800px">
       <tr>
       <td>品牌名称</td>
       <td><input  class="form-control" ng-model="entity.name" placeholder="品牌名称" >  </td>
       </tr>       
       <tr>
       <td>首字母</td>
       <td><input  class="form-control" ng-model="entity.firstChar" placeholder="首字母">  </td>
       </tr>       
 </table>
</div>
<div class="modal-footer">
<button class="btn btn-success" data-dismiss="modal" aria-hidden="true" ng-click="save()">保存</button>
<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>
</div>
</div>
</div>

为了每次打开窗口没有遗留上次的数据,我们可以修改新建按钮,对entity变量进行清空操作 

<button type="button" class="btn btn-default" title="新建" data-toggle="modal" data-target="#editModal" ng-click="entity={}"><i class="fa fa-file-o"></i> 新建</button>

JS代码

$scope.save=function(){
    var methodName = 'add';
$http.post('../brand/'+methodName+'.do',$scope.brand).success(
        function(response){
            if(response.success){
                //重新查询
                $scope.reloadList();//重新加载
            }else{
                alert(response.message);
            }
        }
    );
}

逻辑代码

Controller层
@RequestMapping("/add")
@ResponseBody
public Result addBrand(@RequestBody Brand brand){
    try {
        brandService.addBrand(brand);
        return new Result(true,"添加成功");
    }catch (Exception ex){
        String message = ex.getMessage();
        return new Result(false,message);
    }
}

Service接口
void addBrand(Brand brand);

Service接口实现类
@Override
public void addBrand(Brand brand) {
    brandDao.insertSelective(brand);
}

3:改

修改列表中的“修改”按钮,调用此方法执行查询实体的操作

<button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" ng-click="findOne(entity.id)" >修改</button>

实现数据的回填

//查询实体,实现数据的回填
$scope.findOne=function(id){
    $http.get('../brand/findOne.do?id='+id).success(
        function(response){
            $scope.brand= response;
        }
     );
}    

在上面填的的js代码中添加

//保存
$scope.save=function(){
    var methodName = 'add';
    //在这里进行方法的判断,当有id时,执行的是修改方法
    if($scope.brand.id != null){
        methodName = 'update';
    }
    $http.post('../brand/'+methodName+'.do',$scope.brand).success(
        function(response){
            if(response.success){
                //重新查询
                $scope.reloadList();//重新加载
            }else{
                alert(response.message);
            }
        }
    );
}    

页面逻辑代码

Controller层
@RequestMapping("/findOne")
@ResponseBody
public Brand findByIdBrand(Long id){
    return brandService.findByIdBrand(id);
}
@RequestMapping("/update")
@ResponseBody
public Result updateByIdBrand(@RequestBody Brand brand){
    return brandService.updateByIdBrand(brand);
}

Sercice接口
Brand findByIdBrand(Long id);
Result updateByIdBrand(Brand brand);

Service接口的实现类
@Override
public Brand findByIdBrand(Long id) {
    return brandDao.selectByPrimaryKey(id);
}
@Override
public Result updateByIdBrand(Brand brand) {
    try {
        brandDao.updateByPrimaryKeySelective(brand);
        return new Result(true,"更新成功");
    }catch (Exception ex){
        return new Result(false,ex.getMessage());
    }
}

4:删

html模块

修改列表的复选框

<input  type="checkbox" ng-click="updateSelection($event,entity.id)">

修改删除按钮

<button type="button" class="btn btn-default" title="删除" ng-click="dele()"><i class="fa fa-trash-o"></i> 删除</button> 

js代码

$scope.selectIds=[];//选中的ID集合
//更新复选
$scope.updateSelection = function($event, id) {
    if($event.target.checked){//如果是被选中,则增加到数组
        $scope.selectIds.push(id);
    }else{
        //indexOf() 方法可返回数组中某个指定的元素索引。没有的返回-1
        var idx = $scope.selectIds.indexOf(id);
        //splice()从数组中删除指定元素(第一个参数),第二个参数表示删除的个数
        $scope.selectIds.splice(idx, 1);//删除
    }
}
//批量删除
$scope.dele=function(){
    //获取选中的复选框
    $http.get('../brand/delete.do?ids='+$scope.selectIds).success(
        function(response){
            if(response.success){
                $scope.reloadList();//刷新列表
            }
        }
    );
}

后台代码

Controller层
    @RequestMapping("/delete")
    @ResponseBody
    public Result deleteByIds(Long[] ids){
        try {
            brandService.deleteByIds(ids);
            return new Result(true,"删除成功");
        }catch (Exception ex){
            return new Result(false,ex.getMessage());
        }

    }
Service接口层
    void deleteByIds(Long[] ids);
Service接口实现
    @Override
    public void deleteByIds(Long[] ids) {
        for (Long id : ids) {
            brandDao.deleteByPrimaryKey(id);
        }
    }

5:模糊查询

html模块

修改brand.html,增加查询条件、查询按钮

<div class="box-tools pull-right">
<div class="has-feedback">品牌名称:<input ng-model="searchEntity.name"> 
 品牌首字母:<input ng-model="searchEntity.firstChar">  
<button  class="btn btn-default" ng-click="reloadList()">查询</button>
</div>
</div>

修改reloadList方法

//刷新列表
$scope.reloadList=function(){
    $scope.search( $scope.paginationConf.currentPage,             
    $scope.paginationConf.itemsPerPage);
}

js

//条件模糊查询
$scope.searchEntity={};//定义搜索对象
//条件查询
$scope.search=function(page,rows){
    $http.post('../brand/search.do?page='+page+"&rows="+rows, $scope.searchEntity).success(
        function(response){
            $scope.paginationConf.totalItems=response.total;//总记录数
            $scope.list=response.rows;//给列表变量赋值
        }
    );
}

后台代码

Controller层
    @RequestMapping("/search")
    @ResponseBody
    public PageResult findByLike(@RequestBody Brand brand,Integer page,Integer rows){
        return brandService.findByLike(brand,page,rows);
    }
Service接口
    PageResult findByLike(Brand brand, Integer page, Integer rows);
Service接口实现类
    @Override
    public PageResult findByLike(Brand brand, Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        BrandQuery brandQuery = new BrandQuery();
        BrandQuery.Criteria criteria = brandQuery.createCriteria();
        if(brand != null){
            if(brand.getName()!=null && brand.getName().length()>0){
                criteria.andNameLike("%"+brand.getName()+"%");
            }
            if(brand.getFirstChar()!=null && brand.getFirstChar().length()>0){
                criteria.andFirstCharEqualTo(brand.getFirstChar());
            }
        }
        Page<Brand> pages = (Page<Brand>)brandDao.selectByExample(brandQuery);
        return new PageResult(pages.getTotal(),pages.getResult());
    }
原文地址:https://www.cnblogs.com/wangju/p/11849557.html