leftso 1979 0 2018-03-24 09:45:14

文章位置:左搜> 编程技术> 正文

引言

    在之前,我一直以为http传输的参数是KEY-VALUE键值对的方式和文件流的形式。直到最近遇到新需求才知道还有一种RAW的数据类型。通过这种原生的数据类型进行传输需要指定传输的格式也就是HTTP的头部content type。接下来也将用raw这个类型的传输方式来实现mvc的对象集合参数接收。

一.创建一个spring mvc的web项目

  为了方便,我这里创建的一个spring boot的web项目。大家都知道spring boot来创建spring 的web项目是非常快的。

下面是项目的结构图:

spring boot web项目结构图

二.实战spring mvc 5接收集合对象参数编码

2.1创建一个pojo对象

这里创建的一个Person的简单对象。该对象主要用来等会传递参数使用。
package net.xqlee.project.pojo;

/**
 * 简单对象
 * 
 * @author xqlee
 *
 */
public class Persion {
	private String id;
	private String name;

	@Override
	public String toString() {
		return "ID:" + id + ",name:" + name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
*可以看到这个对象确实挺简单的。就两个属性以及属性的get/set方法。重写了下toString()方法用来等会打印输出测试。

2.2创建一个controller用来接收数组/集合对象

package net.xqlee.project.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import net.xqlee.project.pojo.Persion;

@RestController
public class TestController {

	private static final Logger log = LoggerFactory.getLogger(TestController.class);

	@PostMapping("arrParams.json")
	public Object arrParams(@RequestBody List<Persion> list) {
		for (Persion persion : list) {
			log.info(persion.toString());
		}
		return true;
	}
}
*注意,上面实现接收集合/数组对象的主要在于注解@RequestBody他会将请求的内容进行封装到list(如果请求的格式符合bean的要求)

三.演示实战

3.1启动spring boog项目


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::             (v2.0.0.M6)

2017-11-19 20:20:38.489  INFO 1888 --- [           main] n.x.p.DemoSpringbootPublicApplication    : Starting DemoSpringbootPublicApplication on DESKTOP-2RG0A6O with PID 1888 (D:\workplace\eclipse_mvn\demo-springboot-public\target\classes started by xqlee in D:\workplace\eclipse_mvn\demo-springboot-public)
2017-11-19 20:20:38.492  INFO 1888 --- [           main] n.x.p.DemoSpringbootPublicApplication    : No active profile set, falling back to default profiles: default
2017-11-19 20:20:38.535  INFO 1888 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@419c5f1a: startup date [Sun Nov 19 20:20:38 CST 2017]; root of context hierarchy
2017-11-19 20:20:39.664  INFO 1888 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2017-11-19 20:20:39.676  INFO 1888 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-11-19 20:20:39.677  INFO 1888 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-19 20:20:39.693  INFO 1888 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [H:\TDDOWNLOAD\eclipse-jee-neon-3-win32-x86_64\eclipse\external\jdk\jdk1.8.0_40\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:/software/eclipse-v4.6.3/eclipse//external/jdk/jdk1.8.0_40/jre/bin/server;D:/software/eclipse-v4.6.3/eclipse//external/jdk/jdk1.8.0_40/jre/bin;D:/software/eclipse-v4.6.3/eclipse//external/jdk/jdk1.8.0_40/jre/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\ImageMagick-7.0.6-Q16;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jdk1.8.0_102\bin;C:\Program Files\Java\jdk1.8.0_102;C:\Program Files\nodejs\;C:\Program Files\MySQL\MySQL Server 5.5\bin;C:\Users\xqlee\AppData\Local\Microsoft\WindowsApps;C:\Users\xqlee\AppData\Roaming\npm;D:\software\eclipse-v4.6.3\eclipse;;.]
2017-11-19 20:20:39.764  INFO 1888 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-11-19 20:20:39.764  INFO 1888 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1232 ms
2017-11-19 20:20:39.864  INFO 1888 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-19 20:20:39.868  INFO 1888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-19 20:20:39.868  INFO 1888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-19 20:20:39.868  INFO 1888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-19 20:20:39.868  INFO 1888 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-19 20:20:40.134  INFO 1888 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@419c5f1a: startup date [Sun Nov 19 20:20:38 CST 2017]; root of context hierarchy
2017-11-19 20:20:40.195  INFO 1888 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/arrParams.json],methods=[POST]}" onto public java.lang.Object net.xqlee.project.controller.TestController.arrParams(java.util.List<net.xqlee.project.pojo.Persion>)
2017-11-19 20:20:40.198  INFO 1888 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-19 20:20:40.199  INFO 1888 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-19 20:20:40.220  INFO 1888 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-19 20:20:40.220  INFO 1888 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-19 20:20:40.251  INFO 1888 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-19 20:20:40.375  INFO 1888 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-19 20:20:40.435  INFO 1888 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http)
2017-11-19 20:20:40.438  INFO 1888 --- [           main] n.x.p.DemoSpringbootPublicApplication    : Started DemoSpringbootPublicApplication in 2.252 seconds (JVM running for 2.598)
*可以看到spring boot项目已经在本地的8080端口启动

3.2通过postmain工具进行调用接口测试

调用spring web
如上图所示,
1.选择传输参数的类型为raw
2.选择具体的参数类型为JSON
3.测试数据

点击postmain工具的发送请求按钮观察eclipse的控制台:
Java spring web接口调用图
从上图中可以看到我们的集合参数已经成功接收。