SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)

Easter79
• 阅读 736

2018/1/7

SpringMVC是一个以模型数据为核心的开源框架,将前后端松耦合的管理,最重要的就是数据的传递。

下面给大家介绍的是把参数值传递,包括使用简单类型数据、ModelAndView、Model 、POJO 以及 Map。

一、(View to Conotroller) URL传值--@RequestMapping

【1】修改IndexController.java:

package com.smbms.controller;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller 
@RequestMapping("/a")
public class IndexController {
    private Logger log = Logger.getLogger(IndexController.class.getName());

    @RequestMapping(value="/hello",method=RequestMethod.POST,params="username")
    public String hello(@RequestParam String username){
        log.info("welcome username1 ,"+username);
        return "hello";
    }
    
}

【2】在index.html 修改:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <a href="http://www.baidu.com">click</a>
    <a href="https://my.oschina.net//u/4689327/blog/4663859/hello?username=mmb">hello</a>
</body>
</html>

解释:(1)@RequestMapping 负责将不同的请求映射到对应的控制器方法上;

(2)@RequestMapping 的请求信息必须保持全局唯一,处理修饰方法,也可以修饰类;

(3)@RequestMapping 除了URL 映射请求,还可以使用请求参数、请求方法来映射请求,多条件可以让请求更加精确,匹配顺序为:首先value,然后method,最后参数;

输出结果:

18/01/07 11:08:17 INFO controller.IndexController: welcome username ,mmb

二、(View to Conotroller) URL传值--@RequestParam

【1】修改IndexController.java:

package com.smbms.controller;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller 
@RequestMapping("/a")
public class IndexController {
    private Logger log = Logger.getLogger(IndexController.class.getName());
    
   //@RequestParam
    @RequestMapping(value="/hello")
    public String hello2(@RequestParam(value="username" ,required=false) String username){
     log.info("welcome username2 ,"+username);
     return "hello";
    }
}

【2】输出结果:

18/01/07 11:12:46 INFO controller.IndexController: welcome username2 ,mmb

解释:(1)@RequestParam 注解指定对应的请求参数。@RequestParam 有以三个参数:value(参数名)、required(参数是否必须)、defaultValue(不推荐);

三、(Conotroller to View )

对于mvc,模型数据最重要,Controller产生了Model,View最终也是为了渲染模型数据并进行输出:

1、ModelAndView

既包含视图信息,也包含模型数据。IndexController.java 做修改,将前端URL传参,在控制台输出参数值,并在视图层输出username;

【1】IndexController.java:

package com.smbms.controller;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller 
@RequestMapping("/a")
public class IndexController {
    private Logger log = Logger.getLogger(IndexController.class.getName());
      
    //ModelAndView
    @RequestMapping(value="/hello")
    public ModelAndView hello3(@RequestParam(value="username3" ,required=true) String username3){
        log.info("welcome username3 ,"+username3);
        ModelAndView mView = new ModelAndView();
        mView.addObject("username",username3);
        mView.setViewName("hello");
        return mView;
    }
}

【2】在index.html 修改:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <a href="http://www.baidu.com">click</a>        
    <a href="https://my.oschina.net//u/4689327/blog/4663859/hello?username=mmb">hello-username</a>
    <a href="https://my.oschina.net//u/4689327/blog/4663859/hello?usernameA=mmb">hello-usernameA</a>
</body>
</html>

【3】输出结果:

18/01/07 11:29:24 INFO controller.IndexController: welcome usernameA ,mmb

SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)

解释:(1)ModelAndView 对象介绍(官方文档):

org.springframework.web.servlet 
Class ModelAndView


java.lang.Object
  org.springframework.web.servlet.ModelAndView

public class ModelAndView
   
    extends 
    Object

Constructor Summary

