2015-09-07 29 views
1

我是新來Spring MVC的 &經歷克雷格牆Spring4 in Action關係B/W的控制方法視圖名稱和@RequestMapping(值= 「/ ...」)Spring MVC中

考慮片斷,

@RequestMapping(value = "/spittles", method = RequestMethod.GET) 
    public String spittles(Model model, @RequestParam("max") long max, 
          @RequestParam("count") int count) { 

     model.addAttribute("spittleList",spittleRepository.findSpittles(max, count)); 

     return "spittles";     // <-- return view name 
} 

該圖像示出了spittles.jsp駐留在/WEB-INF /視圖/

enter image description here

WebConfig的.java

@Configuration 
@EnableWebMvc     // Enable Spring MVC 
@ComponentScan(basePackages={"org.spittr"}) 
public class WebConfig extends WebMvcConfigurerAdapter { 

    @Bean 
    public ViewResolver viewResolver() { 

     InternalResourceViewResolver resolver = 
      new InternalResourceViewResolver(); 
     resolver.setPrefix("/WEB-INF/views/"); 
     resolver.setSuffix(".jsp"); 
     resolver.setExposeContextBeansAsAttributes(true); 

     return resolver; 
    } 

    @Override 
    public void configureDefaultServletHandling(
         DefaultServletHandlerConfigurer configurer) { 

     /* configure static content handling */ 
     configurer.enable(); 
    } 



} 

1)爲什麼我需要返回字符串「spittles」在控制器的方法?

2)是否(返回字符串)保持對所述

@RequestMapping的關係(值= 「/ spittles」,方法= RequestMethod.GET)

作爲值(/spittles)是相同的控制器方法中返回的字符串?

3)爲什麼我看不到一個.jsp擴展當我進入URL

http://localhost:8080/web/spittles?max=238900&count=5

O/p被解析爲:enter image description here

+0

這一切都與視圖解析器如何在MVC中工作有關。廣告1)這是應該顯示給用戶的視圖(jsp頁面)的名稱。廣告2)號碼URL映射與視圖解析不直接相關。廣告3)在MVC中,您只能看到視圖的名稱(JSP只是表示層,您可以使用Thymeleaf而不是JSP,它將以非常類似的方式工作)。 –

+0

@ R4J:但是,如果我只是從控制器方法返回null,它也可以工作。 –

+1

是的,即使你返回null也行,因爲視圖解析器InternalResourceViewResolver通過爲jsp添加前綴/後綴來解析@Controllers的視圖。如果該JSP存在,那麼它呈現其他顯示jsp未找到錯誤。 –

回答

1

您的問題:

  1. 字符串「spittles」將被傳遞給視圖解析器,它看起來的視圖/WEB-INF/views/splittles.jsp。如果您返回「hello_world」,則需要查看/WEB-INF/views/hello_world.jsp
  2. 否 - 這是控制器URL。您可以定義一個完全不同的控制器URL,例如/my/super/vality/url如果您願意 - 這只是您接受(GET)請求的路徑。
  3. 查看1.)和2)的答案。儘管它的良好實踐保持了Spring-Controller-URL和JSP視圖名稱的相似性,所以開發人員明白這裏發生了什麼。

例如,你可以有控制器相同的路徑和一個應答GET和其他回答POST請求的方法和兩個導致differne觀點:

@RequestMapping(value = "/spittles", method = RequestMethod.GET) 
public String spittles(Model model, @RequestParam("max") long max, 
         @RequestParam("count") int count) { 
    // ... 
    return "splittles_get"; 
} 

@RequestMapping(value = "/spittles", method = RequestMethod.POST) 
public String spittles(Model model, @RequestParam("max") long max, 
         @RequestParam("count") int count) { 
    // ... 
    return "splittles_post"; 
} 

你甚至可以返回一個相對像splittles/jspName這樣的路徑,這意味着你可以組織你的JSP文件夾 - 這裏/WEB-INF/views/splittles/something.jsp

相關問題