SpringMVC如何处理controller的各种返回类型

问题描述

SpringMVC如何处理controller的各种返回类型

本人小白,求教一下各位大神,springMVC的controller的返回值都可以是什么类型?
然后springMVC对于各种返回类型是怎么处理的。
比如,我知道,如果controller返回string类型的值,那么springMVC会根据视图解析器拼接得到url,从而知道目标视图。
那么,当controlloer返回Map类型、void类型、ModelAndView(有些ModelAndView设置了viewName,有些又没设置),对于这些类型,springMVC框架都是如何处理。

解决方案

对于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}. *
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. * @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 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 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 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 index() { Map map = new HashMap(); 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. * *
This class and the MVC approach associated with it is discussed in Chapter 12 of * Expert One-On-One J2EE Design and Development * by Rod Johnson (Wrox, 2002). * *
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. * *
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. *
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. * *
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. *
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. *
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 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 test(HttpServletResponse response) { return new ResponseEntity("这是测试", HttpStatus.OK); }
文件的demo:
@RequestMapping("download") public ResponseEntity 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(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); }
PS:使用ResponseEntity需要正确配置AnnotationMethodHandlerAdapter,messageConverters中的list是有顺序的,这点很重要!
解决方案二:

实例参考:http://blog.csdn.net/sunhuwh/article/details/41727257

解决方案三:

回答的人怎么这少...
回答得不够明白啊,小弟还是不清楚。。

解决方案四:

回答的人怎么这少...
回答得不够明白啊,小弟还是不清楚。。

解决方案五:

简单说 如果你要跳转页面可以用return ModelAndView(页面)。addobject(“something”,“value”)
如果你是ajax请求你可以在该controlloer方法上配置@ResponseBody ajax数据接收类型写上json就可以获取了。
将会自动将map,string等类型返回成json形式,当然需要配置声明式注解。

解决方案六:

当controlloer返回Map类型 ,相当于返回一个json对象
、void类型、返回内容直接从response输出流里取
ModelAndView 是视图和数据的封装 ,可以往作用域里传递对象参数,可以指定跳转路径 ,相当于request作用域和forward结合

解决方案七:

SpringMVC返回类型
SpringMVC 中 jsp 页面对 Controller 返回数据的使用
spring mvc 控制器(Controller)中可以返回的类型

时间: 2024-12-30 23:37:04

SpringMVC如何处理controller的各种返回类型的相关文章

详解SpringMVC中Controller的方法中参数的工作原理[附带源码分析] good

目录 前言 现象 源码分析 HandlerMethodArgumentResolver与HandlerMethodReturnValueHandler接口介绍 HandlerMethodArgumentResolver与HandlerMethodReturnValueHandler接口的具体应用 常用HandlerMethodArgumentResolver介绍 常用HandlerMethodReturnValueHandler介绍 本文开头现象解释以及解决方案 编写自定义的HandlerMet

java抢购功能问题,大并发情况下spring-mvc如何处理

问题描述 java抢购功能问题,大并发情况下spring-mvc如何处理 由spring托管的controller是单例的,正常情况下大并发访问同一接口,应该是会出现并发问题的,现在公司有一个抢购功能需要实现,数据库中有一个字段保存了当前商品剩余量,每次请求如果成功会将这个剩余量减1,多并发的情况会不会将这个值扣减为负数,请问这块功能应该从哪几个维度去考虑,如果不使用异步处理,在保证效率的前提下该如何解决并发问题 解决方案 数据库本身就可以控制,比如SQL Server两句语句就可以搞定 UPD

C# web api返回类型设置为json的两种方法

 web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面为大家介绍几种不错的方法 web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法:  方法一:(改配置法)    找到Global.asax文件,在Application_Start()方法中添加一句:   代码如下: GlobalConfiguration.Configuration.Formatters.

配置-SpringMVC中怎么将@ResponseBody返回Json数据在log4j中输出

问题描述 SpringMVC中怎么将@ResponseBody返回Json数据在log4j中输出 SpringMVC中怎么将@ResponseBody返回Json数据在log4j中输出 spring配置如下: <!-- json转换器 --> text/html;charset=UTF-8 controller如下: @RequestMapping("/saveUser") @ResponseBody public User saveUser(){ User user =

表单数据-使用springmvc中controller怎么实现JSP页面数据提交到oracle数据库,求代码。

问题描述 使用springmvc中controller怎么实现JSP页面数据提交到oracle数据库,求代码. 如何使用controller进行JSP页面输入数据的存储,如图,怎么写这个功能的代码,将咨询内容提交到后台数据库中,然后在后台管理的页面进行对该问题的回复.求大神给写个代码.谢谢. 解决方案 你要把数据传递到后台,然后在保存到数据库里面,建议使用Ajax操作,先把数据传递到后台,通过业务逻辑保存好了之后,再把你的回复通过Ajax的回调函数返回到界面 解决方案二: 怎么写的,求给个代码.

C# web api返回类型设置为json的两种方法_实用技巧

web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法) 找到Global.asax文件,在Application_Start()方法中添加一句: 复制代码 代码如下: GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 修改后: 复制代码 代码如下: protected void

IntelliSense为何无法重载仅按返回类型区分的函数

IntelliSense:无法重载仅按返回类型区分的函数 d:\programfiles (x86)\microsoft sdks\windows\v7.0a\include\winbase.h       3540 在VS2010下用C语言写Windows系统服务,从另一个c#的项目中Copy过来一段代码,修改后再编译,就产生了这个错误! 在网上搜索得到的答案是:"无法重载仅按返回类型区分的函数"这种情况一般只会发生在有同名函数的情况下,但是我那段代码里却没有同名函数. 根据以往的经

SpringMVC中Controller的方法中参数的工作原理

前言 SpringMVC是目前主流的Web MVC框架之一. 如果有同学对它不熟悉,那么请参考它的入门blog:http://www.cnblogs.com/fangjian0423/p/springMVC-introduction.html SpringMVC中Controller的方法参数可以是Integer,Double,自定义对象,ServletRequest,ServletResponse,ModelAndView等等,非常灵活.本文将分析SpringMVC是如何对这些参数进行处理的,

子类方法返回类型必须和父类相同,抛出的异常声明可以小于或等于父类

Overload译为重载:Override译为重写或者覆盖:  Overload讨论: Java中同一个类不可以有两个相同的方法(方法名.参数类型.参数个数和参数位置都  相同).但可以有方法名相同,参数不同(参数类型.参数个数和参数位置不相同)的方法.这  种相同的方法名,参数不同的方法称为重载. public class Test { public void fn(String name) {} public void fn(int age) {} public void fn(String