Request parameters accepted by Spring MVC

Source: Internet
Author: User

[TOC]

1. Overview

Spring MVC allows the client's data to be transferred to the Controller's processing methods in several ways:

    • Querying parameters (query Parameter)
    • Form parameters (Form Parameter)
    • Path Variant (path Variable)
2. Detailed 2.1 Processing query parameters

Query parameters are of type string, but are converted to the appropriate type when bound to a method parameter

Use annotations in the method @RequestParam , and also defaultValue set the default value when the parameter does not exist, as

public List<Spittle> spittles( @RequestParam(value="max",defaultValue=MAX_LONG_AS_STRING) long max,@RequestParam(value="count",defaultValue="20") int count )// 不设置默认值时public List<Spittle> spittles( @RequestParam("max") long max,@RequestParam("count") int count )
2.2 Processing Path parameter accept input
    1. @RequestMappingadd placeholders (enclosed in {}) to the variables section, for example @RequestMapping(value="/{spittleId}") , to handle requests for "/spittles/123454".
    2. Add annotations on the method parameters @PathVariable("spittleId") , such aspublic String spittle(@PathVariable("spittleId") long spittleId, Model model)
    3. If the method parameter name is the same as the placeholder name (both Spittleid), the Value property can be removed @PathVariable :public String spittle(@PathVariable long spittleId, Model model)

      In this case, if you modify the parameter name, you need to modify the placeholder name synchronously

2.3 Working with Forms

Use the HTML <form> tag.

If the form's view is rendered in the form of a return view name, there can be no action property in the form. At this point, it will be submitted to the URL path that is the same as the presentation. For example, to access "/register" to get a view with a form “/registerForm” , the submission form will be submitted to "/register"

When you process a form submission, the corresponding method parameter can use an object that contains a property with the same name as the request parameter (that is, the object property has the same name as the name of input in the form.) If the Spitter object has attribute username, the name in the form field needs to be username)
If you need to validate the parameters, you can use spring support for the Java Validation API. The annotation is used for the parameter, @Valid and the errors parameter is followed immediately to handle the error.
The specific validation rules are set in the Parameter object, such as

publicclass Spitter{    @NotNull   //所有的注解位于 javax.validation.constraints 包中    @Size(min=5,max=16)    private String username;//非空,5-16个字符}

The

publicprocessRegistration(@Valid Spitter spitter, Errors errs){   if(errs.hasErrors){       return"registerForm";//如果校验失败,重新返回表单,避免重复提交   }}
3. Supplemental Content

This part is not "Spring combat" content

3.1 Ajax/json Input

http://blog.csdn.net/oTengYue/article/details/51598277
Requested data is in the body of request Content-Type application/json

    • Cannot use String xxx form
    • Cannot be used@RequestParam

@RequestBodyAnnotation for parameter passing

@RequestMapping"buAuth/save1")@ResponseBodypublicsave1(@RequestBody BuAuth buAuth){    return"SUCCESS";}

Using @RequestBody the callout parameter, the SPRINGMVC framework can automatically complete the JSON string to the corresponding bean and inject into the method parameters, mainly by using HandlerAdapter the configuration HttpMessageConverters to parse the post data body, and then bind to the corresponding bean. The data value sent by Ajax must be a JSON string, and if the controller needs to map to a custom bean object, the Ajax contenttype must be set to application/json (or application/xml ). The complete example of this approach is as follows:

$.Ajax({    type: "POST",    URL: "$! {_INDEX}/BUAUTH/SAVE1 ",    Data:JSON.stringify(dataobj),//Pass parameter must be a JSON string    ContentType: "Application/json; Charset=utf-8 ",//must declare contenttype to be Application/json, otherwise the background use @requestbody annotation cannot parse the parameter    DataType: "JSON",    Success: function(Response,Info{}});
@RequestMapping"buAuth/save1")@ResponseBodypublicsave1(@RequestBody BuAuth buAuth){    return"SUCCESS";}

Note: (1) At this time the front-end direct use $.post()直接请求会有问题,ContentType默认是application/x-www-form-urlencoded . Need to use $.ajaxSetup() labeled ContentType below application/json (or application/xml ).

$.ajaxSetup({ContentType:" application/json"});$.post("$!{_index}/buAuth/save",{buAuth:JSON.stringify(dataObj),menuIds:menu_ids},function(result){});

(2) You can use @ResponseBody the pass-through array, as an example (as a direct reference to other blog examples)

varSavedataary=[];varData1={"UserName":"Test","Address":"GZ"};varData2={"UserName":"Ququ","Address":"GR"};savedataary.Push(DATA1);savedataary.Push(DATA2);$.Ajax({    type:"POST",    URL:"User/saveuser",    DataType:"JSON",    ContentType:"Application/json",    Data:JSON.stringify(SaveData),    Success:function(data){ }});
@RequestMapping"saveUser", method = {RequestMethod.POST@ResponseBody  publicvoidsaveUser(@RequestBody List<User> users) {     userService.batchSave(users); }

(3) The same method in the controller can only be @ResponseBody marked with one parameter. This means that you cannot pass multiple objects directly through this method, but you can indirectly achieve the effect of passing multiple objects by setting an intermediate Pojo object (setting different properties). Examples are as follows:

varBuauthpage= {    Buauth:Data,    Menuinfo: {Code:" the"}};$.Ajax({    type: "POST",    URL: "$! {_INDEX}/BUAUTH/SAVE5 ",    Data: JSON.stringify(Buauthpage),    ContentType: "Application/json; Charset=utf-8 ",    DataType: "JSON",    Success: function(data){    }});
 Public classbuauthpage {Buauth Buauth; PublicBuauthGetbuauth() {returnBuauth; } Public void Setbuauth(Buauth Buauth) { This.Buauth= Buauth; } PublicMenuinfoGetmenuinfo() {returnMenuinfo; } Public void Setmenuinfo(Menuinfo menuinfo) { This.Menuinfo= Menuinfo; }}@RequestMapping(Value ="Buauth/save5")@ResponseBody PublicStringSave5(@RequestBodyBuauthpage buauthpage) {return "SUCCESS";}

(4) Axios The default request data type isapplication/json

3.2 Multipart parameter 3.3 Receive header data

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-mvc-request-header/
Sometimes, the data in the request header needs to be received and processed, and @RequestHeader annotations (Controller method parameters) are used at this time

Several forms:

    • @RequestHeader("User-Agent") String userAgent@RequestHeader("If-Modified-Since") Date date
    • @RequestHeader(value="User-Agent", defaultValue="foo") String userAgent
    • @RequestHeader HttpHeaders headers
    • @RequestHeader Map<String, String> header

can also be used HttpServletRequest ,request.getHeader("code")

Request parameters accepted by Spring MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.