Spring Mvc那點事---(37)rest服務項目模塊介紹

引子

   一個項目通常要包括幾個模塊,服務層,業務層,數據層,實體類,每個模塊單獨一個項目,降低了項目之間的耦合性,增強了項目的清晰度,減少各個項目之間的依賴。所以越是大的項目,項目模塊分的越多,層次分的越清晰。對於新加入的同伴,對項目熟悉越快,上手越快,同時每個人可以單獨管理一個模塊,分工明確,互不影響。

項目架構

    廢話少說,直接上圖,看看下面的項目結構圖
  
 上面的項目是一個完整的spring mvc rest服務項目架構,  數據層,服務層,業務層,每層分爲兩個模塊,接口模塊和實現模塊。上層調用下層只調用下層的接口,通過spring註解自己去發現接口實現。
項目是rest服務通過mybatis組件向mysql數據庫插入數據,   erp-webapp是啓動項目,也就是宿主項目,rest-api和rest-impl是服務層的接口和接口實現, service-api和service-impl是業務層的接口和接口實現.
dao-api是數據操作層接口,  dao-mybatis是mybatis的配置文件, erp-common是項目的通用操作類。

服務實現

  @RestController用來標註是controller,
 @RequestMapping用來設置請求別名,請求方式和請求動作。
spring mvc啓用掃描使用如下配置
<context:component-scan base-package="org.supersoft.erp.rest.impl" />    
 <context:annotation-config />
   客戶端和服務端數據傳輸使用json,可以使用spring內置的json組件,org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
   可以看如下服務代碼
package org.supersoft.erp.rest.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.supersoft.erp.common.CommonResponse;
import org.supersoft.erp.common.ServiceResponse;
import org.supersoft.erp.domain.Product;
import org.supersoft.erp.rest.api.ProductController;
import org.supersoft.erp.rest.dto.ProductDto;
import org.supersoft.erp.service.api.ProductService;


@RestController
@RequestMapping("product")
public class ProductControllerImpl implements ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 添加
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse<?> addProduct(@RequestBody ProductDto product) {
        try
        {
            Product p=new Product();
            BeanUtils.copyProperties(product, p);
            productService.addProduct(p);
            return CommonResponse.result();
        }
        catch(Throwable t)
        {
            return CommonResponse.error();
        }
    }

    /**
     * 修改
     */
    public CommonResponse<?> updateProduct(@RequestBody ProductDto product) {
        try
        {
            Product p=new Product();
            BeanUtils.copyProperties(product, p);
            productService.updateProduct(p);
            return CommonResponse.result();
        }
        catch(Throwable t)
        {
            return CommonResponse.error();
        }
    }

}


使用tomcat啓動webapp服務。
客戶端調用可以使用瀏覽器自帶的請求組件進行測試,這裏使用谷歌瀏覽器的DHC


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章