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"%>




Insert title here


	click
	hello


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




Insert title here


	click		
	hello-username
	hello-usernameA



【3】输出结果:

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

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



解释:(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 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 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
 ModelAndView addAllObjects(Map modelMap) 
          Add all attributes contained in the provided Map to the model.
 ModelAndView addObject(Object attributeValue) 
          Add an attribute to the model using parameter name generation.
 ModelAndView addObject(String attributeName, Object attributeValue) 
          Add an attribute to the model.
 void clear() 
          Clear the state of this ModelAndView object.
 Map getModel() 
          Return the model map.
protected  Map getModelInternal() 
          Return the model map.
 ModelMap getModelMap() 
          Return the underlying ModelMap instance (never null).
 View getView() 
          Return the View object, or null if we are using a view name to be resolved by the DispatcherServlet via a ViewResolver.
 String getViewName() 
          Return the view name to be resolved by the DispatcherServlet via a ViewResolver, or null if we are using a View object.
 boolean hasView() 
          Indicate whether or not this ModelAndView has a view, either as a view name or as a direct View instance.
 boolean isEmpty() 
          Return whether this ModelAndView object is empty, i.e.
 boolean isReference() 
          Return whether we use a view reference, i.e.
 void setView(View view) 
          Set a View object for this ModelAndView.
 void setViewName(String viewName) 
          Set a view name for this ModelAndView, to be resolved by the DispatcherServlet via a ViewResolver.
 String toString() 
          Return diagnostic information about this model and view.
 boolean wasCleared() 
          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, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait


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"%>




Insert title here


	click		
	hello-username
	hello-usernameA
	hello-usernameB


【3】helloB.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


	

bb

usernameB(key:usernameB) --> ${usernameB}


【4】输出结果:

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

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


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

org.springframework.ui 
Interface Model

All Known Subinterfaces:
RedirectAttributes
All Known Implementing Classes:
BindingAwareModelMap,  ExtendedModelMap,  RedirectAttributesModelMap

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

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




Insert title here


	

bb

usernameB(key:usernameB) --> ${usernameB}

无key值(key:string) --> ${string}

无key值(key:integer)  --> ${integer}

有key值(key:currentUser.userName)  --> ${currentUser.userName}

无key值(key:user.userName)  --> ${user.userName}


【4】输出结果:

SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)_第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,Mapmodel){
	  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"%>




Insert title here


	

hello springmvc!

username(key:username) --> ${username}

username(key:usernameKK) --> ${usernameKK}


【4】输出结果:

18/01/07 12:49:20 INFO controller.IndexController: hello springmvc!username:mmb
SpringMVC(5):MVC的参数传递详解与示例(简单类型数据、ModelAndView、Model 、 POJO 以及 Map)_第5张图片


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

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


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

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


你可能感兴趣的:(项目实战)