1

I imported the Getting Started - Securing a Web Application in STS and added a controller for navigation, the request gets called and the return value instead of redirecting gets displayed in the browser. Any idea why it does this and how to fix it?

Here is the code:

@RestController
public class BetController {

@RequestMapping("/")
public String username(Model model) {
    System.out.println("Test");
    model.addAttribute("username", WebSecurityConfig.getUsername());
    return "statpage";
}

The page start page is registered in this manner:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("startpage");
    registry.addViewController("/login").setViewName("login");
}

All I get in the browser is a blank page with "startpage" on it, looking at the page's source there is no html just "startpage"

Samantha Catania
  • 5,116
  • 5
  • 39
  • 69
  • 1
    You have annotated your controller with `@RestController` instead of `@Controller`. – M. Deinum Jan 05 '15 at 10:40
  • @RestController is just for convenience http://stackoverflow.com/questions/25242321/difference-between-spring-controller-and-restcontroller-annotation – Samantha Catania Jan 05 '15 at 10:49
  • I strongly suggest you read up on what `@RestController` does as judging from what you are doing and your comment you are lacking that understanding. Trust me chancing it will make it work... – M. Deinum Jan 05 '15 at 11:10
  • I tried switching '@RestController' to '@Controller' but it didn't solve the issue – Samantha Catania Jan 06 '15 at 12:04
  • 1
    There is also another issue with your code or at least how you expect it to work. You return the name of a view, this viewname is resolved to an actual view by a `ViewResolver`. What you have configured is that the `/` url will render a `startpage` view. I suspect that you get a 404 now in stead of `statpage` (which should be `startpage` I guess). – M. Deinum Jan 06 '15 at 12:14
  • After I changed some view names and file names it made a difference and started working – Samantha Catania Jan 06 '15 at 12:32

1 Answers1

0

Returning ModelAndView instead of a String in the RequestMapping method solved the problem:

@RequestMapping("/")
public ModelAndView username(Model m) {
    ModelAndView mav = new ModelAndView();
    mav.addObject("username", WebSecurityConfig.getUsername());
    mav.setViewName("betting");
    return mav;
}

Another solution is changing @RestController to @Controller and making sure all the names match

Samantha Catania
  • 5,116
  • 5
  • 39
  • 69