首页 > 代码库 > SpringMVC学习笔记三:Controller的返回值

SpringMVC学习笔记三:Controller的返回值

springMVC的返回值有ModelAndView,String,void,Object类型

项目目录树:

技术分享

该项目是在前面项目的基础上修改的,这里的pom.xml文件需要加入使用到的包,应为@ResponseBody需要使用的包

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.7.3</version>
    </dependency>
        
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.7.3</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.7.3</version>
    </dependency>

 

 ReturnValueController.java控制器

package com.orange.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

@Controller
@RequestMapping(value="/returnValue")
public class ReturnValueController {

    @RequestMapping("/returnModelAndView")  //返回ModelAndView
    public ModelAndView doModelAndView(String name, String password, ModelAndView mav){
        mav.addObject("name", name);
        mav.addObject("password", password);
        mav.setViewName("/showReturn.jsp");
        return mav;
        
    }
    
    @RequestMapping("/returnString") //返回String类型, 可以通过HttpServletRequest 来传递参数
    public String doString(String sname, String spassword, HttpServletRequest request){
        request.setAttribute("sname", sname);
        request.setAttribute("spassword", spassword);
        return "/showReturn.jsp";
        
    }
    
    @RequestMapping("/returnVoid") //无返回值,通过ServletAPI完成参数传递和跳转
    public void doVoid(String vname, String vpassword, HttpServletRequest request, HttpServletResponse response) throws Exception{
        request.setAttribute("vname", vname);
        request.setAttribute("vpassword", vpassword);
        request.getRequestDispatcher("/showReturn.jsp").forward(request, response);
    }
    
    @RequestMapping("/returnObjectValue") //返回Object对象需要开启消息转换器HttpMessageConverter,<mvc:annotation-driven/>
    @ResponseBody
    public Object doObjectValue(){
        return 12.34;
        
    }
    
    @RequestMapping("/returnObjectString") //返回String
    @ResponseBody
    public Object doObjectString(){
        return "Hello SpringMVC";
        
    }
    
    @RequestMapping("/returnObjectList") //返回List
    @ResponseBody
    public Object doObjectList(){
        List<String> list = new ArrayList<String>();
        list.add("String1");
        list.add("String2");
        list.add("String3");
        return list;
        
    }
    
    @RequestMapping("/returnObjectMap") //返回Map
    @ResponseBody
    public Object doObjectMap(){
        Map<String, String> map = new HashMap<String, String>();
        map.put("mk1", "kv1");
        map.put("mk2", "kv2");
        map.put("mk3", "kv3");
        return map;
        
    }
    
}

spring-mvc.xml需要添加驱动器注解

<?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:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
    <!-- 开启驱动器注解 -->
    <mvc:annotation-driven />
    
    <!-- 静态资源设置,因为需要加入js/jquery-1.7.1.js静态资源 -->
    <mvc:resources location="/js/" mapping="/js/**"/>
    
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.orange.controller" />    
    
</beans>

测试页面returnValue.jsp,用来调取Controller的配置

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>    
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<base href="<%=basePath %>">
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $(function(){
        //获取value值得ajax
        $("#value").on("click", function(){
            alert("123");
         $.ajax({
                type: "get",
                url: "returnValue/returnObjectValue",
                success: function(data){
                    alert("data: " + data);
                }
            });
        });
        //获取String值得ajax
        $("#string").on("click", function(){
            alert("123");
         $.ajax({
                type: "get",
                url: "returnValue/returnObjectString",
                success: function(data){
                    alert("data: " + data);
                }
            });
        });
        //获取List值得ajax
        $("#list").on("click", function(){
            alert("123");
         $.ajax({
                type: "get",
                url: "returnValue/returnObjectList",
                success: function(data){
                    for(var i=0; i<data.length; i++)
                    alert("data: " + data[i]);
                }
            });
        });
        //获取Map值得ajax
        $("#map").on("click", function(){
            alert("123");
         $.ajax({
                type: "get",
                url: "returnValue/returnObjectMap",
                success: function(data){
                    for(var key in data){
                        alert("key: " + key + " value: " + data[key]);
                    }
                }
            });
        });
    });
    
    
</script>
<title>ReturnValue</title>
</head>
<body>

返回ModelAndView
<form action="returnValue/returnModelAndView">
    name: <input type="text" name="name"><br/>
    password:<input type="text" name="name"><br/>
    <input type="submit" value="submit">
</form>
<hr>
返回String类型
<form action="returnValue/returnString">
    name: <input type="text" name="sname"><br/>
    password:<input type="text" name="spassword"><br/>
    <input type="submit" value="submit">
</form>
<hr>
无返回值
<form action="returnValue/returnVoid">
    name: <input type="text" name="vname"><br/>
    password:<input type="text" name="vname"><br/>
    <input type="submit" value="submit">
</form>
<hr>
返回Object对象,类型为数值型
<input id="value" type="button" value="AjaxgetValue">
<hr>
返回Object对象,类型为String
<input id="string" type="button" value="AjaxgetString">
<hr>
返回Object对象,类型为List
<input id="list" type="button" value="AjaxgetList">
<hr>
返回Object对象,类型为Map
<input id="map" type="button" value="AjaxgetMap">



</body>
</html>

跳转后的页面showReturn.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>    
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<base href="<%=basePath %>">
<title>ShowReturn</title>
</head>
<body>
返回ModelAndView
<div>
    <h3><c:out value="${name }" /></h3>
    <h3><c:out value="${password }" /></h3>
</div>
<hr>
返回String类型
<div>
    <h3><c:out value="${sname }" /></h3>
    <h3><c:out value="${spassword }" /></h3>
</div>
<hr>
无返回值
<div>
    <h3><c:out value="${vname }" /></h3>
    <h3><c:out value="${vpassword }" /></h3>
</div>
</body>
</html>

测试结果

技术分享

技术分享

 

SpringMVC学习笔记三:Controller的返回值