SpringMVC - 注解的Handler

来源:互联网 发布:mac怎么看运行的程序 编辑:程序博客网 时间:2024/06/14 03:42

一、dispatcher-servlet.xml 文件的配置

<!-- 注解的 Handler可以单独配置--><!--<bean class="club.lemos.ssm.controller.ItemsController3"/>--><!-- 实际开发中,建议使用组件扫描可以扫描controller、service...这里扫描controller,需要指定controller的包。--><context:component-scan base-package="club.lemos.ssm.controller"></context:component-scan><!-- 注解处理器适配器--><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/><!-- 注解处理器映射器--><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/><!-- 使用 mvc:annotation-driven标签可以代替上面的两个注解器的配置。此外 mvc:annotation-driven标签还默认加载了很多参数绑定的方法,比如:默认加载了json转换解析器。如果使用上面的注解器配置,则需要额外配置这些参数--><!--<mvc:annotation-driven></mvc:annotation-driven>-->

注意:初次使用idea开发spingmvc 时,约束文件头标签可能导入出错,导致使用<context:component-scan />标签,显示错误。此时可以尝试删除错误的约束引用,重新开始导入约束文件。

二、Handler 类的编写

//使用 Controller标识它是控制器@Controllerpublic class ItemsController3 {    //RequestMapping 实现对 queryItems方法和url进行映射。一个方法对应一个url。    //建议将注解映射器的url和方法名设为相同。url可以加".action"后缀,也可以不加。    @RequestMapping("queryItems")    public ModelAndView queryItems() {        List<Items> itemsList = new ArrayList<Items>();        Items items_1 = new Items();        items_1.setName("联想笔记本");        items_1.setPrice(6000f);        items_1.setDetail("ThinkpPad 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);        ModelAndView modelAndView = new ModelAndView();        modelAndView.addObject("itemsList", itemsList);        modelAndView.setViewName("WEB-INF/jsp/items/itemsList.jsp");        return modelAndView;    }}
0 0