创建spring配置文件:application-context.xml。
创建处理器类
package com.lanou.demo.controller;public class BookController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { }
}
public class OrderServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("OrderServlet.doGet"); } }
public class UserHandller implements HttpRequestHandler { @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("UserHandller.handleRequest"); } }
1.配置处理器对象:
第一种:
<bean id="/book.do" class="com.lanou.demo.controller.BookController"/>
第二种:
<bean id="book1" class="com.lanou.demo.controller.BookController"/> <bean id="orderServlet" class="com.lanou.demo.controller.OrderServlet"/> <bean id="userHandller" class="com.lanou.demo.controller.UserHandller"/> <bean id="controller" class="com.lanou.demo.controller.CategoryController"/>
2.配置处理器映射器:HandlerMapping
第一种:这个处理器映射是根据Handler的bean的名字(也就是id)来进行映射的
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
第二种:简单Url映射
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/book/1">book1</prop>
<prop key="/book/2">book1</prop>
<prop key="/order">orderServlet</prop>
<prop key="/user">userHandller</prop>
</props>
</property>
</bean>
第三种:注解形式:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
配合Controller层的方法上注解@RequestMapping("/url")使用.
3.配置处理器适配器:HandlerAdapter.
<!--处理Servlet实现类类型的Handller 3--> <bean class="org.springframework.web.servlet.handler.SimpleServletHandlerAdapter"/> <!--处理Controller实现类型的Handler 1--> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--处理HttpRequestHandller实现类类型的Handller 4--> <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>
<!--处理RequestMapping注解形式的Handller 2-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
4.配置视图解析器:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<!--视图的前缀-->
<property name="prefix" value="/视图前缀(即前端网页存放的位置)/"/>
<!--视图的后缀-->
<property name="suffix" value="视图后缀(即网页类型:.jsp或.html)"/>
</bean>