SpringMVC_Controller中方法的返回值


# 返回值的四種類型

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM