What does the addViewControllers method of the Webmvcconfigurer Spring boot class do?

Asked

Viewed 232 times

0

I am using Thymeleaf on the front end of the application and have the following configuration class, with the addViewControllers method in question :

@Configuration
public class WebConfig implements WebMvcConfigurer {

    ...

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/admin/home").setViewName("adminhome");
        registry.addViewController("/user/perfil/{email}").setViewName("userperfil");
        registry.addViewController("/home").setViewName("home");
        //registry.addViewController("/403").setViewName("403");  
       } 
         ...
    }

I was thinking that he would be responsible for modifying the urls shown in the browser bar, but he didn’t do it. So I don’t know what he does..

I tested with this existing url in one of the application controllers for example:

@Controller
@RequestMapping("user")
public class UserController {

    private static final Logger LOG = LogManager.getLogger(UserController.class);

    @Autowired
    private UserService userService;

...

    //metodo bastante simplificado..
    @RequestMapping(value = "/perfil/{email}", method = RequestMethod.GET)
    public ModelAndView perfil(@PathVariable("email") String email) {

        ModelAndView view = new ModelAndView();

            User user = userService.findByEmail(email);

                view.addObject("user", user);

                view.setViewName("usuario/perfil");
                LOG.info("Metodo perfil");
                return view;

    }

    ...
}

So in the addViewControllers method I put:

registry.addViewController("/user/perfil/{email}").setViewName("userperfil");

imagining that in the browser would look like this:

http://localhost:8080/userperfil

instead of :

http://localhost:8080/user/perfil/[email protected]

Besides that it would be possible to define these urls "edited"?

1 answer

0

  • Thanks there for the help but, is exactly the opposite of your example, Cool this method,It works even I try my controllers already defined? In that case the Usercotroller?

  • So, as I understand it, he’s a replacement, so I guess not in your case. Another thing, you said that the example is backwards, so when accessing the user/profile/email it would go home? I have no way to test here to see and I wanted to edit the answer for anyone who would see.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.