SpringMVC_Controller中方法的返回值

时间:2021-07-09 00:27:07
# 返回值的四种类型

1:ModelAndView

2:String

3:void

4:返回自定义类型

# ModelAndView

如果当前的Controller的方法执行完毕后,要跳转到其它jsp资源,又要传递数据,可以使用ModelAndView

package com.doaoao.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloSpringMvc implements Controller
{
    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception
    {
        ModelAndView mv = new ModelAndView();
        mv.addObject("hello", "hello first spring mvc");
        mv.setViewName("/WEB-INF/jsp/first.jsp");
        return mv;
    }
}
# String

如果当前的Controller中的方法执行完毕后,需要跳转到jsp或其它资源上,可以使用String返回值类型(不具备传递数据的能力)

// 跳转道内部资源
package com.monkey1024.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ReturnStringController01 {

    @RequestMapping("/welcome.do")
    public String welcome() throws Exception{
        //直接填写要跳转的jsp的名称 跳转到welcome.jsp上
        return "welcome";
    }
}

// 跳转到外部资源
1:配置springmvc.xml配置文件
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>

    <!--定义外部资源view对象-->
    <bean id="monkey1024" class="org.springframework.web.servlet.view.RedirectView">
        <property name="url" value="http://www.doaoao.com"/>
    </bean>
    
    // id为Controller方法的返回值
    // view为要跳转的外部资源的地址

2:创建一个Controller
    @RequestMapping("/welcome.do")
    public String welcome() throws Exception{

        //直接填写要跳转的jsp的名称
        return "monkey1024";
    }

...

# Model对象和String返回值一起使用

1:创建Controller

@RequestMapping("/welcome1.do")
public String welcome1(String name,Model model) throws Exception{

    //这种写法spring mvc会自动为传入的参数取名
    model.addAttribute(name);
    
    // 自定义名称
    model.addAttribute("username", name);

    //直接填写要跳转的jsp的名称
    return "welcome";
}

2:添加显示输出的jsp文件 welcome.jsp

${username}<br>
${string}<br>    

 3:在浏览器中访问

http://localhost:8080/welcome1.do?name=jack

 # Model中的其它方法

1:addAllAttributes(Collection<?> attributeValues);
会将传入的list中的数据对其进行命名,例如:
    List<Integer> integerList = new ArrayList<>();
    integerList.add(1);
    integerList.add(5);
    integerList.add(3);
    model.addAllAttributes(integerList);    
上面代码相当于:
    model.addAttribute("1", 1);
    model.addAttribute("5", 5);
    model.addAttribute("3", 3);
    
2:addAllAttributes(Map attributes);会将map中的key作为名字,value作为值放入到model对象中,例如:
    Map<String, Integer> integerMap = new HashMap<>();
    integerMap.put("first", 1);
    integerMap.put("second", 2);
    integerMap.put("third", 3);
    model.addAllAttributes(integerMap);
上面代码相当于:
    model.addAttribute("first", 1);
    model.addAttribute("second", 2);
    model.addAttribute("third", 3);

...

# 返回值为 void

返回值为void的应用场景:

1:通过原始的servlet来进行跳转

2:用于ajax响应

# 创建一个“通过原始的servlet来进行跳转”

1:创建一个普通的类

package com.doaoao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ReturnVoidController {

    @RequestMapping("/returnVoid.do")
    public void welcome(HttpServletRequest request, HttpServletResponse response, Student student) throws Exception {
        request.setAttribute("student", student);
        request.getRequestDispatcher("/jsp/welcome.jsp").forward(request, response);
    }
}

2:创建welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${student.name}<br>
${student.age}
</body>
</html>

3:在浏览器中访问:

http://localhost:8080/firstspringmvc_war_exploded/returnVoid.do?name=henry&age=18

 # 创建一个"用于ajax响应"

1:创建一个文件夹,用于引入 jquery文件

2:创建ajaxResponse.jsp 文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="/js/jquery-3.2.1.js"></script>
</head>
<body>
<button id="ajaxRequest">提交</button>
</body>
<script>
    $(function () {
        $("#ajaxRequest").click(function () {
            $.ajax({
                method:"post",
                url:"/ajaxResponse.do",
                data:{name:"henry",age:18},
                dataType:"json",
                success:function (result) {
                    alert(result.name + "," + result.age);
                }
            });
        });
    });

</script>
</html>

3:创建用于处理的类

package com.doaoao.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Controller
public class ReturnVoidController {


    @RequestMapping("/ajaxResponse.do")
    public void ajaxResponse(HttpServletRequest request, HttpServletResponse response,Student student) throws Exception{
        PrintWriter out = response.getWriter();
        String jsonString = JSON.toJSONString(student);
        out.write(jsonString);

    }
}

 ...

# 返回值的类型为Object

## 创建一个返回值为String的

1:在pom.xml文件中添加如下的内容,用于添加 jsckjson的jar包,在springMvc中使用 jackson来进行json数格式转换

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.4</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
  </dependency>
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.4</version>
</dependency>

2:在配置 springmvc.xml 文件中注解驱动

<mvc:annotation-driven/>

3:添加一个用于处理的类

(该需要添加一个注解,之前在Controller方法中返回字符串,springMvc会根据该字符串跳转到相应的jsp中,这里返回的字符串会添加到响应体中传递到jsop页面中,所以需要添加注解 @ResponseBody)

package com.doaoao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 方法返回Object类型
 */
@Controller
public class ReturnObjectController01 {

    @RequestMapping(value = "/returnString.do")
    @ResponseBody
    public Object returnString() throws Exception{

        return "henry";
    }
}

 4:创建一个jsp文件,用于发送请求

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Title</title>
    <script src="/js/jquery-3.3.1.js"></script>
</head>
<body>
    <button id="ajaxRequest">提交</button>
</body>
<script>
    $(function () {
       $("#ajaxRequest").click(function () {
           $.ajax({
               method:"post",
               url:"/returnString.do",
               success:function (result) {
                   alert(result);
               }
           });
       });
    });

</script>
</html>

 5:当第3步中的返回值存在中文时,会出现乱码

(需要在@RequestMapping中添加属性 produces)

@Controller
public class ReturnObjectController01 {

    @RequestMapping(value = "/returnString.do", produces = "text/html;charset=utf-8")
    @ResponseBody
    public Object returnString() throws Exception{
        return "你好世界";
    }
}

## 创建一个返回值为map的

1:创建一个类

@Controller
public class ReturnObjectController {

    @RequestMapping(value = "/returnMap.do")
    @ResponseBody
    public Object returnString() throws Exception{

        Map<String, String> testMap = new HashMap<>();
        testMap.put("hello", "你好");
        testMap.put("world", "世界");
        return testMap;
    }
}

2:jsp中添加 ajax

$(function () {
   $("#ajaxRequest").click(function () {
       $.ajax({
           method:"post",
           url:"/returnString.do",
           success:function (result) {
               alert(result.hello);
           }
       });
   });
});

 ...

本笔记参考自:小猴子老师教程 http://www.monkey1024.com