1. SpringMVC方法的返回值类型

3.1String类作为返回值

3.1.1Controller层

/**
 * 返回值类型为String时,一般用于返回视图名称
 * 1、当方法返回值为null时,默认将请求路径当做视图   forward:/jsp/index.jsp       如果说没有视图解析器,返回值为null携带数据只能用json
 * 2、当方法返回一个String的字符串时,当字符串为逻辑视图名时只返回视图,如果携带数据则使用request,session或者json
 * 3、当方法返回值加入forward时代表转发,如果写为redirect:xxxx代表重定向,不是返回视图了,但是不会这样做!!
 */
@RequestMapping("/condRequest")
public String secondRequest(HttpServletRequest request, HttpServletResponse response){
    request.setAttribute("user","张三");
    return "forward:/jsp/index.jsp";
}

3.1.2页面

3.2void作为返回值

3.2.1Controller层

/**
 * 如果方法写成了void就跟原来servlet含义是差不多 的
 * json
 */
@RequestMapping(value = "/firstRequest",produces = "text/json;charset=utf-8")
public void firstRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
    Invoicing info=new Invoicing();
    info.setUserName("张三");
    info.setPassword("123");
    /**
     * json格式传递
     */
    response.setCharacterEncoding("UTF-8");
    String value= JSON.toJSONString(info);
    response.getWriter().write(value);
}

3.2.2页面

3.3ModelAndView作为返回值

3.3.1Controller层

/**
 * ModelAndView
 * @param request   请求对象
 * @param response  响应对象
 * @return    ModelAndView  model是用来传递数据用的,view是所需要跳转的页面
 */
@RequestMapping("/model")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response){
    ModelAndView modelAndView=new ModelAndView();
    //携带给页面数据
    modelAndView.addObject("user","鸭头");
    //指定跳转页面(视图解析器配置前后缀)
    modelAndView.setViewName("index");
    return modelAndView;
}

3.3.2页面

3.4Object作为返回值类型

3.4.1Controller层

/**
 *Object
 * 1.当方法返回值为null时,默认将请求路径当作视图  jsp/objectRequest.jsp  如果没有视图解析器,如果返回值为null携带数据只能用json
 * 2.当方法返回值为String类型字符串时,就是视图的逻辑名称
 * 3.当返回对象或者集合数据时要使用json格式字符串,可选fashjson手动转换 ,也可以使用jackson自动转换
 */
@RequestMapping("/objectRequest")
@ResponseBody
public  Object objectRequest(){
    List<Invoicing> invoicingList=new ArrayList<>();
    Invoicing invoicing=new Invoicing();
    invoicing.setUid(1);
    invoicing.setUserName("aaa");
    invoicing.setPassword("123");
    invoicing.setRealName("张三");
    invoicingList.add(invoicing);
    return invoicingList;
}

3.4.2页面

2. Spring MVC的自动装配

4.1请求参数的自动类型转换

JSP页面创建表单

<form method="post" action="/formRequest">
    姓名:<input id="userName" name="userName" class="userName"/><span></span><br/>
    密码:<input id="password"name="password" class="password"/><br/>

    <input type="submit" class="submit"/>
</form>
/**
 * 接收零散参数:装配原则为传递参数名和方法接收参数名
 * 手动装配@RequestParam   name代表页面发送的参数名字 ,required代表参数是否必须传递  false
 * 代表不传递,默认为true defaultValue代表默认  model代表给页面传递的数据
 */

@RequestMapping(value = "/formRequest")
public String formRequest(String userName,String password){
    System.out.println(userName+"\t"+password);
    return "welcome";
}

注意点*:控制器Controller中的方法参数名称必须和表单元素的name属性值保持一致

4.2使用@RequestParam注解

@RequestParam的作用是,当表单元素与控制器方法的参数不匹配的情况下,使用@RequestParam注解声明参数名称。

@RequestParam 有三个属性:

(1)value:请求参数名(必须配置)

(2)required:是否必需,默认为 true,即 请求中必须包含该参数,如果

没有包含,将会抛出异常(可选配置)

(3)defaultValue:默认值,如果设置了该值,required 将自动设为 false,

无论你是否配置了required,配置了什么值,都是 false(可选配置)

/**
 * 接收零散参数:装配原则为传递参数名和方法接收参数名
 * 手动装配@RequestParam   name代表页面发送的参数名字 ,required代表参数是否必须传递  false
 * 代表不传递,默认为true defaultValue代表默认  model代表给页面传递的数据
 */

