三、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>
相关文章
相关标签/搜索