在这篇文章中,我们将为您详细介绍SpringMVC注解@RequestMapping@RequestParam@ResponseBody和@RequestBody解析的内容,并且讨论关于springm
在这篇文章中,我们将为您详细介绍SpringMVC注解@RequestMapping @RequestParam @ResponseBody 和 @RequestBody 解析的内容,并且讨论关于springmvc注解的意思的相关问题。此外,我们还会涉及一些关于
- SpringMVC注解@RequestMapping @RequestParam @ResponseBody 和 @RequestBody 解析(springmvc注解的意思)
Spring MVC之@RequestBody, @ResponseBody 详解 - @Param @PathVariable @RequestParam @ResponseBody @RequestBody注解说明
- @RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别
- @RequestMapping @ResponseBody 和 @RequestBody 用法与区别
SpringMVC注解@RequestMapping @RequestParam @ResponseBody 和 @RequestBody 解析(springmvc注解的意思)
SpringMVC Controller层获取参数及返回数据的方式:
@RequestMapping
@RequestMapping(“url”),这里的 url写的是请求路径的一部分,一般作用在 Controller的方法上,作为请求的映射地址。
代码:
@RequestMapping(value = "/test")//类级别映射,可以没有,一般用于减少书写量
public class myController {
//方法级别映射,必须有,那么这个方法的访问地址就是/test/aaa,请求到的页面就是test.jsp【当然,这里的.jsp需要在配置文件中配置】
@RequestMapping(value = "/aaa")
public String getMyName() {
return "test";
}
}
@RequestParam
在SpringMVC后台控制层获取参数的方式主要有两种,一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取。这里主要讲这个注解
一、基本使用,获取提交的参数
后端代码:
@RequestMapping("testRequestParam")
public String filesUpload(@RequestParam String inputStr, HttpServletRequest request) {
System.out.println(inputStr);
int inputInt = Integer.valueOf(request.getParameter("inputInt"));
System.out.println(inputInt);
// ......省略
return "index";
}
前端代码:
<form action="/gadget/testRequestParam" method="post">
参数inputStr:<input type="text" name="inputStr">
参数intputInt:<input type="text" name="inputInt">
</form>
前端界面:
执行结果:
test1
123
可以看到spring会自动根据参数名字封装进入,我们可以直接拿这个参数名来用
二、各种异常情况处理
1、可以对传入参数指定参数名
@RequestParam String inputStr
// 下面的对传入参数指定为aa,如果前端不传aa参数名,会报错
@RequestParam(value="aa") String inputStr
错误信息:
HTTP Status 400 - Required String parameter ''aa'' is not present
2、可以通过required=false或者true来要求@RequestParam配置的前端参数是否一定要传
// required=false表示不传的话,会给参数赋值为null,required=true就是必须要有
@RequestMapping("testRequestParam")
public String filesUpload(@RequestParam(value="aa", required=true) String inputStr, HttpServletRequest request)
3、如果用@RequestMapping注解的参数是int基本类型,但是required=false,这时如果不传参数值会报错,因为不传值,会赋值为null给int,这个不可以
@RequestMapping("testRequestParam")
public String filesUpload(@RequestParam(value="aa", required=true) String inputStr,
@RequestParam(value="inputInt", required=false) int inputInt
,HttpServletRequest request) {
// ......省略
return "index";
}
解决方法:
“Consider declaring it as object wrapper for the corresponding primitive type.”建议使用包装类型代替基本类型,如使用“Integer”代替“int”
@RequestBody
@RequestBody是作用在形参列表上,用于将前台发送过来固定格式的数据【xml 格式或者 json等】封装为对应的 JavaBean 对象,封装时使用到的一个对象是系统默认配置的 HttpMessageConverter进行解析,然后封装到形参上。
@ResponseBody
@ResponseBody是作用在方法上的,@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。 比如异步获取 json 数据,加上 @ResponseBody 后,会直接返回 json 数据。@RequestBody 将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
需要注意的呢,在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
@ResponseBody是作用在方法上的,@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。 比如异步获取 json 数据,加上 @ResponseBody 后,会直接返回 json 数据。@RequestBody 将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
Spring MVC之@RequestBody, @ResponseBody 详解
引言:
接上一篇文章讲述处理@RequestMapping的方法参数绑定之后,详细介绍下@RequestBody、@ResponseBody的具体用法和使用时机;
简介:
@RequestBody
作用:
i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
使用时机:
A) GET、POST方式提时, 根据request header Content-Type的值来判断:
- application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
- multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
- 其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);
B) PUT方式提交时, 根据request header Content-Type的值来判断:
- application/x-www-form-urlencoded, 必须;
- multipart/form-data, 不能处理;
- 其他格式, 必须;
说明:request的body部分的数据编码格式由header部分的Content-Type指定;
@ResponseBody
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
HttpMessageConverter
[java] view plaincopy
- <span >/**
- * Strategy interface that specifies a converter that can convert from and to HTTP requests and responses.
- *
- * @author Arjen Poutsma
- * @author Juergen Hoeller
- * @since 3.0
- */
- public interface HttpMessageConverter<T> {
- /**
- * Indicates whether the given class can be read by this converter.
- * @param clazz the class to test for readability
- * @param mediaType the media type to read, can be {@code null} if not specified.
- * Typically the value of a {@code Content-Type} header.
- * @return {@code true} if readable; {@code false} otherwise
- */
- boolean canRead(Class<?> clazz, MediaType mediaType);
- /**
- * Indicates whether the given class can be written by this converter.
- * @param clazz the class to test for writability
- * @param mediaType the media type to write, can be {@code null} if not specified.
- * Typically the value of an {@code Accept} header.
- * @return {@code true} if writable; {@code false} otherwise
- */
- boolean canWrite(Class<?> clazz, MediaType mediaType);
- /**
- * Return the list of {@link MediaType} objects supported by this converter.
- * @return the list of supported media types
- */
- List<MediaType> getSupportedMediaTypes();
- /**
- * Read an object of the given type form the given input message, and returns it.
- * @param clazz the type of object to return. This type must have previously been passed to the
- * {@link #canRead canRead} method of this interface, which must have returned {@code true}.
- * @param inputMessage the HTTP input message to read from
- * @return the converted object
- * @throws IOException in case of I/O errors
- * @throws HttpMessageNotReadableException in case of conversion errors
- */
- T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
- throws IOException, HttpMessageNotReadableException;
- /**
- * Write an given object to the given output message.
- * @param t the object to write to the output message. The type of this object must have previously been
- * passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}.
- * @param contentType the content type to use when writing. May be {@code null} to indicate that the
- * default content type of the converter must be used. If not {@code null}, this media type must have
- * previously been passed to the {@link #canWrite canWrite} method of this interface, which must have
- * returned {@code true}.
- * @param outputMessage the message to write to
- * @throws IOException in case of I/O errors
- * @throws HttpMessageNotWritableException in case of conversion errors
- */
- void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
- throws IOException, HttpMessageNotWritableException;
- }
- </span>
该接口定义了四个方法,分别是读取数据时的 canRead(), read() 和 写入数据时的canWrite(), write()方法。
在使用 <mvc:annotation-driven />标签配置时,默认配置了RequestMappingHandlerAdapter(注意是
RequestMappingHandlerAdapter
不是AnnotationMethodHandlerAdapter,详情查看Spring 3.1 document “16.14 Configuring Spring MVC”章节),并为他配置了一下默认的HttpMessageConverter:
[java] view plaincopy
- ByteArrayHttpMessageConverter converts byte arrays.
- StringHttpMessageConverter converts strings.
- ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types.
- SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.
- FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.
- Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present on the classpath.
- MappingJacksonHttpMessageConverter converts to/from JSON — added if Jackson is present on the classpath.
- AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath.
- RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.
ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;
StringHttpMessageConverter: 负责读取字符串格式的数据和写出二进制格式的数据;
ResourceHttpMessageConverter:负责读取资源文件和写出资源文件数据;
FormHttpMessageConverter: 负责读取form提交的数据(能读取的数据格式为 application/x-www-form-urlencoded,不能读取multipart/form-data格式数据);负责写入application/x-www-from-urlencoded和multipart/form-data格式的数据;
MappingJacksonHttpMessageConverter: 负责读取和写入json格式的数据;
SouceHttpMessageConverter: 负责读取和写入 xml 中javax.xml.transform.Source定义的数据;
Jaxb2RootElementHttpMessageConverter: 负责读取和写入xml 标签格式的数据;
AtomFeedHttpMessageConverter: 负责读取和写入Atom格式的数据;
RssChannelHttpMessageConverter: 负责读取和写入RSS格式的数据;
当使用@RequestBody和@ResponseBody注解时,
RequestMappingHandlerAdapter
就使用它们来进行读取或者写入相应格式的数据。
HttpMessageConverter匹配过程:
@RequestBody注解时: 根据Request对象header部分的Content-Type类型,逐一匹配合适的HttpMessageConverter来读取数据;
spring 3.1源代码如下:
[java] view plaincopy
- <span >private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType)
- throws Exception {
- MediaType contentType = inputMessage.getHeaders().getContentType();
- if (contentType == null) {
- StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType()));
- String paramName = methodParam.getParameterName();
- if (paramName != null) {
- builder.append('' '');
- builder.append(paramName);
- }
- throw new HttpMediaTypeNotSupportedException(
- "Cannot extract parameter (" + builder.toString() + "): no Content-Type found");
- }
- List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
- if (this.messageConverters != null) {
- for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
- allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
- if (messageConverter.canRead(paramType, contentType)) {
- if (logger.isDebugEnabled()) {
- logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType
- +"\" using [" + messageConverter + "]");
- }
- return messageConverter.read(paramType, inputMessage);
- }
- }
- }
- throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
- }</span>
@ResponseBody注解时: 根据Request对象header部分的Accept属性(逗号分隔),逐一按accept中的类型,去遍历找到能处理的HttpMessageConverter;
源代码如下:
[java] view plaincopy
- <span >private void writeWithMessageConverters(Object returnValue,
- HttpInputMessage inputMessage, HttpOutputMessage outputMessage)
- throws IOException, HttpMediaTypeNotAcceptableException {
- List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
- if (acceptedMediaTypes.isEmpty()) {
- acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
- }
- MediaType.sortByQualityValue(acceptedMediaTypes);
- Class<?> returnValueType = returnValue.getClass();
- List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
- if (getMessageConverters() != null) {
- for (MediaType acceptedMediaType : acceptedMediaTypes) {
- for (HttpMessageConverter messageConverter : getMessageConverters()) {
- if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
- messageConverter.write(returnValue, acceptedMediaType, outputMessage);
- if (logger.isDebugEnabled()) {
- MediaType contentType = outputMessage.getHeaders().getContentType();
- if (contentType == null) {
- contentType = acceptedMediaType;
- }
- logger.debug("Written [" + returnValue + "] as \"" + contentType +
- "\" using [" + messageConverter + "]");
- }
- this.responseArgumentUsed = true;
- return;
- }
- }
- }
- for (HttpMessageConverter messageConverter : messageConverters) {
- allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
- }
- }
- throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
- }</span>
补充:
MappingJacksonHttpMessageConverter 调用了 objectMapper.writeValue(OutputStream stream, Object)方法,使用@ResponseBody注解返回的对象就传入Object参数内。若返回的对象为已经格式化好的json串时,不使用@RequestBody注解,而应该这样处理:
1、response.setContentType("application/json; charset=UTF-8");
2、response.getWriter().print(jsonStr);
直接输出到body区,然后的视图为void。
@Param @PathVariable @RequestParam @ResponseBody @RequestBody注解说明
@Param主要是用来注解dao类中方法的参数,在不使用@Param注解的时候,函数的参数只能为一个,并且在查询语句取值时只能用#{},且其所属的类必须为Javabean,而使用@Param注解则可以使用多个参数,在查询语句中使用时可以使用#{}或者${}
@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上,http://127.0.0.1:8040/findById/1-->>@GetMapping("/findById/{id}") 参数不能为空
@RequestParam注解主要有哪些参数:
value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;
defaultValue:默认值,表示如果请求中没有同名参数时的默认值,例如:
public List<EasyUITreeNode> getItemTreeNode(@RequestParam(value="id",defaultValue="0")long parentId)
@ResponseBody将响应的结果转为json格式
@RequestBody将请求参数转为json格式
@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别
1.@RequestMapping
国际惯例先介绍什么是@RequestMapping,@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法,此处需注意@RequestMapping用在类上可以没用,但是用在方法上必须有。
@RequestMapping("/verifyCode")
public void verifyCode(HttpServletResponse response, HttpSession session){
response.setDateHeader("Expires", -1);
response.setHeader("Cache-Control", "no-cache");
VerifyCode vc = new VerifyCode();
try {
vc.drawImage(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
String code = vc.getCode();
session.setAttribute("code", code);
System.out.println(code);
}
2.@ResponseBody
@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
@ResponseBody
public void activeUser(String userId, String activecode, HttpServletResponse response){
userInfoService.activeUser(userId, activecode);
// 定时刷新
response.setContentType("text/html;charset=utf-8");
try {
response.getWriter().write("激活成功,3秒之后回到登录界面进行登录...");
response.setHeader("refresh", "3;url=/login");
} catch (IOException e) {
e.printStackTrace();
}
}
3.@RequestBody
@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
作用:
1) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
2) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
@RequestMapping @ResponseBody 和 @RequestBody 用法与区别
1.@RequestMapping
国际惯例先介绍什么是@RequestMapping,@RequestMapping 是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法,此处需注意@RequestMapping用在类上可以没用,但是用在方法上必须有。
例如:
@Controller
//设置想要跳转的父路径
@RequestMapping(value = "/Controllers")
public class StatisticUserCtrl {
//如需注入,则写入需要注入的类
//@Autowired
// 设置方法下的子路经
@RequestMapping(value = "/method")
public String helloworld() {
return "helloWorld";
}
}
原理也非常好了解,其对应的 action 就是“ (父路径) controller/(父路径下方法路经)method ”。因此,在本地服务器上访问方法 http://localhost:8080/controller/method 就会返回(跳转)到“ helloWorld.jsp ”页面。
说到这了,顺便说一下 @PathVariable 注解,其用来获取请求路径(url )中的动态参数。
页面发出请求:
function login() {
var url = "${pageContext.request.contextPath}/person/login/";
var query = $(''#id'').val() + ''/'' + $(''#name'').val() + ''/'' + $(''#status'').val();
url += query;
$.get(url, function(data) {
alert("id: " + data.id + "name: " + data.name + "status: "
+ data.status);
});
}
如:
/**
* @RequestMapping(value = "user/login/{id}/{name}/{status}") 中的 {id}/{name}/{status}
* 与 @PathVariable int id、@PathVariable String name、@PathVariable boolean status
* 一一对应,按名匹配。
*/
@RequestMapping(value = "user/login/{id}/{name}/{status}")
@ResponseBody
//@PathVariable注解下的数据类型均可用
public User login(@PathVariable int id, @PathVariable String name, @PathVariable boolean status) {
//返回一个User对象响应ajax的请求
return new User(id, name, status);
}
ResponseBody
@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
当页面发出异步请求:
function login() {
var datas = ''{"username":"'' + $(''#username'').val() + ''","userid":"'' + $(''#userid'').val() + ''","status":"'' + $(''#status'').val() + ''"}'';
$.ajax({
type : ''POST'',
contentType : ''application/json'',
url : "${pageContext.request.contextPath}/user/login",
processData : false,
dataType : ''json'',
data : datas,
success : function(data) {
alert("userid: " + data.userid + "username: " + data.username + "status: "+ data.status);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("出现异常,异常信息:"+textStatus,"error");
}
});
};
如:
@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中,返回json对象响应回去
public User login(User user) {
User user = new User();
user .setUserid(1);
user .setUsername("MrF");
user .setStatus("1");
return user ;
}
步获取 json 数据,加上 @Responsebody 注解后,就会直接返回 json 数据。
@RequestBody
@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
作用:
1) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
2) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
使用时机:
A) GET、POST方式提时, 根据request header Content-Type的值来判断:
application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);
B) PUT方式提交时, 根据request header Content-Type的值来判断:
application/x-www-form-urlencoded, 必须;multipart/form-data, 不能处理;其他格式, 必须;
说明:request的body部分的数据编码格式由header部分的Content-Type指定;
例如:
@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入 User 对象中
public User login(@RequestBody User user) {
// 这样就不会再被解析为跳转路径,而是直接将user对象写入 HTTP 响应正文中
return user;
}
今天关于SpringMVC注解@RequestMapping @RequestParam @ResponseBody 和 @RequestBody 解析和springmvc注解的意思的介绍到此结束,谢谢您的阅读,有关
本文标签: