EchoDemo's Blogs

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

荷叶罗裙一色裁,芙蓉向脸两边开。

乱入池中看不见,闻歌始觉有人来。

—-唐·王昌龄《采莲曲二首》

默认加载

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

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

(1)在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping注解映射器。

(2)在spring3.1之后使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping注解映射器。

(3)在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter注解适配器。

(4)在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"/>

或者:

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

开发注解Handler

package com.echodemo.ssm.controller;

import com.echodemo.ssm.bean.Items;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ItemsController2 {

    @RequestMapping("/queryItems2")
    public ModelAndView queryItems2() throws Exception{
        //调用service查找数据库,查询商品列表,这里使用静态数据模拟
        List<Items> itemsList = new ArrayList<>();

        //向list中填充静态数据
        Items items_1 = new Items();
        items_1.setName("联想笔记本");
        items_1.setPrice(6000f);
        items_1.setDetail("ThinkPad T430 联想笔记本电脑!");

        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("items/itemsList");
        System.out.println(modelAndView);
        return modelAndView;
    }
}

在spring容器中加载Handler

<!-- 对于注解的Handler 可以单个配置
实际开发中建议使用组件扫描
-->
<!--<bean class="com.echodemo.ssm.controller.ItemsController2"/>-->
<!-- 可以扫描controller、service、...
这里让扫描controller,指定controller的包
 -->
<context:component-scan base-package="com.echodemo.ssm.controller"></context:component-scan>
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------