@RequestMapping(value = "/formRequest")
public String formRequest(@RequestParam(name="userName",required = false,defaultValue = "张三")String username,@RequestParam(name = "password",required = false,defaultValue = "123")String password){
    System.out.println(username+"\t"+password);
    return "welcome";
}

4.3请求参数自动装配为对象

/*
* 对象参数:传递的对象参数和对象中的属性名保持一致
* */
@RequestMapping("/invoivingObject")
public String invoivingObject(Invoicing invoicing){
    System.out.println(invoicing.getUserName());
    return "welcome";
}

4.4restful风格参数传递

在使用 RESTful 风格之前,我们如果想要增加一条商品数据通常是这样的:

但是使用了 RESTful 风格之后就会变成:

/**
 * get请求时,如果需要传递参数,那么则把不能使用以往的方式?name=xxx&age=yy,但是现在要遵循restful风格,例:xxx/ttt/ddd
 * 根据地址栏url匹配拿值  使用@PathVariable(name=地址栏中的参数映射)
 *
 */

@RequestMapping("/restfulRequest/{b}/{d}")
@ResponseBody
public String restfulRequest(@PathVariable(name = "b") String username, @PathVariable(name = "d")String password){
    System.out.println(username+"\t"+password);
    return "welcome";
}

4.5域属性对象传递参数

<form method="post" action="/invoivingObject">
    姓名:<input id="userName" name="userName" class="userName"/><span></span><br/>
    密码:<input id="password"name="password" class="password"/><br/>
    teacherName1<input id="t_name" class="t_name" name="teacher.t_name"/>
    <input type="submit" class="submit"/>
</form>
public class Invoicing {
    private  Integer uid;
    private  String userName;
    private  String password;
    private  String realName;
    private Teacher teacher;
    private List<Teacher> teachersList;
    public List<Teacher> getTeachersList() {
        return teachersList;
    }
    public void setTeachersList(List<Teacher> teachersList) {
        this.teachersList = teachersList;
    }
    public Teacher getTeacher() {
        return teacher;
    }
    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }
    public Integer getUid() {
        return uid;
    }
    public void setUid(Integer uid) {
        this.uid = uid;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    @Override
    public String toString() {
        return "Invoicing{" +
                "uid=" + uid +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", realName='" + realName + '\'' +
                ", teacher=" + teacher +
                ", teachersList=" + teachersList +
                '}';
    }
}
 /*
* 域属性传递:传递参数为:域属性名.属性名
* */
@RequestMapping("/invoivingObject")
public String invoivingObject(Invoicing invoicing){
    System.out.println(invoicing.getUserName());
    return "welcome";
}

4.6域属性集合传递参数

<form method="post" action="/invoivingObject">
    姓名:<input id="userName" name="userName" class="userName"/><span></span><br/>
    密码:<input id="password"name="password" class="password"/><br/>
    teacherName2<input id="t_name" class="t_name" name="teachersList[0].t_name"/>
    teacherName3<input id="t_name1"  name="teachersList[1].t_name"/>

    <input type="submit" class="submit"/>
</form>
public class Invoicing {
    private  Integer uid;
    private  String userName;
    private  String password;
    private  String realName;
    private Teacher teacher;
    private List<Teacher> teachersList;
    public List<Teacher> getTeachersList() {
        return teachersList;
    }
    public void setTeachersList(List<Teacher> teachersList) {
        this.teachersList = teachersList;
    }
    public Teacher getTeacher() {
        return teacher;
    }
    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }
    public Integer getUid() {
        return uid;
    }
    public void setUid(Integer uid) {
        this.uid = uid;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    @Override
    public String toString() {
        return "Invoicing{" +
                "uid=" + uid +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", realName='" + realName + '\'' +
                ", teacher=" + teacher +
                ", teachersList=" + teachersList +
                '}';
    }
}

/*
* 集合参数传递:集合名[下标].属性名
* */

@RequestMapping("/teacherInvoicing")
@ResponseBody
public String teacherInvoicing(Invoicing invoicing){
    System.out.println(invoicing.getTeachersList());
    return "welcome";
}

