博客
关于我
非注解和注解的处理器映射器、处理器适配器
阅读量:322 次
发布时间:2019-03-03

本文共 2006 字,大约阅读时间需要 6 分钟。

Spring MVC 处理器映射器和处理器适配器配置

在Spring MVC应用中,处理器映射器和处理器适配器是核心组件,它们负责将HTTP请求映射到具体的Controller方法并执行。以下将详细介绍两种配置方式:非注解形式和注解形式。


一、非注解形式配置

在非注解形式中,处理器映射器和处理器适配器的配置信息通常存放在Spring MVC的配置文件(如springmvc.xml)中。这种方式虽然代码量较多,但配置相对灵活。

处理器映射器配置

使用SimpleUrlHandlerMapping作为示例,配置文件中可以通过<prop>标签将URL请求映射到对应的Controller类:

userController
userController
userController2

然后在配置文件中声明对应的Controller实现类:

处理器适配器配置

处理器适配器负责将处理器映射器返回的执行链与具体的Handler匹配。在非注解形式中,使用HttpRequestHandlerAdapter:

此外,还需要确保Controller实现类支持HttpRequestHandler接口。以下是一个示例实现:

public class UserControllerTest2 implements HttpRequestHandler {    private UserService userService;    @Override    public void handleRequest(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {        List
userList = userService.queryUserList(); request.setAttribute("userList", userList); request.getRequestDispatcher("/WEB-INF/jsp/users/userList.jsp").forward(request, response); }}

二、注解形式配置

注解形式的配置通过在Controller类和方法上使用Spring的注解(如@Controller、@RequestMapping)实现,配置文件的代码量大大减少,开发效率更高。

处理器映射器配置

在Spring MVC配置文件中使用RequestMappingHandlerMapping:

处理器适配器配置

使用RequestMappingHandlerAdapter:

或者可以使用Spring的简写配置<mvc:annotation-driven />,默认注册上述两个bean。

Controller实现

在Controller类上使用@Controller注解,并在方法上使用@RequestMapping指定URL:

@Controllerpublic class AnnotateControllerTest {    private UserService userService;    @RequestMapping("/queryUserList")    public ModelAndView queryUserList() {        List
userList = userService.queryUserList(); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("userList", userList); modelAndView.setViewName("/WEB-INF/jsp/users/userList.jsp"); return modelAndView; }}

在配置文件中扫描Controller包:


总结

两种配置方式各有优缺点。非注解形式适合对注解不熟悉的开发者,配置相对直观;而注解形式代码简洁,易于维护。根据项目需求选择合适的方式进行配置即可。

转载地址:http://nntm.baihongyu.com/

你可能感兴趣的文章
Python--Redis实战:第四章:数据安全与性能保障:第4节:复制
查看>>
python--基本代码规范
查看>>
Python--抽象类接口类
查看>>
PYTHON--欧拉习题二
查看>>
python--高级应用总结
查看>>
python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
查看>>
Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
查看>>
Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
查看>>
Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
查看>>
python出现 unknown encoding: idna 的处理方法
查看>>
Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
查看>>
Python-numpy(2)数组的操作
查看>>
Python-Numpy的tile函数用法
查看>>
python-open函数
查看>>
Python-Pandas-将特定函数应用于给定级别-多索引数据框架
查看>>
python-queue队列通信
查看>>
python-ros No module named PyKDL
查看>>
python-social-auth 是否需要会话
查看>>
Python再获年度编程语言,微软或成最大赢家
查看>>
python-week5
查看>>