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

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="a/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";
    }
}  	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="a/hello?username=mmb">hello-username</a>
	<a href="a/hello?usernameA=mmb">hello-usernameA</a>
</body>
</html>

 

 

 

 

 

【3】输出结果:

 

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

 

 

 

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

 

 

org.springframework.web.servlet 
Class ModelAndView

java.lang.Object
  
正在上传…
取消
org.springframework.web.servlet.ModelAndView

public class ModelAndView

extends Object

Constructor Summary
ModelAndView() 
          Default constructor for bean-style usage: populating bean properties instead of passing in constructor arguments.
ModelAndView(String viewName) 
          Convenient constructor when there is no model data to expose.
ModelAndView(String viewName, Map<String,?> model) 
          Creates new ModelAndView given a view name and a model.
ModelAndView(String viewName, String modelName, Object modelObject) 
          Convenient constructor to take a single model object.
ModelAndView(View view) 
          Convenient constructor when there is no model data to expose.
ModelAndView(View view, Map<String,?> model) 
          Creates new ModelAndView given a View object and a model.
ModelAndView(View view, String modelName, Object modelObject) 
          Convenient constructor to take a single model object.

 

Method Summary
 ModelAndViewaddAllObjects(Map<String,?> modelMap) 
          Add all attributes contained in the provided Map to the model.
 ModelAndViewaddObject(Object attributeValue) 
          Add an attribute to the model using parameter name generation.
 ModelAndViewaddObject(String attributeName, Object attributeValue) 
          Add an attribute to the model.
 voidclear() 
          Clear the state of this ModelAndView object.
 Map<String,Object>getModel() 
          Return the model map.
protected  Map<String,Object>getModelInternal() 
          Return the model map.
 ModelMapgetModelMap() 
          Return the underlying ModelMap instance (never null).
 ViewgetView() 
          Return the View object, or null if we are using a view name to be resolved by the DispatcherServlet via a ViewResolver.
 StringgetViewName() 
          Return the view name to be resolved by the DispatcherServlet via a ViewResolver, or null if we are using a View object.
 booleanhasView() 
          Indicate whether or not this ModelAndView has a view, either as a view name or as a direct View instance.
 booleanisEmpty() 
          Return whether this ModelAndView object is empty, i.e.
 booleanisReference() 
          Return whether we use a view reference, i.e.
 voidsetView(View view) 
          Set a View object for this ModelAndView.
 voidsetViewName(String viewName) 
          Set a view name for this ModelAndView, to be resolved by the DispatcherServlet via a ViewResolver.
 StringtoString() 
          Return diagnostic information about this model and view.
 booleanwasCleared() 
          Return whether this ModelAndView object is empty as a result of a call to clear() i.e.

 

Methods inherited from class java.lang.Object
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

 

 

 

 

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="a/hello?username=mmb">hello-username</a>
	<a href="a/hello?usernameA=mmb">hello-usernameA</a>
	<a href="a/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


 

 

 

 

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

 

org.springframework.ui 
Interface Model

All Known Subinterfaces:

RedirectAttributes

All Known Implementing Classes:

BindingAwareModelMapExtendedModelMapRedirectAttributesModelMap


public interface Model
Method Summary
 ModeladdAllAttributes(Collection<?> attributeValues) 
          Copy all attributes in the supplied Collection into this Map, using attribute name generation for each element.
 ModeladdAllAttributes(Map<String,?> attributes) 
          Copy all attributes in the supplied Map into this Map.
 ModeladdAttribute(Object attributeValue) 
          Add the supplied attribute to this Map using a generated name.
 ModeladdAttribute(String attributeName, Object attributeValue) 
          Add the supplied attribute under the supplied name.
 Map<String,Object>asMap() 
          Return the current set of model attributes as a Map.
 booleancontainsAttribute(String attributeName) 
          Does this model contain an attribute of the given name?
 ModelmergeAttributes(Map<String,?> 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

 

 

 

 

 

解释:(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:

 

 	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>	<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】输出结果:


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

 

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

 

 

 

 

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

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

 

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

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

 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值