Go SPRINGMVC controller Introduction and common annotations

Source: Internet
Author: User

First, Introduction

In SPRINGMVC, controller controllers are responsible for processing requests distributed by Dispatcherservlet, which encapsulates the data requested by the user into a model after processing it through the business processing layer, and then returns the model to the corresponding view for presentation. A very simple way to define a controller is provided in SPRINGMVC, where you do not need to inherit a particular class or implement a specific interface, just use @controller to mark a class as a controller and then use the @requestmapping And @requestparam some annotations are used to define the mapping between URL requests and Controller methods, so that the controller can be accessed by outsiders. In addition, the controller does not directly depend on HttpServlet objects such as HttpServletRequest and HttpServletResponse, which can be obtained flexibly through the controller's method parameters. To first make a preliminary impression on the controller, the following defines a simple controller:

Example 1:

@Controllerpublic class Mycontroller {    @RequestMapping ("/showview") public    Modelandview ShowView () {       Modelandview Modelandview = new Modelandview ();       Modelandview.setviewname ("ViewName");       Modelandview.addobject ("attribute name to be placed in model", "corresponding property value, it is an object");       return modelandview;    

In the example above, the @Controller is labeled above the class Mycontroller, so class Mycontroller is a Springmvc Controller object and then uses @requestmapping ("/ ShowView ") is marked on the Controller method, indicating that the ShowView method of Mycontroller is accessed when the request is/showview.do, and that the method returns a Modelandview object that includes the model and view. These will be described in detail later.

Second, use @Controller to define a controller

Example 1 shows that @controller is used to mark a class, and the class that is tagged with it is a Springmvc Controller object. The distribution processor scans the method of the class that used the annotation and detects whether the method uses @requestmapping annotations. The @Controller just defines a controller class, and the method that uses the @requestmapping annotation is the processor that really handles the request, as the next step.

Simply using the @controller tag on a class does not really mean that it is a controller class for SPRINGMVC, because this time spring does not 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.

This time there are two ways to give mycontroller to spring management so that it can identify our tagged @controller.

The first approach is to define Mycontroller bean objects in the SPRINGMVC configuration file.

<bean class= "Com.host.app.web.controller.MyController"/>

The second way is to tell spring where to look for controller controllers 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 marks a class that does not scan @Service annotations

Third, use the @RequestMapping to map request requests and processors

Example 1 can use @requestmapping to map a URL to a controller class, or to a handler controller's method. When @requestmapping is marked on the controller class, the request address of the method that uses the @requestmapping tag is relative to the @requestmapping on the class; when the controller @requestmapping annotations are not marked on a class, the @requestmapping on the method are absolute paths. The final path of this combination of absolute and relative paths is relative to the root path "/".

In this controller, because Mycontroller is not marked by @requestmapping, it is the absolute path used when it is necessary to access the ShowView method that uses the @requestmapping tag inside/showview.do The request will be ready.

Example 2

@Controller"/test")public class Mycontroller {    @RequestMapping ("/showview")    public Modelandview ShowView () {       Modelandview Modelandview = new Modelandview ();       Modelandview.setviewname ("ViewName");       Modelandview.addobject ("attribute name to be placed in model", "corresponding property value, it is an object");       return modelandview;    

Example 2 is a @requestmapping annotation on the controller, so when you need to access the method that uses the @requestmapping tag inside ShowView (), you need to use the ShowView method @requestmapping The/test/showview.do is relative to the @requestmapping address on the controller mycontroller.

(i) Using URI templates

The URI template is given a variable in the URI, and then dynamically assigns a value to the variable at the time of the 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/ index.html, the URL matches the template, but replaces the variable1 in the template with Hello. In Springmvc, the values of variables defined in this substitution template can also be used by the processor method, so that we can easily implement the RestFul style of the URL. This variable is marked with @pathvariable in SPRINGMVC. In Springmvc, we can use @pathvariable to tag a controller's processing parameters, indicating 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 {    @RequestMapping ("/showview/{ VARIABLE2} ") Public    Modelandview ShowView (@PathVariable String variable1, @PathVariable (" variable2 ") int variable 2) {       Modelandview Modelandview = new Modelandview ();       Modelandview.setviewname ("ViewName");       Modelandview.addobject ("attribute name to be placed in model", "corresponding property value, it is an object");       return modelandview;    

In the code in Example 3 we define two URI variables, one is VARIABLE1 on the controller class, one is the variable2 on the ShowView method, and then it is used in the parameters of the ShowView method @PathVariable The tags use these two variables. So when we use/test/hello/showview/2.do to request, we can access to the Mycontroller ShowView method, this time variable1 is given the value of Hello, Variable2 is given a value of 2, We then annotated the parameters in the ShowView method parameter Variable1 and variable2 are the path variables from the access path, so that the method parameters Variable1 and variable2 are given Hello and 2 respectively. The method parameter variable1 is defined as a string type, and variable2 is defined as an int type, which, like this simple type, is automatically converted when it is assigned, and about how the complex type will be transformed in subsequent content.

In the above code we can see that we are using @pathvariable when we mark variable1 as the path variable, and we use @pathvariable ("Variable2") when we mark Variable2. What is the difference between the two? In the first case, a variable with the same parameter name is found by default in the URI template, but this is only possible when compiling with debug mode, whereas the second case is explicitly defined as the variable2 variable in the URI template. When you are not compiling using 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 URI templates in the request path, defining variables,the wildcard character "*" is also supported in @RequestMapping. I can use/mytest/whatever/wildcard.do to access the controller's Testwildcard method, as in the following code.

@Controller @requestmapping ("/mytest") public class Mycontroller {    @RequestMapping ("*/wildcard")    public String Testwildcard () {       System. Out. println ("wildcard------------");       return "wildcard";    }  

(ii) using the @RequestParam bind httpservletrequest request parameters to the 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 from HttpServletRequest to bind the parameter name to the controller method parameter name, bind the parameter age to the controller method parameter age. It is important to note that, as with @pathvariable, when you do not explicitly specify which parameter to take from request, Spring will default to the parameter with the same name as the method parameter if the code is debug, and if it is not debug, it will be an error. In addition, when the parameter names of the parameters and methods that need to be bound from the request are not the same, you need to explicitly indicate in @Requestparam which parameter to bind. In the above code, if I visit/requestparam.do?name=hello&age=1, Spring will assign the value Hello of the request parameter name to the corresponding processing method parameter name, and the value of the age of the parameter 1 Assigns the corresponding processing method parameter to age.

In addition to the property value that specifies which parameter is bound in @Requestparam , there is also an attribute required that indicates whether the specified parameter must exist in the request property, which is true by default, indicating that it must exist. An error occurs when it does not exist. In the above code we specified the parameter name of the required property is false, and did not specify the required property of age, at this time if we access/requestparam.do without passing arguments, the system will throw an exception, because the The parameter must exist and we do not specify it. And if we visit/requestparam.do?age=1, we can access it normally, because we pass the required parameter age, and the parameter name is non-mandatory and not transitive.

(iii) Use the value of the @CookieValue bound 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. There are two parameters bound above, one is explicitly specified to be bound is the value of the cookie named Hello, one is not specified. Rules that use no specified form are the same as the rules for @pathvariable, @requestparam , which automatically gets the cookie value with the same name as the method parameter name 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. println (hostaddr + "-----" + Host + "-----" + hos    T); return "Requestheader";} 

In the above code we used the @requestheader binding the HttpServletRequest request header host to the controller's method parameters. The three parameters of the above method will be given the same value, so we can know the rules and @pathvariable , @Requestparam , and @ cookievalue when binding the request header parameter to the method parameter. is the same, that is, when you do not specify which parameter to bind to the method parameter, the method parameter name is used in debug compilation mode as the parameter that needs to be bound. But there is a point @Requestheader is not the same as the other three ways of binding, that is, when using @Requestheader is case insensitive, that is @RequestHeader ("Host") and @ Requestheader ("host") is bound to the host header information. Remember that at @pathvariable , @Requestparam , and @Cookievalue are case-sensitive.

(v) Some of the advanced applications of @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 scope of the requested mapping.

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 above code we specify three parameters with the params property of the @requestmapping, which are for the request parameters, which indicate that the value of the parameter param1 must be equal to value1, the parameter param2 must exist, the value does not matter, The parameter param3 must not exist and can be accessed only if the request is/testparams.do and satisfies the specified three parameter criteria. So when the request/testparams.do?param1=value1&param2=value2 is able to correctly access the Testparams method, when the request/testparams.do?param1=value1 It is not possible to access the method normally when &param2=value2&param3=value3, because the parameter param3 specified in the params parameter of @requestmapping cannot exist.

2.method Properties

Example 8

    @RequestMapping (value= "TestMethod", Method={requestmethod. GET, Requestmethod. DELETE}) Public    String TestMethod () {       return ' method ';    

Using the method parameter in the preceding code restricts access to the controller's TestMethod method when the/testmethod.do is requested by a get or delete method.

3.headers Properties

Example 9

    @RequestMapping (value= "Testheaders", headers={"Host=localhost", "Accept"}) public    String testheaders () {       re Turn "headers";    

The usage and functionality of the Headers property is similar to the params property. In the above code, when requesting/testheaders.do, the Testheaders method can be accessed correctly only if the request header contains the accept message and the requested host is localhost.

(vi) The method parameters and return type 1 supported by the processor method labeled @RequestMapping. Supported method parameter types

(1) HttpServlet objects, mainly including HttpServletRequest, HttpServletResponse and HttpSession objects. These parameters spring will automatically assign values when invoking the processor method, so when it is necessary to use these objects in a processor method, you can simply give a declaration of a method parameter on the method and then use it directly in the method body. One thing to note, however, is that when you use the HttpSession object, there is a problem if the HttpSession object is not set up at this time.

(2) Spring's own WebRequest object. use this object to access the property values that are stored in httpservletrequest and httpsession.

(3) InputStream, OutputStream, Reader and writer. InputStream and reader are for httpservletrequest, can take data from the inside, OutputStream and writer is for HttpServletResponse, can write data inside.

(4) parameters using @pathvariable, @RequestParam, @CookieValue, and @requestheader tags.

(5) Use the parameters of the @modelattribute tag.

(6) Java.util.Map, Spring-encapsulated model and MODELMAP. These can be used to encapsulate the model data to show the view.

(7) Entity class. can be used to receive the uploaded parameters.

(8) Spring-encapsulated Multipartfile. to receive the upload file.

(9) Spring encapsulated errors and Bindingresult objects. these two object parameters must be immediately followed by the entity object parameter that requires validation, which contains the validation results for the entity object.

2. Supported return types

(1) A Modelandview object that contains the model and view.

(2) A model object, which mainly includes spring-encapsulated model and Modelmap, and Java.util.Map, when no view is returned, the view name is determined by Requesttoviewnametranslator.

(3) A View object. At this point, if the model is in the process of rendering the view, you can define a model parameter for the processor method, and then add values to the model in the method body.

(4) A string literal. This is often represented by a view name. At this point, if you need a model in the process of rendering the view, you can give the processor method a model parameter, and then add the value to the model in the method body.

(5) The return value is void. This is generally the case when we write the return results directly into the httpservletresponse, and if not, spring will use Requesttoviewnametranslator to return a corresponding view name. If a model is required in the view, the processing method is the same as the return string.

(6) If the processor method is annotated with the @responsebody tag, then any return type of the processor method will be written to HttpServletResponse after the httpmessageconverters conversion, Instead of being treated as a view or a model, as in the case above.

(7) Any return type other than the above is treated as a property in the model, and the returned view is determined by the requesttoviewnametranslator. The name of the property added to the model can be defined with @modelattribute ("AttributeName") on the method, otherwise it will be represented by the first letter lowercase of the class name of the return type. Methods that use the @modelattribute tag are executed before the @requestmapping-tagged method executes.

(vii) Transfer and storage of data using @ModelAttribute and @SessionAttributes

SPRINGMVC supports the use of @Modelattribute and @sessionattributes to share data between different models and controllers. @ModelAttribute are mainly used in two ways, one is labeled on the method, and one is labeled on the Controller method parameter.

When @Modelattribute is marked on the method, the method executes before the processor method executes, and then stores the returned object in the session or model property, and the property name can be used @Modelattribute( "AttributeName") is specified when the method is marked and, if unspecified, uses the class name of the return type (lowercase first letter) as the property name. About @ModelAttribute tags in the method when the corresponding property is stored in the session or stored in the model, let's do an experiment, look at the following section of code.

@Controller @requestmapping ("/mytest") public class Mycontroller {@ModelAttribute ("Hello"), public String Getmod       El () {System. println ("-------------Hello---------");    return "World"; } @ModelAttribute ("Intvalue") public int Getinteger () {System. println ("-------------intvalue-------       --------" );    return 10; } @RequestMapping ("SayHello") public void SayHello (@ModelAttribute ("Hello") String Hello, @ModelAttribute ("       Intvalue ") int num, @ModelAttribute (" user2 ") user user, writer writer, HttpSession session) throws IOException {       Writer.write ("Hello" + Hello + ", hello" + user.getusername () + num);       Writer.write ("\ r");       Enumeration enume = Session.getattributenames ();    while (Enume.hasmoreelements ()) Writer.write (enume.nextelement () + "\ r");        } @ModelAttribute ("User2") public User GetUser () {System. println ("---------getUser-------------"); RetuRN New User (3, "user2");  }}

When we request/mytest/sayhello.do, the method of using @ModelAttribute tag is executed first, and then the objects they return are stored in the model. When the final access to the SayHello method is reached, the method parameters using the @ModelAttribute tag can be injected with the correct value. The execution results are as follows:

Hello World,hello user210

We can see from the execution result that there are no attributes in the session, which means that the objects above are stored in the model properties, not in the session properties. How do you store it in the session properties? This time we introduce a new concept @SessionAttributes, its usage will be introduced after the @ModelAttribute, here we will first use. We add @SessionAttributes attribute on the Mycontroller class to mark which ones need to be stored in the session. Look at the following code:

@Controller @requestmapping ("/mytest") @SessionAttributes (value={"Intvalue", "StringValue"}, Types={user. class}) Pu Blic class Mycontroller {@ModelAttribute ("hello") public String Getmodel () {System. println ("------       -------Hello---------");    return "World"; } @ModelAttribute ("Intvalue") public int Getinteger () {System. println ("-------------intvalue-------       --------" );    return 10; } @RequestMapping ("SayHello") public void SayHello (map<string, object> Map, @ModelAttribute ("Hello") String Hello, @ModelAttribute ("intvalue") int num, @ModelAttribute ("user2") user user, writer writer, httpservletreq       Uest request) throws IOException {map.put ("StringValue", "String");       Writer.write ("Hello" + Hello + ", hello" + user.getusername () + num);       Writer.write ("\ r");       HttpSession session = Request.getsession ();       Enumeration enume = Session.getattributenames (); while (enUme.hasmoreelements ()) Writer.write (enume.nextelement () + "\ r"); System.    Out. println (session);        } @ModelAttribute ("User2") public User GetUser () {System. println ("---------getUser-------------");    return new User (3, "user2");  }}

In the above code we have specified that the property is Intvalue or StringValue or the type User is placed in the session, using the above code when we visit/mytest/sayhello.do, the result is as follows:

Hello World,hello user210

Still no print out any session properties, what's going on? How do you define the objects in the model named Intvalue and the objects of type User to be stored in the session, but not actually added? Are we wrong? Of course we're not wrong, just when we first visited/mytest/sayhello.do @SessionAttributes defined the attributes that need to be stored in the session, and there are corresponding attributes in the model, but this time has not been added to the session , there will be no attributes in the session, and Spring will add the corresponding attribute in the model to the session after the processor method is executed. So when the request is a second time, the following result will appear:

Hello World,hello user210

User2

Intvalue

StringValue

When the @ModelAttribute is marked on the processor method parameter, the value representing the parameter will take the property value of the corresponding name from the model or Session, the name can be specified by @ModelAttribute ("AttributeName"), if unspecified, Use the class name of the parameter type (first letter lowercase) as the property name.

Go SPRINGMVC controller Introduction and common annotations

Related Article

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.