In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What this article shares with you is about the functions and attributes of SpringMVC commonly used annotations. The editor feels that it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
1.@RequestMapping annotations function of 1.1@RequestMapping annotations
As we can see from the annotation name, the purpose of the @ RequestMapping annotation is to associate the request with the controller method that handles the request to establish a mapping relationship.
When SpringMVC receives the specified request, it will find the corresponding controller method in the mapping relationship to process the request.
Location of 1.2@RequestMapping comments
@ RequestMapping identifies a class: sets the initial information for the request path of the mapping request
@ RequestMapping identifies a method: set the specific information of the mapping request request path
@ Controller@RequestMapping ("/ test") public class RequestMappingController {/ / the request path mapped by the request map at this time is / test/testRequestMapping @ RequestMapping ("/ testRequestMapping") public String testRequestMapping () {return "success";}} the value attribute of the 1.3@RequestMapping annotation
The value attribute of the @ RequestMapping annotation matches the request mapping by the request address
The value attribute of the @ RequestMapping annotation is an array of string types, indicating that the request mapping can match requests corresponding to multiple request addresses.
The value property of the @ RequestMapping annotation must be set, at least through the request address matching request mapping
Test the value property of @ RequestMapping-- > / testRequestMapping
Test the value property of @ RequestMapping-- > / test
@ RequestMapping (value = {"/ testRequestMapping", "/ test"}) public String testRequestMapping () {return "success";} method attribute of the 1.4@RequestMapping annotation
The method attribute of the @ RequestMapping annotation matches the request mapping through the request method (get or post) of the request
The method attribute of the @ RequestMapping annotation is an array of type RequestMethod, indicating that the request mapping can match requests with multiple request modes.
If the request address of the current request satisfies the value attribute of the request map, but the request method does not satisfy the method attribute, the browser reports an error
405:Request method 'POST' not supported
Test the value property of @ RequestMapping-- > / test
@ RequestMapping (value = {"/ testRequestMapping", "/ test"}, method = {RequestMethod.GET, RequestMethod.POST}) public String testRequestMapping () {return "success";}
Note:
(1) for the controller method that handles the specified request, a derivative annotation of @ RequestMapping is provided in SpringMVC:
Mapping for handling get requests-> @ GetMapping
Mapping for handling post requests-> @ PostMapping
Mapping for handling put requests-> @ PutMapping
Mapping for handling delete requests-> @ DeleteMapping
(2) the common request method is get,post,put,delete.
But at present, browsers only support get and post. If you set a string (put or delete) for other request methods for method when the form form is submitted, it will be handled according to the default request method get.
To send put and delete requests, you need to use the filter HiddenHttpMethodFilter provided by spring.
Params attribute of 1.5@RequestMapping annotations (understand)
The params attribute of the @ RequestMapping annotation matches the request mapping through the request parameters of the request
The params attribute of the @ RequestMapping annotation is an array of string types, and you can set the matching relationship between request parameters and request mapping through four expressions.
"param": requires that the request matched by the request map must carry param request parameters
"! param": requests matched by request mappings must not carry param request parameters
"param=value": requires that the request matched by the request map must carry param request parameters and param=value
"paramorphic required value": requires that the request matched by the request map must carry the param request parameter but the paramedical required value
Test the params property of @ RequestMapping-- > / test
@ RequestMapping (value = {"/ testRequestMapping", "/ test"}, method = {RequestMethod.GET, RequestMethod.POST}, params = {"username", "passwordkeeper" 123456 "}) public String testRequestMapping () {return" success ";}
Note:
If the current request satisfies the value and method attributes of the @ RequestMapping annotation, but not the params attribute, the page will report an error
400:Parameter conditions "username, passwordkeeper 123456" not met for actual request parameters: username= {admin}, password= {123456}
Headers attribute of 1.6@RequestMapping annotations (understand)
The headers attribute of the @ RequestMapping annotation matches the request mapping through the request header information
The headers attribute of the @ RequestMapping annotation is an array of string types. You can set the matching relationship between request header information and request mapping through four expressions.
"header": requests matched by request mapping must carry header request header information
"! header": requests matched by request mapping must not carry header request header information
"header=value": requests matched by request mapping must carry header request header information and header=value
"headermapped value": requires that the request matched by the request map must carry the header request header information and the headerqualified value
Note:
If the current request satisfies the value and method attributes of the @ RequestMapping annotation, but not the headers attribute, the page displays a 404 error, that is, the resource was not found.
1.7SpringMVC supports placeholders in paths (@ PathVariable) (emphasis)
Original method: / deleteUser?id=1
Rest mode: / deleteUser/1
The placeholder in the SpringMVC path is often used in the RESTful style. When some data is transferred to the server through the path in the request path, the transferred data can be represented by the placeholder {xxx} in the value attribute of the corresponding @ RequestMapping annotation, and the data represented by the placeholder can be assigned to the formal parameter of the controller method through the = = @ PathVariable== annotation.
Placeholder in the test path-- > / testRest
@ RequestMapping ("/ testRest/ {id} / {username}") public String testRest (@ PathVariable ("id") String id, @ PathVariable ("username") String username) {System.out.println ("id:" + id+ ", username:" + username "); return" success ";} / / the final output is-- > id:1,username:admin2.SpringMVC obtain request parameters 2.1 through ServletAPI (understand)
Take HttpServletReques as the formal parameter of the controller method, and the parameter of type HttpServletRequest represents the object that encapsulates the request message of the current request.
@ RequestMapping ("/ testParam") public String testParam (HttpServletRequest request) {String username = request.getParameter ("username"); String password = request.getParameter ("password"); System.out.println ("username:" + username+ ", password:" + password "); return" success ";} 2.2 obtain request parameters through the formal parameters of the controller method
At the parameter position of the controller method, set the parameter with the same name as the request parameter. When the browser sends the request and matches the request mapping, the request parameter will be assigned to the corresponding parameter in DispatcherServlet.
Test get request parameters-- > / testParam
@ RequestMapping ("/ testParam") public String testParam (String username, String password) {System.out.println ("username:" + username+ ", password:" + password); return "success";}
Note:
If there are multiple request parameters with the same name in the request parameters transmitted by the request, you can set a string array or a string type parameter in the parameter of the controller method to receive the request parameter.
If you use a formal parameter of a string array type, the array of this parameter contains each data.
If you use a formal parameter of type string, the value of this parameter is the result of using comma concatenation in the middle of each data.
2.3@RequestParam
@ RequestParam is to create a mapping between the request parameters and the formal parameters of the controller method
The @ RequestParam annotation has three attributes:
Value: specifies the parameter name of the request parameter assigned to the parameter
Required: sets whether this request parameter must be transferred. The default is true.
If set to true, the current request must transmit the request parameters specified by value. If the request parameters are not transmitted and the defaultValue attribute is not set, the page reports an error
400:Required String parameter 'xxx' is not present
If set to false, the current request does not have to transmit the request parameters specified by value. If there is no transmission, the value of the parameter identified by the note is null.
DefaultValue: regardless of whether the required attribute value is true or false, when the request parameter specified by value is not transmitted or the transmitted value is "", the formal parameter is assigned a value using the default value.
2.4@RequestHeader
@ RequestHeader is to create a mapping relationship between the request header information and the formal parameters of the controller method
The @ RequestHeader annotation has three attributes: value, required, and defaultValue, which is the same as @ RequestParam
2.5@CookieValue
@ CookieValue is to create a mapping relationship between * * cookie data * * and the formal parameters of the controller method
The @ CookieValue annotation has three attributes: value, required, and defaultValue, which is the same as @ RequestParam
2.6 obtain request parameters through POJO
You can set a formal parameter of the entity class type in the parameter location of the controller method. If the parameter name of the request parameter transmitted by the browser is the same as the attribute name in the entity class, then the request parameter will be assigned a value for this property.
User name:
Password:
Gender: male and female
Age:
/. / mailbox:
@ RequestMapping ("/ testpojo") public String testPOJO (User user) {System.out.println (user); return "success";} / / final result-> User {id=null, username=' Zhang San', password='123', age=23, sex=' Man, email='123@qq.com'} 3. Domain object sharing data 3.1 share data to request domain objects using ServletAPI @ RequestMapping ("/ testServletAPI") public String testServletAPI (HttpServletRequest request) {request.setAttribute ("testScope", "hello,servletAPI"); return "success";} 3.2 use ModelAndView to share data with request domain objects
ModelAndView has the functions of Model and View:
Model is mainly used to share data with the request domain.
View is mainly used to set the view and realize page jump.
@ RequestMapping ("/ testModelAndView") public ModelAndView testModelAndView () {/ * ModelAndView has the functions of Model and View * Model is mainly used to share data to the request domain * View is mainly used to set the view and realize page jump * / ModelAndView mav = new ModelAndView (); / / share data mav.addObject ("testScope", "hello,ModelAndView") to the request domain / / set the view to enable the page to jump to mav.setViewName ("success"); return mav;} 3.3 use Model to share data @ RequestMapping ("/ testModel") public String testModel (Model model) {model.addAttribute ("testScope", "hello,Model"); return "success";}
3.4 use map to share data with request domain objects
@ RequestMapping ("/ testMap") public String testMap (Map map) {map.put ("testScope", "hello,Map"); return "success";}
3.5 use ModelMap to share data with request domain objects
@ RequestMapping ("/ testModelMap") public String testModelMap (ModelMap modelMap) {modelMap.addAttribute ("testScope", "hello,ModelMap"); return "success";}
The relationship among 3.6Model, ModelMap and Map
The parameters of type Model, ModelMap and Map are essentially of type BindingAwareModelMap.
Public interface Model {} public class ModelMap extends LinkedHashMap {} public class ExtendedModelMap extends ModelMap implements Model {} public class BindingAwareModelMap extends ExtendedModelMap {}
3.7 share data to session domain
@ RequestMapping ("/ testSession") public String testSession (HttpSession session) {session.setAttribute ("testSessionScope", "hello,session"); return "success";}
3.8 share data with the application domain
@ RequestMapping ("/ testApplication") public String testApplication (HttpSession session) {ServletContext application = session.getServletContext (); application.setAttribute ("testApplicationScope", "hello,application"); return "success";} 4.HttpMessageConverter
HttpMessageConverter: message information converter that converts a request message into a Java object or a Java object into a response message
HttpMessageConverter provides two annotations and two types: @ RequestBody,@ResponseBody,RequestEntity,ResponseEntity
4.1@RequestBody
@ RequestBody can get the request body. You need to set a parameter in the controller method and use @ RequestBody to identify it. The request body of the current request will assign a value to the parameter identified by the current annotation.
User name:
Password:
@ RequestMapping ("/ testRequestBody") public String testRequestBody (@ RequestBody String requestBody) {System.out.println ("requestBody:" + requestBody); return "success";} / * output result: requestBody:username=admin&password=123456*/4.2RequestEntity
RequestEntity encapsulates a type of request message, which needs to be set in the parameter of the controller method. The request message of the current request will be assigned to the parameter. The request header information can be obtained by getHeaders (), and the request body information can be obtained by getBody ().
@ RequestMapping ("/ testRequestEntity") public String testRequestEntity (RequestEntity requestEntity) {System.out.println ("requestHeader:" + requestEntity.getHeaders ()); System.out.println ("requestBody:" + requestEntity.getBody ()); return "success";}
Output result:
RequestHeader: [host: "localhost:8080", connection: "keep-alive", content-length: "27", cache-control: "max-age=0", sec-ch-ua: "Not AtterBrand"; v = "99", "Chromium"; v = "90", "Google Chrome"; v = "90", sec-ch-ua-mobile: "0", upgrade-insecure-requests: "1", origin: "http://localhost:8080", user-agent:" Mozilla/5.0 (Windows NT 10.0; Win64) X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 "] requestBody:username=admin&password=1234.3@ResponseBody
@ ResponseBody is used to identify a controller method, and the return value of this method can be directly responded to the browser as the response body of the response message.
@ RequestMapping ("/ testResponseBody") @ ResponseBodypublic String testResponseBody () {return "success";}
Result: the browser page displays success
4.4@RestController
The @ RestController annotation is a composite annotation provided by springMVC. Marking on the class of the controller is equivalent to adding the @ Controller annotation to the class and the @ ResponseBody annotation to each of these methods.
4.5ResponseEntity
ResponseEntity is used for the return value type of the controller method, which is the response message to the browser
These are the common annotation functions and attributes of SpringMVC. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, 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.