本文主要介绍非注解的处理器映射器和适配器配置
非注解的处理器映射器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <bean id ="itemsController" name ="/queryItems.action" class ="com.iot.ssm.controller.ItemsController" /> <bean class ="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <bean class ="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name ="mappings" > <props > <prop key ="/queryItems1.action" > itemsController</prop > <prop key ="/queryItems2.action" > itemsController</prop > </props > </property > </bean >
多个映射器可并存,前端控制器判断url能让哪些映射器处理就让正确的映射器处理
非注解的处理器适配器 1 2 3 4 <!-- 处理器适配器 所有处理器适配器都实现了HandlerAdapter接口 --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
要求编写的Handler实现Controller
接口
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
要求编写的Handler实现HttpRequestHandler
接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 package com.iot.ssm.controller;import com.iot.ssm.po.Items;import org.springframework.web.HttpRequestHandler;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.ArrayList;import java.util.List;public class ItemsController2 implements HttpRequestHandler { public void handleRequest (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { List<Items> itemsList = new ArrayList<Items>(); 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); httpServletRequest.setAttribute("itemsList" ,itemsList); httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/items/itemsList.jsp" ).forward(httpServletRequest,httpServletResponse); } }
HttpRequestHandler
适配器的handleRequest
方法返回为void
,没有返回ModelAndView
,可通过response修改响应内容,比如返回json数据:
1 2 3 response.setCharacterEncoding("utf-8" ); response.setContentType("application/json;charset=utf-8" ); response.getWriter().write("json串" );