Spring MVC的方法返回值和参数传递的更多相关文章

  1. Spring MVC同一方法返回JSON/XML格式

    最近一道面试题,要求同一API接口支持不同格式返回值.一开始是设想通过过滤器(Filter)设置返回值,但是并不可行,因为方法返回值一般都是类型需要做转换,而过滤器则是前置的.另一方面可以通过拦截器的 ...

  2. Spring MVC--------处理方法返回值的可选类型

    对于Spring MVC处理方法支持支持一系列的返回方式:  (1)ModelAndView (2)Model (3)ModelMap (4)Map (5)View (6)String (7)Void ...

  3. spring3 mvc:方法返回值的学习

    新建后台代码用以测试返回类型,在这里我新建的如下: /** * 项目名称:Spring3mvc demo * Copyright ? 2010-2012 spartacus.org.cn All Ri ...

  4. Spring MVC中Controller返回值void时报错

    Controller如下: 当使用url访问该处理器方法时,报错如下: 26-Jan-2019 21:16:28.105 警告 [http-nio-8080-exec-39] org.springfr ...

  5. spring mvc处理方法返回方式

    Model: package org.springframework.ui; import java.util.Collection; import java.util.Map; public int ...

  6. Spring MVC学习之三:处理方法返回值的可选类型

    http://flyer2010.iteye.com/blog/1294400 ———————————————————————————————————————————————————————————— ...

  7. Spring MVC 3.0 返回JSON数据的方法

    Spring MVC 3.0 返回JSON数据的方法1. 直接 PrintWriter 输出2. 使用 JSP 视图3. 使用Spring内置的支持// Spring MVC 配置<bean c ...

  8. SpringBoot系列: Spring MVC视图方法的补充

    SpringMVC 视图方法的参数, 已经在这个文章中写得非常清楚了, 链接为 https://www.cnblogs.com/morethink/p/8028664.html 这篇文章做一些补充. ...

  9. SpringMVC入门(二)—— 参数的传递、Controller方法返回值、json数据交互、异常处理、图片上传、拦截器

    一.参数的传递 1.简单的参数传递 /* @RequestParam用法:入参名字与方法名参数名不一致时使用{ * value:传入的参数名,required:是否必填,defaultValue:默认 ...

随机推荐

  1. php中比较复杂但又常用的字符串函数

    php系统核心库自带的函数中,字符串比数组函数较为简单,但还是有一些较为复杂但又很常用的函数,比如下面的这些函数 explode()函数 用一个字符串来分割另一个字符串,返回结果是一个数组 explo ...

  2. 通过tushare获取股票价格

    # Author llll # coding=utf-8 # ---描述# 完成股票 价格查询和展示# 不直接根据网页进行爬虫获取股票价格,而是通过已有组件查询股票价格,并保存到csv文件或者exce ...

  3. ~postman使用Runner

    1.准备参数的.text文件. postman支持三种参数的方式,分别为.text文件,.csv文件,json文件.此处使用.text文件.编码格式使用utf-8 2.替换请求参数 3.设置Runne ...

  4. C++动态内存常见面试题解析

           malloc/free和new/delete傻傻分不清?动态内存管理的面试题难道你了?来看这篇文章,包你全会. 1.malloc/free和new/delete的区别   (1)mall ...

  5. Vue.js 2.x 混入

    Vue.js 2.x mixins 混入 混入(mixins)是一种分发vue组件中可复用功能的非常灵活的方式.混入对象可以包含任意组件选项.当组件使用混入对象时,所有混入对象的选项将被混入该组件本身 ...

  6. 偷窥篇:重要的C#语言特性——30分钟LINQ教程

    本文转自:http://www.cnblogs.com/liulun/archive/2013/02/26/2909985.html 千万别被这个页面的滚动条吓到!!! 我相信你一定能在30分钟之内看 ...

  7. WPF不同方式快捷键判断

    private void Window_PreviewKeyDown(object sender, KeyEventArgs e) { //单个按键e.Key方式判断 if (e.Key == Key ...

  8. .NET调用腾讯云API实例

    最近项目有用到腾讯云的身份识别接口,话不多说,直接上代码: private void IDCardVerification(HttpContext context) { string imgStr = ...

  9. 测试winform程序到树莓派运行

    啥也不说了,都在下图中了.winform可以在树莓派上跑了

  10. 【转载】 腾讯云通过设置安全组禁止某些IP访问你的服务器

    有时候我们在运维网站的过程中会发现一些漏洞扫描者的IP信息,或者个人爬虫网站的IP信息,此时我们想禁止掉这些IP访问到你的服务器,可以通过腾讯云的安全组功能来设置禁止这些IP访问你的服务器,也可以通过 ...