**[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#ModelAndView%28%29)**() 
          Default constructor for bean-style usage: populating bean properties instead of passing in constructor arguments.

**[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#ModelAndView%28java.lang.String%29)**([String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) viewName) 
          Convenient constructor when there is no model data to expose.

**[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#ModelAndView%28java.lang.String,%20java.util.Map%29)**([String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) viewName, [Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),?> model) 
          Creates new ModelAndView given a view name and a model.

**[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#ModelAndView%28java.lang.String,%20java.lang.String,%20java.lang.Object%29)**([String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) viewName, [String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) modelName, [Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue) modelObject) 
          Convenient constructor to take a single model object.

**[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#ModelAndView%28org.springframework.web.servlet.View%29)**([View](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/View.html) view) 
          Convenient constructor when there is no model data to expose.

**[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#ModelAndView%28org.springframework.web.servlet.View,%20java.util.Map%29)**([View](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/View.html) view, [Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),?> model) 
          Creates new ModelAndView given a View object and a model.

**[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#ModelAndView%28org.springframework.web.servlet.View,%20java.lang.String,%20java.lang.Object%29)**([View](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/View.html) view, [String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) modelName, [Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue) modelObject) 
          Convenient constructor to take a single model object.

Method Summary

[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html)

**[addAllObjects](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#addAllObjects%28java.util.Map%29)**([Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),?> modelMap) 
          Add all attributes contained in the provided Map to the model.

[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html)

**[addObject](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#addObject%28java.lang.Object%29)**([Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue) attributeValue) 
          Add an attribute to the model using parameter name generation.

[ModelAndView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html)

**[addObject](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#addObject%28java.lang.String,%20java.lang.Object%29)**([String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) attributeName, [Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue) attributeValue) 
          Add an attribute to the model.

void

**[clear](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#clear%28%29)**() 
          Clear the state of this ModelAndView object.

[Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),[Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue)>

**[getModel](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#getModel%28%29)**() 
          Return the model map.

protected  [Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),[Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue)>

**[getModelInternal](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#getModelInternal%28%29)**() 
          Return the model map.

[ModelMap](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/ModelMap.html)

**[getModelMap](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#getModelMap%28%29)**() 
          Return the underlying ModelMap instance (never null).

[View](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/View.html)

**[getView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#getView%28%29)**() 
          Return the View object, or null if we are using a view name to be resolved by the DispatcherServlet via a ViewResolver.

[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue)

**[getViewName](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#getViewName%28%29)**() 
          Return the view name to be resolved by the DispatcherServlet via a ViewResolver, or null if we are using a View object.

boolean

**[hasView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#hasView%28%29)**() 
          Indicate whether or not this ModelAndView has a view, either as a view name or as a direct View instance.

boolean

**[isEmpty](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#isEmpty%28%29)**() 
          Return whether this ModelAndView object is empty, i.e.

boolean

**[isReference](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#isReference%28%29)**() 
          Return whether we use a view reference, i.e.

void

**[setView](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#setView%28org.springframework.web.servlet.View%29)**([View](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/View.html) view) 
          Set a View object for this ModelAndView.

void

**[setViewName](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#setViewName%28java.lang.String%29)**([String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) viewName) 
          Set a view name for this ModelAndView, to be resolved by the DispatcherServlet via a ViewResolver.

[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue)

**[toString](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#toString%28%29)**() 
          Return diagnostic information about this model and view.

boolean

**[wasCleared](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/web/servlet/ModelAndView.html#wasCleared%28%29)**() 
          Return whether this ModelAndView object is empty as a result of a call to clear() i.e.

Methods inherited from class java.lang.Object

[clone](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23clone%2528%2529), [equals](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23equals%2528java.lang.Object%2529), [finalize](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23finalize%2528%2529), [getClass](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23getClass%2528%2529), [hashCode](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23hashCode%2528%2529), [notify](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23notify%2528%2529), [notifyAll](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23notifyAll%2528%2529), [wait](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23wait%2528%2529), [wait](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23wait%2528long%2529), [wait](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue%23wait%2528long%2C%2520int%2529)

2、Model 对象模型的使用

还可以使用Model对象完成模型数据的传递。
【1】修改IndexController.java:

package com.smbms.controller;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller 
@RequestMapping("/a")
public class IndexController {
    private Logger log = Logger.getLogger(IndexController.class.getName());
    
    //Model 
  @RequestMapping(value="/helloB")
  public String hello4(String usernameB ,Model model){
      log.info("welcome usernameB ,"+usernameB);
      model.addAttribute("usernameB",usernameB);
      return "helloB";
  }
}

【2】在index.jsp 修改:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <a href="http://www.baidu.com">click</a>        
    <a href="https://my.oschina.net//u/4689327/blog/4663859/hello?username=mmb">hello-username</a>
    <a href="https://my.oschina.net//u/4689327/blog/4663859/hello?usernameA=mmb">hello-usernameA</a>
    <a href="https://my.oschina.net//u/4689327/blog/4663859/hello?usernameB=mmb">hello-usernameB</a>
</body>
</html>

【3】helloB.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>bb</h1>
    <!-- ${usernameB}才是取值 -->
    <h1>usernameB(key:usernameB) --> ${usernameB}</h1>
</body>
</html>

【4】输出结果:

18/01/07 11:52:33 INFO controller.IndexController: welcome usernameB ,mmb

SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)

解释:(1)Model对象介绍(官方文档):

org.springframework.ui 
Interface Model


All Known Subinterfaces:

RedirectAttributes

All Known Implementing Classes:

BindingAwareModelMapExtendedModelMapRedirectAttributesModelMap


public interface Model

Method Summary

[Model](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html)

**[addAllAttributes](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html#addAllAttributes%28java.util.Collection%29)**([Collection](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FCollection.html%3Fis-external%3Dtrue)<?> attributeValues) 
          Copy all attributes in the supplied Collection into this Map, using attribute name generation for each element.

[Model](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html)

**[addAllAttributes](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html#addAllAttributes%28java.util.Map%29)**([Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),?> attributes) 
          Copy all attributes in the supplied Map into this Map.

[Model](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html)

**[addAttribute](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html#addAttribute%28java.lang.Object%29)**([Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue) attributeValue) 
          Add the supplied attribute to this Map using a generated name.

[Model](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html)

**[addAttribute](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html#addAttribute%28java.lang.String,%20java.lang.Object%29)**([String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) attributeName, [Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue) attributeValue) 
          Add the supplied attribute under the supplied name.

[Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),[Object](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FObject.html%3Fis-external%3Dtrue)>

**[asMap](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html#asMap%28%29)**() 
          Return the current set of model attributes as a Map.

boolean

**[containsAttribute](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html#containsAttribute%28java.lang.String%29)**([String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue) attributeName) 
          Does this model contain an attribute of the given name?

[Model](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html)

**[mergeAttributes](http://tool.oschina.net/uploads/apidocs/Spring-3.1.1/org/springframework/ui/Model.html#mergeAttributes%28java.util.Map%29)**([Map](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Futil%2FMap.html%3Fis-external%3Dtrue)<[String](https://www.oschina.net/action/GoToLink?url=http%3A%2F%2Fdownload.oracle.com%2Fjavase%2F6%2Fdocs%2Fapi%2Fjava%2Flang%2FString.html%3Fis-external%3Dtrue),?> attributes) 
          Copy all attributes in the supplied Map into this Map, with existing objects of the same name taking precedence (i.e.

(2)其实springmvc 在调用方法前,就会创建一个隐含的模型对象(隐含模型)Model,作为数据的存储容器。那么,若处理方法的入参为Model模型,springmvc就会将隐含模型的引用传递给这些入参;简单说,开发者可以通过一个Model类型的入参对象,访问到模型的所有数据,当然也可以添加新的属性数据!

【4】添加无key值的属性,修改IndexController.java::

package com.smbms.controller;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller 
@RequestMapping("/a")
public class IndexController {
    private Logger log = Logger.getLogger(IndexController.class.getName());
      
    //Model 
  @RequestMapping(value="/hello")
  public String hello4(String usernameB ,Model model){
    Integer value = 110; 
      log.info("welcome usernameB ,"+usernameB);
      model.addAttribute("usernameB",usernameB);
      model.addAttribute(usernameB);
      model.addAttribute(value);
      return "helloB";
  }
}

输出结果:

18/01/07 12:07:39 INFO controller.IndexController: welcome usernameB ,mmb是否包含string :true是否包含integer:true

SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)

解释:(3)Model对象使用无参属性是,参数的类型名称会成为其默认的key!!大家可以自主探究:对于使用多个相同类型的无key参数,调用会出错吗?参数的key区分大小写吗?(答案:区分大小写!多个参数时,若是没有通过变量赋值,是取不出来的!)

3、POJO 对象模型的使用

【0】在工程新建一个包,新建一个JavaBean,这里举例User.java:

package com.smbms.entities;

import java.util.Date;
import java.util.List;

public class User {
    private Integer id;
    private String userCode;
    private String userName;
    private String userPassword;
    private Integer gender;
    private Date birthday;
    private String phone;
    private String address ;
    private Integer userRole;
    private Integer createdBy;
    private Date creationDate;
    private Integer modifyBy;
    private Date modifyDate;
    private String userRoleName;
        
        public String getUserRoleName() {
        return userRoleName;
    }
    public void setUserRoleName(String userRoleName) {
        this.userRoleName = userRoleName;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserCode() {
        return userCode;
    }
    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPassword() {
        return userPassword;
    }
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
    public Integer getGender() {
        return gender;
    }
    public void setGender(Integer gender) {
        this.gender = gender;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getUserRole() {
        return userRole;
    }
    public void setUserRole(Integer userRole) {
        this.userRole = userRole;
    }
    public Integer getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Integer getModifyBy() {
        return modifyBy;
    }
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public User(Integer id, String userCode, String userName, String userPassword, Integer gender, Date birthday,
            String phone, String address, Integer userRole, Integer createdBy, Date creationDate, Integer modifyBy,
            Date modifyDate) {
        super();
        this.id = id;
        this.userCode = userCode;
        this.userName = userName;
        this.userPassword = userPassword;
        this.gender = gender;
        this.birthday = birthday;
        this.phone = phone;
        this.address = address;
        this.userRole = userRole;
        this.createdBy = createdBy;
        this.creationDate = creationDate;
        this.modifyBy = modifyBy;
        this.modifyDate = modifyDate;
    }
    public User() {
        super();
        // TODO 自动生成的构造函数存根
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", userCode=" + userCode + ", userName=" + userName + ", userPassword=" + userPassword
                + ", gender=" + gender + ", birthday=" + birthday + ", phone=" + phone + ", address=" + address
                + ", userRole=" + userRole + ", createdBy=" + createdBy + ", creationDate=" + creationDate
                + ", modifyBy=" + modifyBy + ", modifyDate=" + modifyDate + "]";
    }
    
}

【1】修改IndexController.java:

package com.smbms.controller; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.smbms.entities.User; @Controller  @RequestMapping("/a") public class IndexController {  private Logger log = Logger.getLogger(IndexController.class.getName());        //POJO+Model   @RequestMapping(value="/hello")   public String hello5(String usernameB ,Model model){    model.addAttribute("usernameB",usernameB);    model.addAttribute(usernameB);    User user = new User();    user.setUserName(usernameB);    model.addAttribute("currentUser", user);    model.addAttribute(user);    return "helloB";   } }  

【2】index.jsp 不作修改;

【3】helloB.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body>  <h1>bb</h1>  <table width="500">  <tr>  <td>  <!-- ${usernameB}才是取值 -->  <h1>usernameB(key:usernameB) --> ${usernameB}</h1>  </td>  </tr>  <tr><td>  <h1>无key值(key:string) --> ${string}</h1>   </td></tr>  <tr><td>  <h1>无key值(key:integer)  --> ${integer}</h1>  </td></tr>    <tr><td>  <h1>有key值(key:currentUser.userName)  --> ${currentUser.userName}</h1>  </td>  </tr>    <tr><td>  <h1>无key值(key:user.userName)  --> ${user.userName}</h1>  </td></tr>  </table>   </body> </html>

【4】输出结果:

SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)

解释:还是使用“.”进行属性值的访问。

4、Map 对象模型的使用

不难发现,其实Model也是一个Map 的数据结构,所以,我们使用Map 作为处理方法入参也是可以的。

【1】修改IndexController.java:

package com.smbms.controller;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.smbms.entities.User;

@Controller 
@RequestMapping("/a")
public class IndexController {
    private Logger log = Logger.getLogger(IndexController.class.getName());
  
  //Map
  @RequestMapping(value="/hello")
  public String index(String username,Map<String,Object>model){
      log.info("hello springmvc!username:"+username);
      model.put("usernameKK", username);
      return "helloC";
  }
}

【2】 index.jsp 不作修改;

【3】新建helloC.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <h1>hello springmvc!</h1>
    <h2>username(key:username) --> ${username}</h2>
    <h2>username(key:usernameKK) --> ${usernameKK}</h2>
</body>
</html>

【4】输出结果:

18/01/07 12:49:20 INFO controller.IndexController: hello springmvc!username:mmb

SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)

4、@ModelAttribute 对象模型的注解使用:

若希望将入参的数据对象放入数据模型,可以在相应的参数入参前使用该注解。后续做跟进。

5、@ModelAttributes 对象模型的注解使用:

此注解可以将模型的属性存入HttpSession中,以便多个请求之间共享该属性。后续做跟进。

点赞
收藏
评论区
推荐文章
Wesley13 Wesley13
3年前
java传值与引用的关系
       首先,我们必须要搞清楚的一件事是,不管java的参数类型是什么,一律传递的是参数的副本。也就是说每次传递参数的时候都会讲参数拷贝一份传递。1.基本数据类型:       对于基本的数据类型来说,java传递的是指的副本;也就是将数据拷贝一份以后传递。因此当函数返回的时候,不管在调用的函数中做了什么操作,基本数据类型的值都不会改变。
Wesley13 Wesley13
3年前
Java中只存在值传递
在Java中并不存在引用传递(即地址传递),对于变量(可以是基本数据类型,也可以是引用数据类型)而言,可以理解为就是一个地址。传递,存在着拷贝操作。举个列子:1、在方法参数上,传递的是基本数据类型。定义了一个用于交换两个整型数的方法:publicstaticvoidswap(inta,intb){in
Wesley13 Wesley13
3年前
Java对象的浅拷贝和深拷贝&&String类型的赋值
Java中的数据类型分为基本数据类型和引用数据类型。对于这两种数据类型,在进行赋值操作、方法传参或返回值时,会有值传递和引用(地址)传递的差别。浅拷贝(ShallowCopy):①对于数据类型是基本数据类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。因为是两份不同的数据,所以对其中一个对象的该成员变量值进行修改,
Easter79 Easter79
3年前
SpringMVC 方法三种类型返回值总结,你用过几种?
SpringMVC现在算是Java领域的一个基础性框架了,很多人天天用,可是对于SpringMVC方法的返回值,你又是否完全清楚呢?今天松哥就来和大家聊一聊SpringMVC中四种不同类型的返回值,看看有没有get到你的知识盲点?1\.ModelAndView以前前后端不分的情况下,ModelAn
可莉 可莉
3年前
2020,最新Model的设计
很多的app使用MVC设计模式来将“用户交互”与“数据和逻辑”分开,而model其中一个重要作用就是持久化。下文中设计的Model可能不是一个完美的,扩展性强的model范例,但在我需要重构的app中,这样的设计能够满足我的需要。关于ModelModel层包含了app的数据与逻辑,Model层中的类需要关心的是数据的表现,存储,以及操
Stella981 Stella981
3年前
2020,最新Model的设计
很多的app使用MVC设计模式来将“用户交互”与“数据和逻辑”分开,而model其中一个重要作用就是持久化。下文中设计的Model可能不是一个完美的,扩展性强的model范例,但在我需要重构的app中,这样的设计能够满足我的需要。关于ModelModel层包含了app的数据与逻辑,Model层中的类需要关心的是数据的表现,存储,以及操
Stella981 Stella981
3年前
Golang高效实践之array、slice、map实践
前言Golang的slice类型为连续同类型数据提供了一个方便并且高效的实现方式。slice的实现是基于array,slice和map一样是类似于指针语义,传递slice和map并不涉及底层数据结构的拷贝,相当于传递底层数据结构的指针。Arrays数组 数组类型的定义需要指定长度和元素的类型。例如,\4\int表示一个四个整数
Stella981 Stella981
3年前
Android 原生webview传递header前端H5如何接收
_开发背景_跟其他公司合作的一个项目,传递参数的方式为原生通过自定义header头参数,由前端来接收。_踩坑_1原生传参安卓原生传参的方式很简单,通过webview.loadUrl这个方法,如下:Map<String,StringmapnewHashMap
Stella981 Stella981
3年前
JavaScript深入之参数按值传递
定义在《JavaScript高级程序设计》第三版4.1.3,讲到传递参数:ECMAScript中所有函数的参数都是按值传递的。什么是按值传递呢?也就是说,把函数外部的值复制给函数内部的参数,就和把值从一个变量复制到另一个变量一样。按值传递举个简单的例子:varvalue1;fun
小万哥 小万哥
11个月前
灵活配置 Spring 集合:List、Set、Map、Properties 详解
使用标签的value属性配置原始数据类型和ref属性配置对象引用的方式来定义Bean配置文件。这两种情况都涉及将单一值传递给Bean。那么如果您想传递多个值,例如Java集合类型,如List、Set、Map和Properties怎么办?为了处理这种情况,S
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k