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

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 mvc框架依赖全面jar

    Spring MVC 是一个基于 Java 的轻量级Web应用框架,它为构建模型-视图-控制器(MVC)架构的应用程序提供了强大的支持。在本压缩包中包含了一系列与Spring MVC相关的jar文件,这些文件是构建和运行Spring MVC项目所...

    Spring mvc5.0.3 所有jar包

    2. **Model-View-Controller(MVC)架构**: Spring MVC遵循MVC设计模式,将应用程序逻辑分解为模型(Model)、视图(View)和控制器(Controller)三个部分。模型处理业务逻辑,控制器处理用户交互,视图负责展示...

    Spring MVC 学习笔记 九 json格式的输入和输出

    当前端向后端发送JSON数据时,Spring MVC可以自动将这些数据绑定到控制器方法的参数上。这需要我们的参数是Java Bean类型,其属性与JSON对象的键相对应。例如,如果我们有一个`User`类,Spring MVC可以通过`@...

    SSM(Spring+Spring MVC+Mybatis)jar包集合

    在SSM框架中,Spring MVC作为前端控制器,负责请求的转发和响应;Spring则作为整体的框架管理,提供依赖注入和事务控制;Mybatis作为数据访问层,处理与数据库的交互。这三个框架的集成,使得开发者可以高效地开发出...

    spring mvc3 学习资料

    - 注解式控制器是Spring 3.0引入的,用于简化Spring MVC的控制器实现。 - 本部分内容详细介绍如何使用@Controller、@RequestMapping等注解来定义控制器,处理请求映射,以及如何定义返回值等。 7. 请求映射规则...

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

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

    spring3mvc导入包

    总之,"spring3mvc导入包大全"是一个集合了构建Spring3MVC项目所需的所有核心库和其他相关依赖的资源包,对于初学者来说,这是一个非常实用的起点,可以帮助快速搭建起一个功能完备的Spring MVC开发环境。

    spring MVC数据绑定大全

    在Spring MVC中,数据绑定是一项核心功能,它允许开发者将用户输入的数据与控制器中的对象属性进行关联,简化了数据处理的复杂性。本文将详细介绍Spring MVC中的数据绑定,并提供实例帮助初学者理解。 1. **模型...

    Spring MVC开发技术文档和中文参考手册

    Spring MVC是Spring框架的一个核心模块,专为构建Web应用程序提供模型-视图-控制器(MVC)架构支持。它在Java开发中广泛使用,因为其灵活性、可扩展性和高效的性能。下面将详细介绍Spring MVC的各个方面。 一、MVC...

    Spring MVC不能直接接收list类型参数的问题

    **后台控制器代码**: ```java @RequestMapping(value = "/getEventData", method = RequestMethod.POST) public void getEventData(@RequestBody List&lt;String&gt; areaList) { // 处理 areaList 数据 } ``` 这种方法...

    Spring MVC 集合各种功能点

    它基于Spring框架,提供了模型-视图-控制器(MVC)架构,让开发者能够将业务逻辑、数据处理和用户界面分离,从而实现更加清晰的代码结构。在Spring MVC中,我们能够集成多种功能和技术来增强应用的功能和性能。 AOP...

    Spring MVC + hibernate 集合

    1. **DispatcherServlet**: Spring MVC 的核心组件,作为前端控制器,负责接收请求并分发到处理器。 2. **Model-View-Controller** 结构:Spring MVC 基于 MVC 设计模式,模型负责业务逻辑,视图负责展示,控制器...

    Java EE企业级应用开发教程 Spring+Spring MVC+MyBatis 第2版 Jav 第2版源码

    Spring MVC是Spring框架的一部分,专门用于构建Web应用程序,它简化了模型-视图-控制器(MVC)模式的实现,提高了开发效率。 MyBatis是一个优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免...

    Java EE 框架整合 开发入门到实战-Spring+Spring MVC+MyBatis微课版复习笔记

    通过以上内容,我们可以了解到Spring框架的核心组件、控制反转和依赖注入的概念和实践方法、Bean的实例化方式以及注解在依赖注入中的应用。此外,了解Spring框架整合MyBatis及Spring MVC的细节,对于开发基于Java EE...

    使用Spring MVC构建Web应用程序1

    在Spring MVC中,控制器是应用程序的核心组件。控制器负责处理用户请求,并将结果返回给用户。控制器可以使用注解来指定请求映射,例如: ```java @Controller @RequestMapping("/user") public class ...

    Spring MVC核心组件之HandlerMapping详解

    `HandlerMapping`是Spring MVC中用于将HTTP请求映射到处理该请求的控制器方法(或称处理器)的组件。简而言之,它的主要职责是从HTTP请求中确定应该调用哪个控制器方法来处理这个请求。 #### 三、DispatcherServlet...

    spring mvc 简单例子

    Spring MVC 支持自动将请求参数绑定到控制器方法的参数上,以及将模型数据自动填充到表单中。这包括基本类型、复杂类型以及集合类型的绑定。 11. **RESTful 风格的支持** Spring MVC 支持创建 RESTful 风格的 Web...

    spring MVC morphia mongo 整合的例子

    6. **Spring整合**:Spring MVC和Morphia可以通过Spring的依赖注入(DI)进行整合,使你能在控制器中直接注入`Datastore`,简化代码并提高可测试性。 7. **RESTful API设计**:示例可能展示了如何使用Spring MVC...

Global site tag (gtag.js) - Google Analytics