Address mapping of @RequestMapping usage details (transfer)

Introduction:

Some time ago, the RESTful mode was used in the project to develop the program, but when the data was submitted in the POST and PUT modes, it was found that the server side could not accept the submitted data (the server-side parameter binding did not add any annotations), and checked the submission method. It is application/json, and the data sent by the server through request.getReader() does exist in the data submitted by the browser. In order to find out the reason, I researched the parameter binding (@RequestParam, @RequestBody, @RequestHeader, @PathVariable), and also looked at the relevant content of HttpMessageConverter, which is summarized here.



Introduction:

@RequestMapping

RequestMapping is an annotation for processing request address mapping, which can be used on classes or methods. Used on a class, indicating that all methods in the class that respond to requests use this address as the parent path.

The RequestMapping annotation has six attributes. Let's divide it into three categories for description.

1. value, method;

value: specify the actual address of the request, the specified address can be in URI Template mode (will be explained later);

method: specify the method type of the request, GET, POST, PUT, DELETE, etc.;



2. consumes, produces;

consumes: specifies the submitted content type (Content-Type) of the processing request, such as application/json, text/html;

produces: specifies the returned content type, only if the specified type is included in the (Accept) type in the request header only return;



3. params, headers;

params: Specifies that the request must contain certain parameter values ​​before this method can process it.

headers: The specified request must contain certain specified header values ​​in order for this method to process the request.



Example:

1. Example of value / method

Default RequestMapping("....str...") is the value of value;

copy code
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private AppointmentBook appointmentBook;
   
    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

    @RequestMapping(value="/{day}", method = RequestMethod.GET)
    public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
        return appointmentBook.getAppointmentsForDay(day);
    }

    @RequestMapping(value="/new", method = RequestMethod.GET)
    public AppointmentForm getNewForm() {
        return new AppointmentForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String add(@Valid AppointmentForm appointment, BindingResult result) {
        if (result.hasErrors()) {
            return "appointments/new";
        }
        appointmentBook.addAppointment(appointment);
        return "redirect:/appointments";
    }
} The
uri
value of value can be specified as the following three types:

A) It can be specified as a common specific value;

B) It can be specified as a type of value containing a variable (URI Template Patterns with Path Variables);

C) Can be specified as a class of values ​​with regular expressions ( URI Template Patterns with Regular Expressions);



example B)

@RequestMapping(value="/owners/{ownerId}", method= RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId); 
  model.addAttribute("owner", owner); 
  return "displayOwner";
}
example C)

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
  public void handle(@PathVariable String version, @PathVariable String extension) {   
    // ...
  }
}
2 consumes、produces 示例

cousumes的样例:

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {   
    // implementation omitted
}
方法仅处理request Content-Type为“application/json”类型的请求。

produces的样例:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {   
    // implementation omitted
}
The method only processes requests that contain "application/json" in the Accept header of the request, and implies that the returned content type is application/json;





3 params, headers Example

params example:

copy code
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

  @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params ="myParam=myValue") public void findPet(@PathVariable String ownerId, @PathVariable
  String petId, Model model) {   
    // implementation omitted
  }
} request; sample headers:









Copy code
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com /") public void findPet(@PathVariable String ownerId, @PathVariable
  String petId, Model model) {   
    // implementation omitted
  }
} //www.ifeng.com/"; the above only introduces which requests are processed by the method specified by RequestMapping. The following article will explain how to process the data submitted by the request (data binding) and the returned data. References: 1. Spring Web Doc: spring-3.1.0/docs/spring-framework-reference/html/mvc.htmlIntroduction:





















Some time ago, the RESTful mode was used in the project to develop the program, but when the data was submitted in the POST and PUT modes, it was found that the server side could not accept the submitted data (the parameter binding on the server side did not add any annotations), and the submission method was application. /json, and the data sent by the server through request.getReader() does exist in the data submitted by the browser. In order to find out the reason, I researched the parameter binding (@RequestParam, @RequestBody, @RequestHeader, @PathVariable), and also looked at the relevant content of HttpMessageConverter, which is summarized here.



Introduction:

@RequestMapping

RequestMapping is an annotation for processing request address mapping, which can be used on classes or methods. Used on a class, indicating that all methods in the class that respond to requests use this address as the parent path.

The RequestMapping annotation has six attributes. Let's divide it into three categories for description.

1. value, method;

value: specify the actual address of the request, the specified address can be in URI Template mode (will be explained later);

method: specify the method type of the request, GET, POST, PUT, DELETE, etc.;



2. consumes, produces;

consumes: specifies the submitted content type (Content-Type) of the processing request, such as application/json, text/html;

produces: specifies the returned content type, only if the specified type is included in the (Accept) type in the request header only return;



3. params, headers;

params: Specifies that the request must contain certain parameter values ​​for this method to process.

headers: The specified request must contain certain specified header values ​​in order for this method to process the request.



Example:

1. Example of value / method

Default RequestMapping("....str...") is the value of value;

copy code
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private AppointmentBook appointmentBook;
   
    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

    @RequestMapping(value="/{day}", method = RequestMethod.GET)
    public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
        return appointmentBook.getAppointmentsForDay(day);
    }

    @RequestMapping(value="/new", method = RequestMethod.GET)
    public AppointmentForm getNewForm() {
        return new AppointmentForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String add(@Valid AppointmentForm appointment, BindingResult result) {
        if (result.hasErrors()) {
            return "appointments/new";
        }
        appointmentBook.addAppointment(appointment);
        return "redirect:/appointments";
    }
} The
uri
value of value can be specified as the following three types:

A) It can be specified as a common specific value;

B) It can be specified as a type of value containing a variable (URI Template Patterns with Path Variables );

C) can be specified as a type of value with regular expressions (URI Template Patterns with Regular Expressions);



example B)

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner (@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId); 
  model.addAttribute("owner", owner); 
  return "displayOwner";
}
example C)

@RequestMapping("/spring-web/{ symbolicName:[az-]+}-{version:\d\.\d\.\d}.{extension:\.[az]}")
  public void handle(@PathVariable String version, @PathVariable String extension) {   
    // ...
  }
}
2 consumes、produces 示例

cousumes的样例:

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {   
    // implementation omitted
}
方法仅处理request Content-Type为“application/json”类型的请求。

produces的样例:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {   
    // implementation omitted
}
method only processes requests that contain "application/json" in the Accept header of the request request, and implies that the returned content type is application/json;





3 params, headers Example

of params:

Copy code
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

  @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
  public void findPet(@PathVariable String ownerId , @PathVariable String petId , Model model) {   
    // implementation omitted
  }
}











@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {   
    // implementation omitted
  }
} ifeng.com/"; the above only describes which requests are processed by the method specified by RequestMapping. The following article will explain how to process the data submitted by the request (data binding) and the returned data. References: 1. Spring Web Doc: spring-3.1.0/docs/spring-framework-reference/html/mvc.html



















Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326588905&siteId=291194637