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是有顺序的,这点很重要!