Java – Get the @RequestMapping values of different methods in the same controller

Get the @RequestMapping values of different methods in the same controller… here is a solution to the problem.

Get the @RequestMapping values of different methods in the same controller

With Spring Boot, I have several methods in my RegisterController that handle new user registration.

The createNewUser method is responsible for saving the new user to the database and sending a confirmation email with a link with a unique token.

The confirmUser method handles a GET request confirming the link.

Is there a way for the createNewUser method to get the @RequestMapping value assigned to the confirmUser? I want to use this value to generate a confirmation link instead of hardcoding it.

// Process form input data
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult) {

}

 Process confirmation link
 Link in confirmation e-mail will be /registerConfirmation?token=UUID
@RequestMapping(value="/registerConfirmation", method = RequestMethod.GET)
public ModelAndView confirmUser( @RequestParam("token") String token) {

}

Solution

I don’t know of any way to get it from the @RequestMapping value, but you have a few different options.

Option 1: Create a constant for the map and use a constant that allows you to reference it in both methods.

private final static String REGISTER_CONF_VAL = "/registerConfirmation";

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult) {

}

 Process confirmation link
 Link in confirmation e-mail will be /registerConfirmation?token=UUID
@RequestMapping(value=REGISTER_CONF_VAL, method = RequestMethod.GET)
public ModelAndView confirmUser( @RequestParam("token") String token) {

}

Option 2: Less than ideal, but if you add registerConfirmation to your profile, you can access it like this:

@RequestMapping(value="${register.conf.val}", method = RequestMethod.GET)
public ModelAndView confirmUser( @RequestParam("token") String token) {

}

The reason this isn’t ideal is because you probably don’t want it to vary from environment to environment. That is, it will work.

Related Problems and Solutions