基于注解的spring MVC程序

2021-09-24 10:22:53 浏览数 (1)

修改配置文件

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        ">

<!-- 自动装配bean -->

<!-- 自动检测bean -->
    <context:component-scan
        base-package="com.hellospringmvc"
    ></context:component-scan>

<!-- 配置处理器映射器 -->
<!-- 使用RequestMappingHandlerMapping需要在Handler 中使用@controller标识此类是一个控制器,使用@requestMapping指定Handler方法所对应的url -->
<bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
</bean>

<!-- 配置处理器适配器 -->
<!-- RequestMappingHandlerAdapter,不要求Handler实现任何接口,它需要和RequestMappingHandlerMapping注解映射器配对使用,主要解析Handler方法中的形参 -->
<bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>


<!-- 配置视图解析器
    要求将jstl的包加到classpath
 -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/" />
      <property name="suffix" value=".jsp" />
   </bean>
</beans></pre> 

 修改类
package com.hellospringmvc;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {

@RequestMapping("/queryItems")
public ModelAndView queryItems(){

    //商品列表
    List<Item> itemsList = new ArrayList<Item>();

    Item items_1 = new Item();
    items_1.setName("联想笔记本");
    items_1.setPrice(6000f);
    items_1.setDetail("ThinkPad T430 联想笔记本电脑!");

    Item items_2 = new Item();
    items_2.setName("苹果手机");
    items_2.setPrice(5000f);
    items_2.setDetail("iphone6苹果手机!");

    itemsList.add(items_1);
    itemsList.add(items_2);

    //创建modelAndView准备填充数据、设置视图
    ModelAndView modelAndView = new ModelAndView();

    //填充数据
    modelAndView.addObject("itemsList", itemsList);
    //视图
    modelAndView.setViewName("helloController");

    return modelAndView;
}



}</pre> 

0 人点赞