非注解的处理器映射器
<!-- 配置Handler -->
<bean id="itemsController" name="/queryItems.action" class="com.echodemo.ssm.controller.ItemsController"/>
<!-- 处理器映射器
将bean的name作为url进行查找,需要在配置Handler时指定beanname(就是url)
所有的映射器都实现HandlerMapping接口
-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 简单的url映射 -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<!-- 对itemsController进行url映射,key表示访问的路径,itemsController表示Handler的id -->
<prop key="/queryItems1.action">itemsController</prop>
<prop key="/queryItems2.action">itemsController</prop>
</props>
</property>
</bean>
多个映射器可并存,前端控制器判断url能让哪些映射器处理就让正确的映射器处理。
非注解的处理器适配器
<!-- 配置处理器适配器,所有处理器适配器都实现了HandlerAdapter接口,编写的Handler实现Controller接口 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!-- 另一个处理器适配器,编写的Handler实现HttpRequestHandler接口 -->
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
实现HttpRequestHandler接口的ItemsController1:
package com.echodemo.ssm.controller;
import com.echodemo.ssm.bean.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 ItemsController1 implements HttpRequestHandler {
@Override
public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
//调用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);
// 设置模型数据
httpServletRequest.setAttribute("/WEB-INF/jsp/itemsList.jsp", itemsList);
// 设置转发的视图
httpServletRequest.getRequestDispatcher("items/itemsList")
.forward(httpServletRequest, httpServletResponse);
/*
*HttpRequestHandler适配器的handleRequest方法返回为void,
*没有返回ModelAndView,可通过response修改响应内容,比如返回json数据:
*/
// httpServletResponse.setCharacterEncoding("utf-8");
// httpServletResponse.setContentType("application/json;charset=utf-8");
// httpServletResponse.getWriter().write("json串");
}
}