• Post Reply Bookmark Topic Watch Topic
  • New Topic

spring rest controllers  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a rest controller with class level request mapping and each method has individual request mapping. As i need to add few more methods, i have decided to have another controller (Class B). I still want to keep request mapping "/base" from old controller (Class A). Is there a better way to do this as i don't like appending  "base/" in each method in class B.

@Restcontroller
@requestMapping("/base")
Class A {

  @requestMapping("/first")
   methodA(){
}
}

@Restcontroller
Class B {

  @requestMapping("/base/second")
   methodB(){
}

  @requestMapping("/base/third")
   methodC(){
}
}
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code snippet you have provided, there is an inherent link between class A & B since they have a linked base mapping. This indicates that there is some commonality at the base class/interface level . You need to manifest and implement the same in the code as well.
You can have both the classes implement the same Interface/base class and provide base RequestMapping there.
You can then have just the method level RequestMapping in the implementation classes.

@RequestMapping("/base")
public interface BaseRestInterface{
}

@RestController
public class A implements BaseRestInterface{

  @RequestMapping("/first")
   methodA(){
}
}

@RestController
public class B implements BaseRestInterface{

  @RequestMapping("/second")
   methodB(){
}

  @RequestMapping("/third")
   methodC(){
}
}

The org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping would register the URLs while scanning the controller classes. you should see the below messages in the Tomcat console/logs:

INFO: Mapped "{[/base/first]}" onto ...A.methodA()
INFO: Mapped "{[/base/second]}" onto ....B.methodB()
INFO: Mapped "{[/base/first]}" onto ...C.methodC()

Ensure you use latest spring framework jars (Spring 5+ would be best, I think 4.3+ at least)



With Regards
Kiran Tiwari

www.sevenmentor.com
 
Ranch Hand
Posts: 1054
2
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice example, but I think you have a typo.  That should be "/base/third" correct?




 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!