SpringMVC basics-parameter acquisition and Servlet Resource Acquisition Problems, springmvcservlet
I. SpringMVC uses @ PathVariable, @ RequestParam, @ RequestHeader, @ CookieValue, and so on to solve the parameter acquisition problem.
1. @ PathVariable: a placeholder for ing URL binding. You can obtain the parameter values in URL ing by using the @ PathVariable annotation passed in to the method parameter list. For example:
<a href="handler01/1">test pathvariable</a>
@RequestMapping("/handler01/{id}")public String testPathVariable(@PathVariable("id") String id) { System.out.println("id:" + id); return "success";}
Note: SpringMVC supports REST by binding placeholders to URLs. The rest style examples of SpringMVC will be described in future articles.
2. @ RequestParam
The official documents are described as follows:
* Annotation which indicates that a method parameter should be bound to a web * request parameter. Supported for annotated handler methods in Servlet and * Portlet environments. * * <p>If the method parameter type is {@link Map} and a request parameter name * is specified, then the request parameter value is converted to a {@link Map} * assuming an appropriate conversion strategy is available. * * <p>If the method parameter is {@link java.util.Map Map<String, String>} or * {@link org.springframework.util.MultiValueMap MultiValueMap<String, String>} * and a parameter name is not specified, then the map parameter is populated * with all request parameter names and values. |
Note:
(1) The annotation indicates that the web request parameter is bound to the input parameter of the target handler method.
(2) If the input parameter type of the method is a Map, it does not contain the generic type, and the request parameter name is specified
(For example, public String testRequestParam5 (@ RequestParam ("userName") Map map), the request parameters are converted to a Map, provided that a conversion policy exists.
The conversion policy mentioned here usually refers to the type conversion from request parameters to Map. For example, the request parameter is userName = a | 12, B | 34, A conversion policy (type converter) is required)
To complete the conversion from a | 12, B | 34 to map. This situation is not included in the general development process. Is an extension. Type conversion will be introduced in later articles.
(3) If the input parameter of the method is a Map and the generic Map <String, String> or org. springframework. util. MultiValueMap type MultiValueMap <String, String> is specified
If no request parameter is specified, all request parameter names and values (populate) are filled in the Map-type parameter.
For example:
Request: <a href = "testRequestParam4? UserName = jack & age = 23 "> test request param4 </a>
Handler method:
@RequestMapping("/testRequestParam4")public String testRequestParam4(@RequestParam Map<String, String> map) { System.out.println("map:" + map); return "success";}
Console output:
Map: {userName = jack, age = 23}
@ RequestParam is introduced as a whole above. Let's take a closer look at its API:
It contains three attributes:
(1) value Attribute. The default value is ""
Official documentation:
The name of the request parameter to bind.
The explanation is clear and I will not go into details.
(2) The required attribute. The default value is true.
Official documentation: Whether the parameter is required.
The request parameter is required. If the parameter is not in the request, an exception is thrown. If this parameter is set to false, the corresponding value of the method input parameter is null.
In addition, the defaultValue attribute is set to false.
(3) defaultValue attribute
If no corresponding request parameter is provided or the request parameter is null, the value corresponding to this attribute is used. When this attribute is set, the required attribute is set to false.
Below are several examples of common requests:
(1) Request: <a href = "testRequestParam? UserName = abc "> test request param </a>
Handler method:
@RequestMapping("/testRequestParam")public String testRequstParam01(@RequestParam("userName") String userName) { System.out.println("userName: " + userName); return "success";}
(2) request: <a href = "testRequestParam2?UserName= Jack &UserName= Lucy "> test request param2 </a>
Handler method:
@RequestMapping("/testRequestParam2")public String testRequestParam02(@RequestParam("userName") List<String> userNames) { System.out.println("userNames:" + userNames); return "success";}
Console output:
UserNames: [jack, lucy]
(3) Request: <a href = "testRequestParam4? UserName = jack & age = 23 "> test request param4 </a>
Handler method:
@RequestMapping("/testRequestParam4")public String testRequestParam4(@RequestParam Map<String, String> map) { System.out.println("map:" + map); return "success";}
Console output:
Map: {userName = jack, age = 23}
There are three main cases: the first is the most commonly used, and the second and third are rarely thought of. If you can think of it, it can save a lot of time for us to develop.
3. @ RequestHeader
This is described in the official document:
Annotation which indicates that a method parameter should be bound to a web request header. Supported for annotated handler methods in Servlet and Portlet environments. |
Similar to the description of @ RequestParam, only the web request header information is bound to the method input parameter.
The three attributes defined are the same as @ RequestParam, and the default value and the method used are the same. Because it is rarely used, here is only an example:
Request: <a href = "testRequestHeader"> test request header </a>
Handler method:
@RequestMapping("/testRequestHeader")public String testRequestHeader(@RequestHeader(value = "Accept", required = false) String accept) { System.out.println("accept:" + accept); return "success";}
Console output:
Accept: text/html, application/xhtml + xml, application/xml; q = 0.9, image/webp, */*; q = 0.8
4. @ CookieValue
Official Document Description:
Annotation which indicates that a method parameter should be bound to an HTTP cookie. Supported for annotated handler methods in Servlet and Portlet environments. |
Bind an http cookie to the input parameter of the method. The value Attribute indicates the cookie key of the request parameter.
The default value and usage are similar to @ RequestParam.
Example:
Request: <a href = "testCookieValue"> test cookie value </a>
Handler method:
@RequestMapping("/testCookieValue")public String testCookieValue(@CookieValue(value = "JSESSIONID", required = false) String sessionId) { System.out.println("sessionId:"+sessionId); return "success";}
Console output:
SessionId: 9d16bdf7063e1bfd9a0c052f1bda-a0d
5. Bind The request parameters to the bean object of the method entry.
Let's take a look at two examples:
(1) Bind Request Parameters to bean
Request: including the submission of get and post requests.
<a href="testBean?personName=jack&age=23">test bean</a><form action="testBean" method="post"> <label> personName:<input type="text" name="personName"/> </label> <label> age:<input type="text" name="age"/> </label> <input type="submit" value="submit"/></form>
Handler method:
@RequestMapping("/testBean")public String testBean(Person person) { System.out.println(person);//Person{personName='jack', age='23'} return "success";}
It is found that the corresponding request parameters can be injected into the corresponding bean either through get or post.
(2) Bind Request Parameters to the cascading bean
Bean structure:
/*** @ Author solverpeng * @ create 2016-08-04-*/public class Employee {private String empName; private Address address Address; public String getEmpName () {return empName;} public void setEmpName (String empName) {this. empName = empName;} public Address getAddress () {return address;} public void setAddress (Address address Address) {this. address = address ;}@ Override public String toString () {return "Employee {" + "empName = '" + empName +' \ ''+ ", address = "+ address + '}';}}Employee/*** @ author solverpeng * @ create 2016-08-04-*/public class Address {private String addressName; public String getAddressName () {return addressName ;} public void setAddressName (String addressName) {this. addressName = addressName;} @ Override public String toString () {return "Address {" + "addressName = '" + addressName +' \ ''+ '}';}}Address
Requests: Include get requests and post requests.
<a href="testBeanCascade?empName=jack&address.addressName=beijing">test bean cascade</a><form action="testBeanCascade" method="post"> <label> empName:<input type="text" name="empName"/> </label> <label> Address:<input type="text" name="address.addressName"/> </label> <input type="submit" value="submit"/></form>
Handler method:
@RequestMapping("/testBeanCascade")public String testBeanCascade(Employee employee) { System.out.println(employee);//Employee{empName='jack', address=Address{addressName='beijing'}} return "success";}
How is it bound? The source code conversion process is as follows:
Org. springframework. web. servlet. mvc. annotation. AnnotationMethodHandlerAdapter # invokeHandlerMethod
ExtendedModelMap implicitModel = new BindingAwareModelMap ();
Object result = methodInvoker. invokeHandlerMethod (handlerMethod, handler, webRequest, implicitModel );
Step 1: find that the injected bean is included in the result. Therefore, injection is performed in the methodInvoker. invokeHandlerMethod () method.
Step 2: org. springframework. web. bind. annotation. support. HandlerMethodInvoker # invokeHandlerMethod
Object [] args = resolveHandlerArguments (handlerMethodToInvoke, handler, webRequest, implicitModel );
Step 3: org. springframework. web. bind. annotation. support. HandlerMethodInvoker # resolveHandlerArguments
DoBind (binder, webRequest, validate, validationHints ,! AssignBindingResult); // binding here
Step 4: org. springframework. web. bind. ServletRequestDataBinder # bind
DoBind (mpvs );
Step 5: org. springframework. validation. DataBinder # doBind
This. applyPropertyValues (mpvs );
It is found that it is bound in the doBind () method of the DataBinder class. During the source code conversion process, we found that the resolveHandlerArguments () method is worth looking at, regardless of the level,
In fact, the SpringMVC parameter is actually solved in this method.
To sum up, Spring MVC automatically matches the request parameter name and POJO attribute name and automatically fills in the attribute value for the object. Cascade attributes are supported.
Ii. SpringMVC solves the problem of Servlet Resource Acquisition
1. SpringMVC uses Servlet resources as the input parameters of the method to solve the Servlet resource acquisition problem.
2. Servlet resources that can be used as input parameters include HttpServletRequest, HttpServletResponse, HttpSession, Locale, InputStream, OutputStream, Reader, and Writer.
3. Example:
Use HttpServletRequest as the input parameter
Request: <a href = "testServletAPI"> test servlet api </a>
Handler method:
@RequestMapping("/testServletAPI")public String testServletAPI(HttpServletRequest request) { String id = request.getSession().getId(); System.out.println("sessionId:" + id); return "success";}
Console output:
SessionId: e42437af3dc276ba78539f0af5c044b
Other Servlet resources are not described here.
Iii. Summary
SpringMVC uses @ PathVariable to obtain the placeholder value in @ RequestMapping, which provides support for compiling REST-style programs. Use@ RequestParamCan receive the vast majority of request parameters, and provides the type
Convert this extension. Use @ RequestHeader to map request header information. Use @ CookieValue to map http cookie information. Model injection is also supported. You can also obtain the native servlet resources. That is, in the target method,
SpringMVC simplifies the process and makes development more convenient and flexible.