【问题标题】:What is best practice to realise Controllers whith same functionality?实现具有相同功能的控制器的最佳实践是什么?
【发布时间】:2018-03-20 13:41:51
【问题描述】:

我有一个简单的 WebApp,它有两个表 ClothesShoes
创建控制器的最佳实践是什么,因为它们都有 CRUD 方法。
我有两个这样的控制器:

@Controller
@RequestMapping("/shoes")
@Component
public class ShoesController {
private ShoesService shoesService;

@Autowired
public void setShoesService(ShoesService shoesService) {
    this.shoesService = shoesService;
}

public ShoesService getShoesService() {
    return shoesService;
}

@RequestMapping(value = "/view/all", method = RequestMethod.GET)
public @ResponseBody
List<Shoes> getAllShoes(){
    return shoesService.getAllShoes();
}

@RequestMapping(value = "/byId/{id}", method = RequestMethod.GET)
public @ResponseBody
Shoes getShoesById(@PathVariable ("id") Integer id, Shoes shoes){
    //TODO remove hardcoded values
    return shoesService.getShoesByID(id, shoes);
}

@RequestMapping(value = "/view/{columnName}={value}", method = 
RequestMethod.GET)
public @ResponseBody
List<Shoes> getByColumnValue(@PathVariable ("columnName") String colunmName, 
@PathVariable("value") String columnValue, Shoes shoes){
    //TODO remove hardcoded values
    return shoesService.getByColumnValue(colunmName, columnValue, shoes);
}

@RequestMapping(value = "/edit/id={id}", method = RequestMethod.GET)
public @ResponseBody
Shoes update(@PathVariable ("id") Integer id, Shoes shoes){

    shoes = getShoesById(id, shoes);
    shoes.setShoesSeason("SPRINGGG");
    shoesService.updateShoes(shoes);
    return shoes;
}

@RequestMapping(value = "/delete/{id}", method =RequestMethod.GET)
public @ResponseBody
List<Shoes> delete(@PathVariable ("id") Integer id, Shoes shoes){
    shoes = getShoesById(id, shoes);
    shoesService.delete(shoes, id);
    return getAllShoes();
}

@RequestMapping(value = "/add", method = RequestMethod.GET)
public @ResponseBody
List<Shoes> add (Shoes shoes){
    shoes = new Shoes(333666, "Blue", "Autumn", "Noski", "URL");
    shoesService.add(shoes);
    return shoesService.getAllShoes();
}
}

Clothes 控制器具有相同的实现。
具有相同功能的实现控制器的最佳实践是什么?

【问题讨论】:

  • 为什么没有抽象控制器...
  • 您不需要控制器上的@Component@Controller 是一个更具体的版本,使您的 @Component 变得多余

标签: java spring model-view-controller


【解决方案1】:

您还可以创建父类并使用继承。这样,所有子类将具有与父类相同的方法。如果需要任何特定的方法,可以直接在子类中创建。

【讨论】:

    【解决方案2】:

    我认为好的简单解决方案是使用Spring Data REST。 您还可以创建抽象控制器,该控制器可以根据您要使用的类型进行参数化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多