三、SpringMVC註解的處理器映射器和適配器

默認加載

前端控制器從\org\springframework\web\servlet\DispatcherServlet.properties件中加載處理器映射器、適配器、視圖解析器等組件,若是不在springmvc.xml中配置,則使用默認加載的前端

註解的處理器映射器和適配器java

  • 在spring3.1以前使用org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping註解映射器。
  • 在spring3.1以後使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping註解映射器。
  • 在spring3.1以前使用org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter註解適配器。
  • 在spring3.1以後使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter註解適配器

註解的處理器映射器和適配器

<!-- 註解的映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!-- 註解的適配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

或者web

<!-- 
使用mvc:annotation-driven代替上面兩個註解映射器和註解適配的配置。mvc:annotation-driven默認加載不少的參數綁定方法,好比json轉換解析器默認加載了,若是使用mvc:annotation-driven則不用配置上面的RequestMappingHandlerMapping和RequestMappingHandlerAdapter實際開發時使用mvc:annotation-driven
-->
<mvc:annotation-driven></mvc:annotation-driven>

開發註解Handler

使用註解的映射器和註解的適配器。(註解的映射器和註解的適配器必須配對使用)spring

//@Controller標識它是一個控制器
@Controller
public class ItemsController3 {

    // @RequestMapping實現對queryItems方法和url進行映射,一個方法對應一個url。
    //通常建議將url和方法寫成同樣
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception{
        //使用靜態數據模擬,查詢商品列表
        List<Items> itemsList = new ArrayList<Items>();

        //向list中填充靜態數據
        Items items_1 = new Items();
        items_1.setName("聯想筆記本");
        items_1.setPrice(6000f);
        items_1.setDetail("ThinkPad T430 c3 聯想筆記本電腦!");

        Items items_2 = new Items();
        items_2.setName("蘋果手機");
        items_2.setPrice(5000f);
        items_2.setDetail("iphone6蘋果手機!");

        itemsList.add(items_1);
        itemsList.add(items_2);

        //返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        //至關於request的setAttribute方法,在jsp頁面中經過itemsList取數據
        modelAndView.addObject("itemsList",itemsList);

        //指定視圖
        modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
        return modelAndView;
    }
}

在spring容器中加載Handler

<!-- 對於註解的Handler能夠單個配置,實際開發中能夠使用組件掃描-->
<!--  <bean  class="com.iot.ssm.controller.ItemsController3"/> -->

<!-- 能夠掃描controller、service、...這裏讓掃描controller,指定controller的包-->
<context:component-scan base-package="com.iot.ssm.controller"></context:component-scan>
相關文章
相關標籤/搜索