First, Introduction
In SPRINGMVC, the controller controller is responsible for handling requests distributed by the Dispatcherservlet, which encapsulates the user's requested data into a model after processing the transaction layer, and then returns the model to the corresponding view for presentation. A very simple way of defining Controller in SPRINGMVC is that you don't have to inherit a particular class or implement a specific interface, just use @controller to mark a class as Controller, and then use @requestmapping Some annotations, such as @requestparam, are used to define mappings between URL requests and Controller methods, and such controller can be accessed by the outside world. Furthermore, Controller will not rely directly on HttpServlet objects such as HttpServletRequest and HttpServletResponse, which can be obtained flexibly through controller method parameters. To first have an initial impression of controller, the following defines a simple controller:
Example 1:
@Controller public
class Mycontroller {
@RequestMapping ("/showview") public
Modelandview ShowView () {
Modelandview Modelandview = new Modelandview ();
Modelandview.setviewname ("ViewName");
Modelandview.addobject ("attribute name to be put in model", "corresponding attribute value, it is an object");
return modelandview;
}
In the above example, the @Controller is marked above the class Mycontroller, so the class Mycontroller is a Springmvc Controller object, and then uses @requestmapping ("/ ShowView ") is marked on the controller method, which means that when the request/showview.do is accessed by the Mycontroller ShowView method, the method returns a Modelandview object that includes model and view. These will be described in detail later.
Ii. Define a Controller controller using @Controller
As shown in Example 1, @controller is used to mark a class, and a class marked with it is a Springmvc Controller object. The distribution processor scans the method of the class that uses the annotation and detects whether the method uses a @requestmapping annotation. @Controller just defines a controller class, and the method using the @requestmapping annotation is the processor that really handles the request, which is what we'll talk about next.
Simply using the @controller tag on a class does not really mean that it is a controller class for SPRINGMVC, because spring doesn't know it yet. So how do you do spring to know it? This time we need to give this controller class to spring to manage.
There are two ways to give mycontroller to spring management, so that it can identify the @controller we are marking.
The first approach is to define the Mycontroller bean object in the SPRINGMVC configuration file.
<bean class= "Com.host.app.web.controller.MyController"/>
The second way is to tell spring where to find the Controller controller labeled @controller in the SPRINGMVC configuration file.
< Context:component-scan base-package = "Com.host.app.web.controller" >
< context:exclude-filter type = " Annotation "
expression =" Org.springframework.stereotype.Service "/>
Note:
The above context:exclude-filter labeled Class three without scanning @Service annotations , using @RequestMapping to map request requests and processors
Example 1 can use @requestmapping to map URLs to controller classes, or to the controller controller's processing method. When the @requestmapping is marked on the controller class, the request address of the method in which the @requestmapping tag is used is relative to the @requestmapping of the class; @requestmapping annotations are not marked on a class, the @requestmapping on the method is an absolute path. The final path combined by this absolute path and relative path is relative to the root path "/".
In this controller, because Mycontroller is not marked by @requestmapping, the absolute path is used when you need to access the ShowView method in which the @requestmapping tag is used/showview.do The request is OK.
Example 2
@Controller
@RequestMapping ("/test") public
class Mycontroller {
@RequestMapping ("/showview")
Public Modelandview ShowView () {
Modelandview Modelandview = new Modelandview ();
Modelandview.setviewname ("ViewName");
Modelandview.addobject ("attribute name to be put in model", "corresponding attribute value, it is an object");
return modelandview;
}
Example 2 adds a @requestmapping annotation to the controller, so you need to use the ShowView method when you need to access the method ShowView () that uses the @requestmapping tag in it @requestmapping Relative to the @requestmapping address on the controller Mycontroller, that is,/test/showview.do. (i) using a URI template
The URI template is given a variable in the URI and then dynamically assigned to the variable at the time of mapping. such as URI template http://localhost/app/{variable1}/index.html, this template contains a variable variable1, then when we request http://localhost/app/hello/ When index.html, the URL matches the template, but replaces the variable1 in the template with Hello. In Springmvc, this replaces the value of the variable defined in the template to the processor method, so that we can easily implement the restful style of the URL. This variable is marked with @pathvariable in the SPRINGMVC. In Springmvc, we can use @pathvariable to mark a controller processing parameter that indicates that the value of the parameter will be assigned using the value of the corresponding variable in the URI template.
Example 3
@Controller @RequestMapping ("/test/{variable1} ") public class Mycontroller {@Reque Stmapping ("/showview/{variable2}") Public Modelandview ShowView (@PathVariable String variable1, @PathVariable ("V
Ariable2 ") int variable2) {Modelandview Modelandview = new Modelandview ();
Modelandview.setviewname ("ViewName");
Modelandview.addobject ("attribute name to be put in model", "corresponding attribute value, it is an object");
return modelandview; }
}
In the code for example 3 we defined two URI variables, one is VARIABLE1 on the controller class, one is the variable2 on the ShowView method, and then uses the @pathvariable tag in the parameters of the ShowView method to use the two variables. So when we use/test/hello/showview/2.do to request, we can access the Mycontroller ShowView method, when Variable1 is given a value of Hello, Variable2 is given a value of 2, Then we mark the parameters in the ShowView method parameters Variable1 and Variable2 are path variables from the access path, so that the method parameters Variable1 and variable2 are respectively given Hello and 2. The method parameter variable1 is defined as a string type, and variable2 is defined as the int type, as this simple type will help us automatically convert when it is assigned, and how the complex type is to be converted in subsequent content will be mentioned.
In the above code we can see that we are using @pathvariable when marking variable1 as the path variable, while the @pathvariable ("Variable2") is used when marking variable2. What is the difference between the two? In the first case, the default goes to the URI template to find the same variable as the parameter name, but this is only possible when compiling using the debug mode, and the second is to explicitly specify that the variable2 variable in the URI template is used. When you are not compiling with debug mode, or if you need to use a variable name that is not the same as the parameter name, use the second method to explicitly indicate which variable in the URI template is being used.
In addition to using the URI template in the request path and defining the variable, the wildcard character "*" is also supported @RequestMapping. As the following code I can use/mytest/whatever/wildcard.do to access the Testwildcard method of controller.
@Controller
@RequestMapping ("/mytest") public
class Mycontroller {
@RequestMapping ("*/wildcard")
Public String Testwildcard () {
System. Out. println ("wildcard------------");
return "wildcard";
}
(ii) using @RequestParam binding httpservletrequest Request parameters to controller method parameters
Example 4
@RequestMapping ("Requestparam") public
String Testrequestparam (@RequestParam (required=false) string name, @ Requestparam (' age ') int age) {return
"Requestparam";
In the above code, using @requestparam to bind parameters from httpservletrequest to the controller method parameter name name parameters age To the controller method parameter age . It's worth noting that, like @pathvariable , when you don't explicitly specify which argument to take from request ,,spring the parameter with the same name as the method parameter by default when the code is compiled debug . If it is not debug compiled it will be an error. In addition, when the parameter names of the parameters and methods you want to bind from request are not the same, you need to specify in the @requestparam which parameter to bind. In the above code, if I visit/requestparam.do?name=hello&age=1 , spring will request the requested parameter name the value hello Assigning the corresponding processing method parameter name , assigning the value of the parameter age 1 to the corresponding processing method parameter age .
In @requestparam, in addition to specifying the property value of which parameter is bound, there is also a property required that indicates whether the specified parameter must exist in the Request property, the default is true, that it must exist, and that an error is made when it does not exist. In the code above we specified the required property of parameter name is false without specifying the required attribute of age, which throws an exception if we visit/requestparam.do without passing arguments because the parameter must exist, and we have not specified it. And if we visit/requestparam.do?age=1, we can access it normally, because we pass the necessary argument age, and the parameter name is not required, not passed. (iii) using the value of the @CookieValue binding cookie to the Controller method parameter
Example 5
@RequestMapping ("Cookievalue") public
string Testcookievalue (@CookieValue ("Hello") string cookievalue, @CookieV Alue String Hello) {
System. Out. println (Cookievalue + "-----------" + Hello);
return "Cookievalue";
In the above code we use @cookievalue to bind the value of the cookie to the method parameter. A total of two parameters were bound above, one explicitly specifying the value of the cookie named Hello, which is not specified. A rule that uses a form that is not specified is the same as a @pathvariable, @RequestParam rule, in which a cookie value with the same name as the method parameter name is automatically obtained in debug compilation mode. (iv) Binding HttpServletRequest header information to controller method parameters using @RequestHeader annotations
Example 6
@RequestMapping ("Testrequestheader") public
string Testrequestheader (@RequestHeader ("Host") string hostaddr, @R Equestheader string host, @RequestHeader string host) {
System. Out. println (hostaddr + "-----" + Host + "-----" + Ho ST);
return "Requestheader";
In the code above we used the method parameters @RequestHeader bind the HttpServletRequest request header to the controller. The three parameters of the above method will be given the same value, so we know that the rules and @PathVariable, @RequestParam, and @CookieValue are the same when binding the request header parameter to the method parameter. That is, when you do not specify which parameter is bound to the method argument, the method parameter name is used as the parameter to bind in debug compilation mode. But one @RequestHeader is different from the other three ways of binding, which is case-insensitive when using @RequestHeader, that is, @RequestHeader ("host") and @RequestHeader ("host ") is the Host header information that is bound. Remember to be case-sensitive in @PathVariable, @RequestParam, and @CookieValue. (v) Some advanced applications of the @RequestMapping
In Requestmapping, in addition to specifying the request Path Value property, there are other properties that can be specified, such as params, method, and headers. This property can be used to narrow the mapping scope of the request. 1.params Properties
Example 7
@RequestMapping (value= "Testparams", params={"param1=value1", "param2", "!PARAM3"}) public
String Testparams () {
System. Out. println ("Test Params ....");
return "Testparams";
In the code above, we specify three parameters with the @requestmapping params property, which are all for request parameters, which indicate that the value of the parameter param1 must be equal to value1, the parameter param2 must exist, and the value does not matter. The parameter param3 must not exist and can be accessed only if the request/testparams.do and satisfies the specified three parameter conditions. So when the request is/testparams.do?param1=value1¶m2=value2, the Testparams method can be accessed correctly when the request/testparams.do?param1=value1 ¶m2=value2¶m3=value3 is not able to access the method normally, because the parameter param3 specified in the params parameter of the @requestmapping cannot exist. 2.method Properties
Example 8
@RequestMapping (value= "TestMethod", Method={requestmethod. Get, Requestmethod. DELETE})