In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail "how to get request data from SpringMVC in Java". The content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to get request data from SpringMVC in Java" can help you solve your doubts.
1. Get request parameters
The format of the client request parameter is: name=value&name=value … ... In order to obtain the requested parameters on the server side, sometimes data encapsulation is required. SpringMVC can receive the following types of parameters:
1) basic type parameters:
The parameter name of the business method in Controller should be the same as the name of the request parameter, and the parameter values will automatically map and match.
/ / http://localhost:8080/project/quick9?username=zhangsan&age=12@RequestMapping("/quick9")@ResponseBodypublic void quickMethod9 (String username,int age) throws IOException {System.out.println (username); System.out.println (age);} 2) POJO type parameters:
The property name of the POJO parameter of the business method in Controller is the same as the name of the request parameter, and the parameter values are automatically mapped and matched.
/ / http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12public class User {private String username; private int age; getter/setter … } @ RequestMapping ("/ quick10") @ ResponseBodypublic void quickMethod10 (User user) throws IOException {System.out.println (user);} 3) Array type parameter
The business method array name in Controller is the same as the name of the request parameter, and the parameter values are automatically mapped and matched.
/ / http://localhost:8080/project/quick11?strs=111&strs=222&strs=333@RequestMapping("/quick11")@ResponseBodypublic void quickMethod11 (String [] strs) throws IOException {System.out.println (Arrays.asList (strs));} 4) Collection type parameters
When you get the collection parameters, you need to wrap the collection parameters in a POJO.
RequestMapping ("/ quick12") @ ResponseBodypublic void quickMethod12 (Vo vo) throws IOException {System.out.println (vo.getUserList ());}
When you use ajax submission, you can specify contentType as json, so you can use @ RequestBody at the method parameter location to receive collection data directly without wrapping it with POJO.
/ / Analog data var userList = new Array (); userList.push ({username: "zhangsan", age: "20"}); userList.push ({username: "lisi", age: "20"}); $.ajax ({type: "POST", url: "/ itheima_springmvc1/quick13", data: JSON.stringify (userList), contentType: 'application/json;charset=utf-8'}) @ RequestMapping ("/ quick13") @ ResponseBodypublic void quickMethod13 (@ RequestBody List userList) throws IOException {System.out.println (userList);}
Note: through the Google developer tool grab package, it is found that it is not loaded into the jquery file, because the url-pattern of SpringMVC's front-end controller DispatcherServlet is configured to filter all resources. We can specify the release of static resources in the following two ways: specify the released resources in the spring-mvc.xml configuration file
Or use tags.
two。 Request garbled problem
When the post request, the data will be garbled, we can set a filter in web.xml to filter the code.
CharacterEncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 CharacterEncodingFilter / *
When the requested parameter name does not match the business method parameter name of Controller, the binding shown by the @ RequestParam annotation is required.
3. Parameter binding annotation @ RequestParam
The annotation @ RequestParam also has the following parameters to use:
Value: request parameter name required: whether the specified request parameter must be included. The default is true. If this parameter is not specified, an error defaultValue is reported: when no request parameter is specified, the specified default value is assigned to @ RequestMapping ("/ quick14") @ ResponseBodypublic void quickMethod14 (@ RequestParam (value= "name", required = false,defaultValue = "defaultname") String username) throws IOException {System.out.println (username);} 4. Get parameters of Restful style
Restful is a software architecture style, design style, not a standard, but provides a set of design principles and constraints. Mainly used for client and server mutual class software, based on this style of software design can be more concise, more hierarchical, easier to implement caching mechanism and so on.
A Restful-style request uses "url+ request method" to indicate the purpose of a request. The four verbs in the HTTP protocol to indicate the operation mode are as follows:
GET: get resources DELETE: delete resources PUT: update resources POST: create new resources
For example:
/ user/1 GET: get the user/user/1 DELETE of id = 1: delete the user/user/1 PUT of id = 1; update the useruser POST of id = 1: add user
The 1 in the above url address / user/1 is the request parameter to be obtained, which can be bound with a placeholder in SpringMVC. The address / user/1 can be written as / user/ {id}, and the placeholder {id} corresponds to the value of 1. In the business method, we can use the @ PathVariable annotation to match placeholders.
/ / http://localhost:8080/itheima_springmvc1/quick19/zhangsan@RequestMapping("/quick19/{name}")@ResponseBodypublic void quickMethod19 (@ PathVariable (value = "name", required = true) String name) {System.out.println (name);} 5. Custom type converter
Although SpringMVC already provides some common type converters by default, for example, the string submitted by the client is converted to int for parameter setting.
However, not all data types provide converters, and custom converters are required for those that are not provided. For example, custom converters are required for date-type data.
Development steps for custom type converters:
① defines the converter class to implement Converter interface
Public class DateConverter implements Converter {@ Override public Date convert (String source) {SimpleDateFormat format=new SimpleDateFormat ("yyyy-MM-dd"); Date date = null; try {date = format.parse (source);} catch (ParseException e) {e.printStackTrace ();} return date;}}
② declares the converter in the spring-mvc.xml configuration file
③ references the converter in
6. Get the request header
@ RequestHeader
Request header information can be obtained using @ RequestHeader. The attributes of the request.getHeader (name) @ RequestHeader annotation equivalent to web phase learning are as follows:
Whether the name of the value request header required must carry this request header @ RequestMapping ("/ quick17") @ ResponseBodypublic void quickMethod17 (@ RequestHeader (value = "User-Agent", required = false) String headerValue) {System.out.println (headerValue);}
@ CookieValue
Using @ CookieValue, you can get the value of the specified Cookie @ CookieValue annotation. The attributes are as follows:
Value specifies whether the name of the cookie required must carry this cookie@RequestMapping ("/ quick18") @ ResponseBodypublic void quickMethod18 (@ CookieValue (value = "JSESSIONID", required = false) String jsessionid) {System.out.println (jsessionid);} 7. File upload
Three elements of file upload client:
Form item type= "file"
The form is submitted by post
The enctype property of the form is in multipart form form, and enctype= "multipart/form-data"
Name:
File:
File upload steps
① imports fileupload and io coordinates in pom.xml
Commons-fileupload commons-fileupload 1.4 commons-io commons-io 2.6
② profile upload parser
③ write file upload code
@ RequestMapping ("/ quick8") @ ResponseBody public void save8 (String name, MultipartFile uploadfile) {System.out.println ("save8 running..."); System.out.println (name); String filename = uploadfile.getOriginalFilename (); try {uploadfile.transferTo (new File ("D:\ upload\" + filename));} catch (IOException e) {e.printStackTrace () }} here, the article "how to obtain request data from SpringMVC in Java" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to learn more about related articles, please follow the industry information channel.
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.