Spring:SpringMVC 使用非注解方式和注解方式
SpringMVC配置的组件众多,如果单纯的在xml文件中进行配置,需要配置处理器映射器,处理器适配器,处理器,处理器解析器.尤其是处理器的配置,并且还得指定处理器的name,才能完成请求地址到handler之间的映射.相比较于注解方式,注解方式实在是太麻烦了.
但是,我们还是先来看看两种配置方式的具体做法吧!
1.1 使用非注解方式
1.1.1 处理器映射器
使用BeanNameUrlHandlerMapping:
它能够完成Handler的bean的name和url之间的映射
1 | <!--配置处理器映射器--> |
使用SimpleUrlHandlerMapping:
它可以批量完成Handler和url之间的映射
1 | <!--通过Handler的ID值完成url和Handler的映射--> |
上述两种方式都能完成url到handler的映射
1.1.2 处理器适配器
使用:
SimpleControllerHandlerAdapter,它能够调用的Handler必须实现org.springframework.web.servlet.mvc包下的Controller接口UserController处理器:
1 | public class UserController implements Controller { |
SimpleControllerHanderAdapter的配置:
1 | <!--配置处理器适配器--> |
使用
HttpRequestHandlerAdapter,他只能适配HttpRequestHandler实现类型的ControllerOrdersController处理器:
1
2
3
4
5
6
7
8
9public class OrdersController implements HttpRequestHandler {
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 接下来的开发像极了使用Servlet的原生开发
response.getWriter().print(getClass().getSimpleName() + ",hello!");
request.getRequestDispatcher("jsp/helloworld.jsp").forward(request, response);
}
}HttpRequestHandlerAdapter配置:
1
2<!--他只能适配HttpRequestHandler实现类型的Controller-->
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"/>上面两种非注解的处理器适配器能够适配不同类型的Handler(也称作Controller)
使用注解的方式
在applicationContext.xml中配置:
1 | <!--使用注解的方式配置Handler以后,需要将处理器映射器和处理器适配器配置为以下的方式--> |
或者使用:
1 | <mvc:annotation-driven/> |
上面这一句就可以在Spring容器中自动的帮我们注册RequestMappingHandlerMapping和RequestMappingHandlerAdapter.
编写Controller类:
1 |
|
RequestMappingHandlerMapping能够完成url到该方法的映射.另外,FirstAnnoController中也可以配置多个方法,只要他们的@RequestMapping注解中value不一样就可以,这样一个Controller中可以实现多种功能.
另外:在applicationContext.xml中开启组件扫描,@Controller就能被自动扫描到并被Spring容器管理
测试:在浏览器中输入地址:http://localhost:8080/ssm/firstanno.action就能自动跳转到jsp/helloworld.jsp页面