springmvc学习笔记(3)-注解的处理器映射器和适配器

springmvc学习笔记(3)-注解的处理器映射器和适配器

标签: springmvc前端


[TOC]java


本文主要介绍注解的处理器映射器和适配器相关配置git

默认加载

前端控制器从\org\springframework\web\servlet\DispatcherServlet.properties件中加载处理器映射器、适配器、视图解析器等组件,若是不在springmvc.xml中配置,则使用默认加载的github

注解的处理器映射器和适配器web

  • 在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"/>

或者spring

<!-- 使用mvc:annotation-driven代替上面两个注解映射器和注解适配的配置
     mvc:annotation-driven默认加载不少的参数绑定方法,
     好比json转换解析器默认加载了,若是使用mvc:annotation-driven则不用配置上面的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
     实际开发时使用mvc:annotation-driven
     -->
    <mvc:annotation-driven></mvc:annotation-driven>

开发注解Handler

使用注解的映射器和注解的适配器。(使用注解的映射器和注解的适配器必须配对使用)数据库

//使用@Controller来标识它是一个控制器
@Controller
public class ItemsController3 {

    //商品查询列表
    @RequestMapping("/queryItems")
    //实现 对queryItems方法和url进行映射,一个方法对应一个url
    //通常建议将url和方法写成同样
    public ModelAndView queryItems() throws Exception{
        //调用service查找数据库,查询商品列表,这里使用静态数据模拟
        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>

参考资料


做者@brianway更多文章:我的网站 | CSDN | oschinajson

相关文章
相关标签/搜索