How to make controller endpoint to get two differe

2020-02-29 07:47发布

I have a server built with java and spring.

What i am trying to do is that my controller with the same endpoint will get two different objects.

This is an example for what I mean:

I know I can do that:

  public class Option1{
   private String name;
   ...
     //getter and setter
    }

public class Option2{
 private Long id;
  ...
//getter and setter
}

@Controller
public class Controller{

 @RequestMapping(value = "service/getData/option1", method = RequestMethod.POST)
 @ResponseBody
 public String searchProv(@ResponseBody Option1 data1){
  return "option1"
   }

@RequestMapping(value = "service/getData/option2", method = RequestMethod.POST)
@ResponseBody
public String searchProv(@ResponseBody Option2 data2){
  return "option2"
  }
}

but I wonder if it is possible to passing different json object to the same endpoint and do that:

 @Controller
public class Controller{

 @RequestMapping(value = "service/getData", method = RequestMethod.POST)
 @ResponseBody
 public ResponseEntity<Any> getData(@ResponseBody Option1And2 data){
if(data instanceof Option1){
  return return ResponseEntity<Any>(data.name,HttpStatus.OK)
}        
if(data instanceof Option2){
   return ResponseEntity<Any>(data.id,HttpStatus.OK)
}
 return ResponseEntity<Any>("ok",HttpStatus.OK)
  }

such that 'Option1And2' is generic object can be option1 or option2.

I tried to replace 'Option1And2' to 'Any' but it didn't went well because I get a list of keys and values

3条回答
老娘就宠你
2楼-- · 2020-02-29 08:02

Seems like you want program itself to determine what type the option is.But before you do that,are you sure what is the difference between these two Object?

First is,what is the Option1And2 actually is?If the Option1And2 contains all the field of Option1 and Option2 but it's not the subclass of those,then probably the Option1And2 could be like:

@Data
public class Option1And2{
    private String name;

    private Long id;
}
  • If you have other limits like "one of them and only one of them has to be null",then you could determine it by this rule.
  • If you don't have any other limitation,then maybe you could add a new field as a flag.

In fact those code style are not recommend.If those two functions have different responsibilities,then maybe it's better to not mix them together.You will understand what I mean when you have to refactor these code.

If these two functions do have lots of things in common,maybe it's better for you to refactor the service logic instead of just combining two service roughly by creating a new param Option1And2.

By the way,what are you exactly want to do?Why do you want to merge those two object into one?

查看更多
够拽才男人
3楼-- · 2020-02-29 08:12

This is a good time to use inheritance and Java Generics. It is worth noting, if your controller has any dependencies such as a @Service or @Repository, then those too must be generic.

enter image description here

You might have a generic controller:

abstract class GenericController<T> {

    public abstract GenericService<T> getService();

    @GetMapping
    public ResponseEntity<Iterable<T>> findAll() {

        return ResponseEntity.ok(getService().findAll());
    }

    @PostMapping
    public ResponseEntity<T> save(T entity) {

        return ResponseEntity.ok(getService().save(entity));
    }

    // @DeleteMapping, @PutMapping
    // These mappings will automatically be inherited by
    // the child class. So in the case of findAll(), the API
    // will have a GET mapping on /category as well as a GET
    // mapping on /product. So, by defining and annotating the
    // CRUD operations in the parent class, they will automatically
    // become available in all child classes.
}

@Controller
@RequestMapping("/category")
class CategoryContr extends GenericController<Category> {

    @Autowired CategoryServ serv;

    @Override
    public GenericService<Category> getService() {
        return serv;
    }
}

@Controller
@RequestMapping("/product")
class ProductContr extends GenericController<Product> {

    @Autowired ProductServ serv;

    @Override
    public GenericService<Product> getService() {
        return serv;
    }
}

You then have to have abstract versions of the dependencies. The services:

abstract class GenericService<T> {

    public abstract GenericRepository<T> getRepository();

    public Iterable<T> findAll() {

        return getRepository().findAll();
    }

    public T save(T entity) {

        return getRepository().save(entity);
    }

}

@Service
class CategoryServ extends GenericService<Category> {

    @Autowired CategoryRepo repo;

    @Override
    public GenericRepository<Category> getRepository() {
        return repo;
    }
}

@Service
class ProductServ extends GenericService<Product> {

    @Autowired ProductRepo repo;

    @Override
    public GenericRepository<Product> getRepository() {
        return repo;
    }
}

Then, the services have their dependencies as well - the repositories:

@NoRepositoryBean
interface GenericRepository<T> extends JpaRepository<T, Long> {
}

@Repository
interface CategoryRepo extends GenericRepository<Category> {
}

@Repository
interface ProductRepo extends GenericRepository<Product> {
}

This was my first approach. It works very nicely. However, this does create a strong coupling between the business logic of each service and the generic service. The same holds true for the generic controller and its child classes. You can of course always override a particular CRUD operation. But, you must do this with care as you may created unexpected behavior. It is also worth noting that inheriting from classes that have methods that are annotated with @RequestMapping automatically exposes all of the annotated methods. This may be undesirable. For example, we may not want a delete option for categories, but we want it for products. To combat this, instead of annotating the method in the parent class, we can simply define it in the parent class, and override the desired CRUD operations with the added @RequestMapping annotation and then call the super class method.

Another approach is using annotations.

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-29 08:23

You should use JsonNode object.

for your example you should do this:

 @Controller
 public class Controller{

 @RequestMapping(value = "service/getData", method = RequestMethod.POST)
 @ResponseBody
 public ResponseEntity<Any> getData(@RequestBody JsonNode jsonNode){

   ObjectMapper obj = new ObjectMapper();

  if(jsonNode.has("name"){
   Option1 result= obj.convertValue(jsonNode,Option1.class)
  return ResponseEntity<Any>(result.name,HttpStatus.OK)
    }    

   else {

   Option2 result= obj.convertValue(jsonNode,Option2.class)
   return ResponseEntity<Any>(result.id,HttpStatus.OK)
    }

    return ResponseEntity<Any>("ok",HttpStatus.OK)
     }

the JsonNode and the ObjectMapper you should import from here:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.JsonNode;

this link should help you to understand better on JsonNode and give you more details.

and this link should help you with the convertValue from JsonNode to java object(POJO).

查看更多
登录 后发表回答