`
bartholomew4
  • 浏览: 11269 次
社区版块
存档分类
最新评论

spring mvc中的控制器返回方式集合

阅读更多

第一次自己写文章,参考了很多前人的作品,整理并加入了一些自己的见解,写的不好请多谅解

对于springMVC处理方法支持支持一系列的返回方式(可能有更多目前仅了解到这些):

1.ModelAndView

2.Model

3.ModelMap

4.Map

5.View

6.String

7.ResponseEntity

 -----------------------------------------------------------------------------------------------------------

一.ModelAndView

 

@RequestMapping("/test")
public ModelAndView list(@ModelAttribute("id") String id,HttpServletRequest request) {
             ModelAndView mv = new ModelAndView();
           //ModelAndView mv = new ModelAndView("test");
             mv.addObject("name", "test");
             mv.setViewName("test");//如用上面注释的可去掉这句
             return mv;
}

 ModelAndView构造函数可以指定返回页面的名称,也可以通过setViewName方法来设置所需要跳转的页面,并且返回的是一个包含模型和视图的ModelAndView对象;

 

 

二.Model

Model是一个接口,并不能直接返回,作用是作为一个模型对象包含了封装好的Model和modelMap,以及java.util.Map,当没有视图返回的时候视图名称将由requestToViewNameTranslator决定;

本人水平有限,可能描述的不够到位,附上spring里这个类的源码

 

/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.ui;

import java.util.Collection;
import java.util.Map;

/**
 * Java-5-specific interface that defines a holder for model attributes.
 * Primarily designed for adding attributes to the model.
 * Allows for accessing the overall model as a {@code java.util.Map}.
 *
 * @author Juergen Hoeller
 * @since 2.5.1
 */
public interface Model {

	/**
	 * Add the supplied attribute under the supplied name.
	 * @param attributeName the name of the model attribute (never {@code null})
	 * @param attributeValue the model attribute value (can be {@code null})
	 */
	Model addAttribute(String attributeName, Object attributeValue);

	/**
	 * Add the supplied attribute to this {@code Map} using a
	 * {@link org.springframework.core.Conventions#getVariableName generated name}.
	 * <p><emphasis>Note: Empty {@link java.util.Collection Collections} are not added to
	 * the model when using this method because we cannot correctly determine
	 * the true convention name. View code should check for {@code null} rather
	 * than for empty collections as is already done by JSTL tags.</emphasis>
	 * @param attributeValue the model attribute value (never {@code null})
	 */
	Model addAttribute(Object attributeValue);

	/**
	 * Copy all attributes in the supplied {@code Collection} into this
	 * {@code Map}, using attribute name generation for each element.
	 * @see #addAttribute(Object)
	 */
	Model addAllAttributes(Collection<?> attributeValues);

	/**
	 * Copy all attributes in the supplied {@code Map} into this {@code Map}.
	 * @see #addAttribute(String, Object)
	 */
	Model addAllAttributes(Map<String, ?> attributes);

	/**
	 * Copy all attributes in the supplied {@code Map} into this {@code Map},
	 * with existing objects of the same name taking precedence (i.e. not getting
	 * replaced).
	 */
	Model mergeAttributes(Map<String, ?> attributes);

	/**
	 * Does this model contain an attribute of the given name?
	 * @param attributeName the name of the model attribute (never {@code null})
	 * @return whether this model contains a corresponding attribute
	 */
	boolean containsAttribute(String attributeName);

	/**
	 * Return the current set of model attributes as a Map.
	 */
	Map<String, Object> asMap();

}

 

 

 三.ModelMap

在spring mvc中可以通过ModelMap对象传递模型参数到视图进行处理。在Controller方法中声明一个ModelMap参数,spring会创建一个ModelMap对象,并传入方法,方法处理完成后自动传递到视图进行处理。

ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。

 

@RequestMapping("/test")
	public String testmethod(String someparam,ModelMap model)
	{
	      model.addAttribute("test","test");
		// 返回跳转地址
	      return "path:handleok";
	}

 PS:建议使用ModelAndView

 

四.Map

这个个人感觉没什么可以介绍的,直接上代码

 

@RequestMapping(value = "/test")
	public Map<String, String> index() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("test", "test");
		// map.put相当于request.setAttribute方法
		return map;

	}

 

 

五.View

View同Model一样也是一个接口,了解不多,上源码,欢迎补充

 

/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet;

import java.util.Map;

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

import org.springframework.http.MediaType;

/**
 * MVC View for a web interaction. Implementations are responsible for rendering
 * content, and exposing the model. A single view exposes multiple model attributes.
 *
 * <p>This class and the MVC approach associated with it is discussed in Chapter 12 of
 * <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0764543857/">Expert One-On-One J2EE Design and Development</a>
 * by Rod Johnson (Wrox, 2002).
 *
 * <p>View implementations may differ widely. An obvious implementation would be
 * JSP-based. Other implementations might be XSLT-based, or use an HTML generation library.
 * This interface is designed to avoid restricting the range of possible implementations.
 *
 * <p>Views should be beans. They are likely to be instantiated as beans by a ViewResolver.
 * As this interface is stateless, view implementations should be thread-safe.
 *
 * @author Rod Johnson
 * @author Arjen Poutsma
 * @see org.springframework.web.servlet.view.AbstractView
 * @see org.springframework.web.servlet.view.InternalResourceView
 */
public interface View {

	/**
	 * Name of the {@link HttpServletRequest} attribute that contains the response status code.
	 * <p>Note: This attribute is not required to be supported by all View implementations.
	 */
	String RESPONSE_STATUS_ATTRIBUTE = View.class.getName() + ".responseStatus";

	/**
	 * Name of the {@link HttpServletRequest} attribute that contains a Map with path variables.
	 * The map consists of String-based URI template variable names as keys and their corresponding
	 * Object-based values -- extracted from segments of the URL and type converted.
	 *
	 * <p>Note: This attribute is not required to be supported by all View implementations.
	 */
	String PATH_VARIABLES = View.class.getName() + ".pathVariables";

	/**
	 * The {@link MediaType} selected during content negotiation, which may be
	 * more specific than the one the View is configured with. For example:
	 * "application/vnd.example-v1+xml" vs "application/*+xml".
	 */
	String SELECTED_CONTENT_TYPE = View.class.getName() + ".selectedContentType";

	/**
	 * Return the content type of the view, if predetermined.
	 * <p>Can be used to check the content type upfront,
	 * before the actual rendering process.
	 * @return the content type String (optionally including a character set),
	 * or {@code null} if not predetermined.
	 */
	String getContentType();

	/**
	 * Render the view given the specified model.
	 * <p>The first step will be preparing the request: In the JSP case,
	 * this would mean setting model objects as request attributes.
	 * The second step will be the actual rendering of the view,
	 * for example including the JSP via a RequestDispatcher.
	 * @param model Map with name Strings as keys and corresponding model
	 * objects as values (Map can also be {@code null} in case of empty model)
	 * @param request current HTTP request
	 * @param response HTTP response we are building
	 * @throws Exception if rendering failed
	 */
	void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception;

}

 

六.String

有2种返回方式:

String 指定返回的视图页面名称,结合设置的返回地址路径加上页面名称后缀即可访问到。

 

@RequestMapping("/test") 
	public String welcomeHandler() { 
	  return "index"; 
	}

 简单粗暴,对应的逻辑视图名为“index”,URL= prefix前缀+视图名称 +suffix后缀。

第2种返回字符串

 

@RequestMapping(value = "/test")
	@ResponseBody
	public String lista(HttpServletRequest request) {
		return "test";
	}

 

七.ResponseEntity

ResponseEntity作用比较强大,可以返回文件,字符串等

字符串的demo:

 

@RequestMapping(value = "/test", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8;")
	public ResponseEntity<String> test(HttpServletResponse response) {
		return new ResponseEntity<String>("这是测试", HttpStatus.OK);
	}

 文件的demo:

@RequestMapping("download")
	public ResponseEntity<byte[]> download(String filepath) throws IOException {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", "filename.suffix");
		File file = new File(filepath);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
				headers, HttpStatus.CREATED);
	}

 PS:使用ResponseEntity需要正确配置AnnotationMethodHandlerAdapter,messageConverters中的list是有顺序的,这点很重要!

 

分享到:
评论

相关推荐

    Spring+Spring mvc+Hibernate+Bootstrap、企业级员工信息管理系统

    Spring mvc 返回数据格式采用统一的对象(JSONReturn)进行封装 09. 通过自定义处理器 ExceptionIntercept 实现 Spring mvc的全局异常捕获 10. 系统中包含了企业中采用的开发工具类的集合 11. AbstractDao 父类...

    支持Spring Data开发的工具集合(95分以上课程大作业).zip

    它采用MVC(Model-View-Controller,模型-视图-控制器)的架构模式,将应用程序分为模型层、视图层和控制器层,提供了处理请求、渲染视图和管理流程的功能。 3. MyBatis框架:MyBatis是一个持久层框架,用于与数据库...

    Spring-Reference_zh_CN(Spring中文参考手册)

    标准MVC控制器代码 14.5.1.3. 把模型数据转化为XML 14.5.1.4. 定义视图属性 14.5.1.5. 文档转换 14.5.2. 小结 14.6. 文档视图(PDF/Excel) 14.6.1. 简介 14.6.2. 配置和安装 14.6.2.1. 文档视图定义 14.6.2.2. ...

    Spring面试题含答案.pdf

    1. 什么是 spring? 2. 使用 Spring 框架的好处是什么? 3. Spring 由哪些模块组成? 4. 核心容器(应用上下文) 模块 ...67. 什么是 Spring MVC 框架的控制器? 68. @Controller 注解 69. @RequestMapping 注解

    图书管理系统( Spring+Spring MVC+JdbcTemplate).zip

    计算机硬件系统: 计算机硬件系统是构成计算机物理实体的所有部件的集合,包括核心组件以及外设。其主要组成部分包括: 中央处理单元 (CPU):作为计算机的大脑,负责执行指令、进行逻辑运算和数据处理。 内存:...

    Spring攻略(第二版 中文高清版).part1

    13.3 Spring MVC控制器的单元测试 518 13.3.1 问题 518 13.3.2 解决方案 518 13.3.3 工作原理 518 13.4 管理集成测试中的应用上下文 520 13.4.1 问题 520 13.4.2 解决方案 520 13.4.3 工作原理 521 ...

    Spring-WebMvc-IntelliJ:SpringMvc1工作区

    Spring Web MVC 编程时必须使用的类的集合称为类库或库。 Spring是Java服务器编程所需的非常大的类库。 大型库通常被称为框架库。 因此,它通常被称为Spring Framework。 Spring框架库的组件之一是Spring Web ...

    Spring攻略(第二版 中文高清版).part2

    13.3 Spring MVC控制器的单元测试 518 13.3.1 问题 518 13.3.2 解决方案 518 13.3.3 工作原理 518 13.4 管理集成测试中的应用上下文 520 13.4.1 问题 520 13.4.2 解决方案 520 13.4.3 工作原理 521 ...

    springmybatis

    查询出列表,也就是返回list, 在我们这个例子中也就是 List&lt;User&gt; , 这种方式返回数据,需要在User.xml 里面配置返回的类型 resultMap, 注意不是 resultType, 而这个resultMap 所对应的应该是我们自己配置的 ...

    Spring in Action(第二版 中文高清版).part2

    B.2 单元测试Spring MVC控制器 B.2.1 模拟对象 B.2.2 断言ModelAndView的内容 B.3 使用Spring进行综合测试 B.3.1 测试装配后的对象 B.3.2 综合测试事务处理对象 B.3.3 测试数据库 B.3.4 使用Gienah Testing在...

    Spring in Action(第二版 中文高清版).part1

    B.2 单元测试Spring MVC控制器 B.2.1 模拟对象 B.2.2 断言ModelAndView的内容 B.3 使用Spring进行综合测试 B.3.1 测试装配后的对象 B.3.2 综合测试事务处理对象 B.3.3 测试数据库 B.3.4 使用Gienah Testing在...

    Spring.3.x企业应用开发实战(完整版).part2

    15.6.2 编写控制器和文件上传表单页面 15.7 杂项 15.7.1 静态资源处理 15.7.2 装配拦截器 15.7.3 异常处理 15.8 小结 第5篇 测试及实战 第16章 实战型单元测试 16.1 单元测试概述 16.1.1 为什么需要单元测试 16.1.2...

    Spring3.x企业应用开发实战(完整版) part1

    15.6.2 编写控制器和文件上传表单页面 15.7 杂项 15.7.1 静态资源处理 15.7.2 装配拦截器 15.7.3 异常处理 15.8 小结 第5篇 测试及实战 第16章 实战型单元测试 16.1 单元测试概述 16.1.1 为什么需要单元测试 16.1.2...

    Spring面试题

    基于Struts开发的应用由3类组件构成:控制器组件、模型组件、视图组件 8. Struts的validate框架是如何验证的? 在struts配置文件中配置具体的错误提示,再在FormBean中的validate()方法具体调用。 9. 说下Struts...

    spring3.1中文参考文档

    2.4 新的模块组织方式和系统构建方式............................................................................................... 23 2.5 新特性概述 .......................................................

    java8看不到源码-Spring-boot-mybatis:使用Springboot、SpringMVC和Mybatis实现ORM和持久化M

    MVC(模型、视图、控制器)设计模式开发 Web 应用程序。 为了熟悉 Spring MVC 应用程序,以下 Spring 注释很有用。 @Controller - 该注解定义了 Web 应用程序的控制器,模型将与数据库和视图进行通信,以通过 JSP 或...

    Spring 3 Reference中文

    4.6.1.6 在非Web 应用中,优雅地关闭Spring IoC 容器 74 4.6.2 ApplicationContextAware 和BeanNameAware . 75 4.6.3 其它Aware 接口 75 4.7 Bean 定义的继承. 77 4.8 容器扩展点. 78 4.8.1...

    Milkomeda:Spring扩展了从商务经验中构建的组件,使开发人员能够尽快使用Spring Boot进行开发。(基于Spring生态打造的各种来自业务上的快速开发模块集合。)

    Milkomeda 该项目名称的灵感来自银河系,仙女座将在未来合并,就像春天的... Comet:用于统一请求方面记录(包括控制器层和服务层( 1.12.0+ ))。 0.2.0+ 取决于:Spring MVC Struts:用于if / else业务块拆分。

    基于java web技术实现学生成绩管理系统附项目源码+数据库文件+文档说明

    例如,Spring MVC框架可以帮助开发人员构建Web应用程序的控制器、视图和模型,简化了Web应用程序的开发过程。 2. 提高可维护性:Spring框架的设计思想是基于面向对象的编程,它鼓励开发人员编写松耦合的代码,提高...

Global site tag (gtag.js) - Google Analytics