如果添加了@RestController,则忽略SpringBoot ViewController

时间:2017-01-17 07:39:17

标签: java spring spring-mvc spring-boot

我正在做一些春季启动示例。

一个就像下面一样;

@Controller
public class WebController {

    @GetMapping("/verify")
    public String showForm(PersonForm personForm) {
        return "form";
    }

    @PostMapping("/verify")
    public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "form";
        }
        return "redirect:/results";
    }
}

和配置类:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

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

哪种方法正常。

但是,如果我添加如下所示的RestController,则所有不存在的无效网址都会映射到下面的类(包括根“/”)。我不再获得WhiteLabel错误页面了。 results视图也映射到此类

@RestController
public class GreetingController {

    private static final String baseTemplate = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping(name = "/greeting")
    public Greeting greet(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(baseTemplate, name));
    }
}

添加WebMvcConfiguration时,为什么会忽略RestController?我在这里做错了什么?

注意:我使用的是Spring Boot Version 1.4.3.RELEASE

一些日志

[12:59:03.824][DEBUG][http-nio-8080-exec-1][o.s.w.s.DispatcherServlet]DispatcherServlet with name 'dispatcherServlet' processing GET request for [/results]
[12:59:03.828][DEBUG][http-nio-8080-exec-1][o.s.w.s.m.m.a.RequestMappingHandlerMapping] Looking up handler method for path /results
[12:59:03.835][DEBUG][http-nio-8080-exec-1][o.s.w.s.m.m.a.RequestMappingHandlerMapping] Returning handler method [public com.sample.boot.model.Greeting com.sample.boot.controller.GreetingController.greet(java.lang.String)]
[12:59:03.836][DEBUG][http-nio-8080-exec-1][o.s.w.s.DispatcherServlet] Last-Modified value for [/results] is: -1
[12:59:03.920][DEBUG][http-nio-8080-exec-1][o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor] Written [com.sample.boot.model.Greeting@19aea6b5] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@16a2ed51]
[12:59:03.921][DEBUG][http-nio-8080-exec-1][o.s.w.s.DispatcherServlet] Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
[12:59:03.921][DEBUG][http-nio-8080-exec-1][o.s.w.s.DispatcherServlet] Successfully completed request

0 个答案:

没有答案