SpinrMVC方法返回值(二)

方法返回Object类型

返回Object类型需要在xml配置文件中声明一个注解驱动

    <context:component-scan base-package="day09"></context:component-scan>

  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
//注解驱动 <mvc:annotation-driven></mvc:annotation-driven>

下边是Object作为返回值的一些方法代码:

返回数值型

    /*
    * 返回数值型
    * */
    @RequestMapping("/first")
    @ResponseBody
    public Object doFirst(){
        return 1;
    }

返回字符串

    //返回字符串  解决乱码
    @RequestMapping(value = "/second",produces = "text/html;charset=utf-8")
    @ResponseBody
    public Object doSecond(){
        return "我是返回字符串";
    }

返回对象

    //返回对象
    @RequestMapping("/third")
    @ResponseBody
    public Object doThird(){
        Student stu=new Student();
        stu.setUname("明天会更好");
        stu.setUpwd("没有密码");
        return  stu;
    }

返回集合

    //返回List集合
    @RequestMapping("/four")
    @ResponseBody
    public Object doFour(){
        List<Student> list=new ArrayList<Student>();
        Student stu=new Student();
        stu.setUname("明天会更好");
        stu.setUpwd("没有密码");
        Student stu1=new Student();
        stu1.setUname("十万个为什么");
        stu1.setUpwd("没有密码");
        list.add(stu);
        list.add(stu1);
        return list;
    }
原文地址:https://www.cnblogs.com/1234AAA/p/8669331.html