In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to use @ RequestBody to transfer multiple different objects". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to use @ RequestBody to transfer multiple different objects"!
Catalogue
@ RequestBody passes multiple different objects
Solution 1
Solution 2
Use multiple @ RequestBody to receive parameters
Reason
Solution: two classes, just copy directly.
@ RequestBody passes multiple different objects
If you use spring mvc to communicate with the client and completely use the json data format, you need to add RequestBody annotations, and the function argument is a custom class.
Controllerpublic class TestController {@ RequestMapping ("\ test") @ ResponseBody public RetureResult test (@ RequestBody User user) {return new ReturnResult ();}}
In this way, the received data in json format can be converted into the specified data object user. For example, {name: "test"}, name is the property field of the User class. With ResponseBody annotations, you can return data in json format.
Sometimes when we receive data in json format, we may need to convert it to multiple objects.
The following methods are wrong. The reason is that the content-body of request is read as a stream, and after reading it once, it cannot be read again.
@ Controllerpublic class TestController {@ RequestMapping ("\ test") @ ResponseBody public RetureResult test (@ RequestBody User user,@RequestBody Address address) {return new ReturnResult ();}} solution 1
Add a wrapper class, write the required class, and add the get,set method
@ Controllerpublic class TestController {@ RequestMapping ("\ test") @ ResponseBody public RetureResult test (@ RequestBody Param param) {User user=param.getUser (); Address address=param.getAddress (); return new ReturnResult ();}} class Param {private User user; private Address address; public User getUser () {return user;} public void setUser (User user) {this.user = user;} public Address getAddress () {return address } public void setAddress (Address address) {this.address = address;}}
At this point, the format of the transmitted json data becomes {user: {name: "test"}, address: {location: "Xinhua Road"}}.
Because only a wrapper class is added to TestController, it will not affect other classes and the defined model class, so it is very convenient to receive multiple object parameters.
Solution 2
Define the receive parameter as Map, and then use the map to object tool to convert it to the desired object.
At this point, it doesn't matter if there are fewer attributes in the custom Param class than in the json data.
JSONUtils is a custom tool class, which can be packaged and implemented using common toolkits such as fastjson.
Controllerpublic class TestController {@ RequestMapping ("\ test") @ ResponseBody public Object test (@ RequestBody Map models) {User user=JsonXMLUtils.map2object ((Map) models.get ("user"), User.class); Address address=JsonXMLUtils.map2object ((Map) models.get ("address"), Address.class); return models;}} import com.alibaba.fastjson.JSON; public class JsonXMLUtils {public static String obj2json (Object obj) throws Exception {return JSON.toJSONString (obj) } public static T json2obj (String jsonStr, Class clazz) throws Exception {return JSON.parseObject (jsonStr, clazz);} public static Map json2map (String jsonStr) throws Exception {return JSON.parseObject (jsonStr, Map.class);} public static T map2obj (Map map, Class clazz) throws Exception {return JSON.parseObject (JSON.toJSONString (map), clazz);}} use multiple @ RequestBody to receive parameter reasons
Normally, because the body of request can only be read once and @ RequestBody can only be parsed once, stream is closed when the second @ RequestBody is parsed and cannot be read again.
Don't say much, pick up the goods:
Solution: two classes, import javax.servlet.ReadListener;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import java.io.*; public class BodyReaderRequestWrapper extends HttpServletRequestWrapper {private final String body; / * * @ param request * / public BodyReaderRequestWrapper (HttpServletRequest request) throws IOException {super (request); StringBuilder sb = new StringBuilder () InputStream ins = request.getInputStream (); BufferedReader isr = null; try {if (ins! = null) {isr = new BufferedReader (new InputStreamReader (ins)); char [] charBuffer = new char [128]; int readCount = 0 While ((readCount = isr.read (charBuffer))! =-1) {sb.append (charBuffer,0,readCount);}} else {sb.append (");}} catch (IOException e) {throw e } finally {if (isr! = null) {isr.close ();}} sb.toString (); body = sb.toString ();} @ Override public BufferedReader getReader () throws IOException {return new BufferedReader (new InputStreamReader (this.getInputStream () } @ Override public ServletInputStream getInputStream () throws IOException {final ByteArrayInputStream byteArrayIns = new ByteArrayInputStream (body.getBytes ()); ServletInputStream servletIns = new ServletInputStream () {@ Override public boolean isFinished () {return false;} @ Override public boolean isReady () {return false } @ Override public void setReadListener (ReadListener readListener) {} @ Override public int read () throws IOException {return byteArrayIns.read ();}; return servletIns;}} import org.springframework.stereotype.Component; import javax.servlet.*;import javax.servlet.annotation.WebFilter Import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException; @ Component@WebFilter (filterName = "crownFilter", urlPatterns = "/ *") public class BodyReaderRequestFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; BodyReaderRequestWrapper requestWrapper = new BodyReaderRequestWrapper (request) If (requestWrapper = = null) {filterChain.doFilter (request,response);} else {filterChain.doFilter (requestWrapper,response);} @ Override public void destroy () {}}
Use: self-test.
At this point, I believe you have a better understanding of "how to use @ RequestBody to transfer multiple different objects". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.