SpringMVC Controller and its common comment

Reprinted from the article:

I. Introduction

  In SpringMVC, the distribution of Controller responsible for processing requests from the DispatcherServlet, it requests the user service data after a treatment layer. Package Model, the Model and then returned for display to the corresponding View. In SpringMVC provided in a very simple way to define the Controller, you do not need to inherit a particular class or implement a specific interface, just use @Controller mark a class is Controller, and then use @RequestMapping and @RequestParam some of the notes and so on to define URL mapping between the request and the Controller method, this Controller can be accessible to the outside world. Further Controller does not depend directly on the other and HttpServletResponse HttpServletRequet HttpServlet object.

  Example 1:

@Controller
 public  class MyController by { 

    @RequestMapping ( "/ ShowView" )
     public ModelAndView ShowView () { 
       ModelAndView ModelAndView = new new ModelAndView (); 
       modelAndView.setViewName ( "viewName" ); 
       modelAndView.addObject ( "needs to be set in the attribute name model "," corresponding to the attribute value, it is an object " );
        return ModelAndView; 
    } 

}

In the example above, @Controller  is labeled class MyController above, it is a SPRINGMVC MyController Controller class objects, and then use @RequestMapping ( "/ showView") marked on the Controller method, when the request indicates the /showView.do MyController the time of the visit is showView method returns an object ModelAndView including the Model and View. All these will be described in the following detailed.

Second, using the definition of a Controller Controller @Controller

  @Controller shown in one case for marking a class, which is a class mark SpringMVC Controller object. The processor will distribute a scanning method using the annotation class, and the method detects whether the @RequestMapping annotations. @Controller controller only defines a class, a method using real @RequestMapping annotation process requesting processor , this will be mentioned next.

    @Controller alone are marked on a class can not really say that it is SpringMVC of a controller in the sense of class, because this time the Spring do not even know it. So how do the Spring you can recognize it? This time we need to put this Spring controller class to manage.

  This time there are two ways to manage MyController to Spring, make sure it is able to recognize our mark @Controller.

     (1) The first way is to define objects in a bean MyController SpringMVC profile.

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

(2) The second way is to tell the SpringMVC Spring configuration file where to look for marked @Controller the Controller controller.

< context:component-scan base-package = "com.host.app.web.controller" >
       < context:exclude-filter type = "annotation"
           expression = "org.springframework.stereotype.Service" />
 </ context:component-scan > 

NOTE: The above context: exclude-filter was not noted in the class label scanning @Service

 

 

Third, the use @RequestMapping Request requesting processor to map

  Example 1 may be used @RequestMapping  to map a URL to the controller class, or to the processing method of the controller Controller.
   (1) when the mark on @RequestMapping Controller class, request address used inside @RequestMapping marking methods are relative terms based on @RequestMapping;
  (2) when there is no mark on the annotation @RequestMapping Controller class, the methods are @RequestMapping absolute path.
  This absolute and relative paths are combined into the final path is relative to the root path of "/" is concerned.

   Example 1 In this controller, because MyController @RequestMapping not marked, when the need to access to the inside using a labeled @RequestMapping showView method, the absolute path is used /showView.do request it.  

 Example 2

@Controller 
@RequestMapping ( "/ Test" )
 public  class MyController by { 
    @RequestMapping ( "/ ShowView" )
     public ModelAndView ShowView () { 
       ModelAndView ModelAndView = new new ModelAndView (); 
       modelAndView.setViewName ( "viewName" ); 
       modelAndView.addObject ( " attribute needs to be set in the model name "," corresponding to the attribute value, it is an object " );
        return ModelAndView; 
    } 

}

 Example 2 is added on the controller @RequestMapping annotations, so when it is necessary to access the inside ShowView @RequestMapping method using a labeled () when you need to use addresses on ShowView method @RequestMapping MyController by the controller with respect to the @RequestMapping, That /test/showView.do.

 

(A) use the URI template

  URI in the URI template is given a variable and then dynamically to the variable assignment when mapping. URI templates such as http: // localhost / app / { variable1} /index.html, this template which contains a variable variable1, then when we request http: //localhost/app/hello/index.html of time, the URL will match with the template, but the template to replace variable1 with a hello. In SpringMVC, this substitution values of the variables defined in the template may also use the method to the processor, so that we can very easily achieve the URL RestFul  style. This variable is in SpringMVC use @PathVariable  to mark. In SpringMVC, we can use the processing method to mark @PathVariable parameters of a Controller, a value representative of the parameter values used in the URI template corresponding to the variable assignment.

Example 3

@Controller 
@RequestMapping ( "/ Test / variable1 {}" )
 public  class MyController by { 

    @RequestMapping ( "/ ShowView / variable2 {}" )
     public ModelAndView ShowView (@PathVariable String variable1, @PathVariable ( "variable2") int variable2) { 
       ModelAndView ModelAndView = new new ModelAndView (); 
       modelAndView.setViewName ( "viewName" ); 
       modelAndView.addObject ( "model needs to be set in the attribute name", "corresponding to the attribute value, it is an object" );
        return ModelAndView; 
    } 
}

In Example 3, the code we define two variables URI, on a controller class is variable1, variable2 on showView is a method and parameters used in the method of showView inside @PathVariable  labeled using these two variables. So when we use /test/hello/showView/2.do to request access to showView method can MyController, this time it is given the value variable1 hello, variable2 was given a value of 2, then the method parameters which we showView labeled variable1 and variable2 parameters are variables from the path of access paths, this method parameters variable1 and variable2, respectively, was given hello and 2. Variable1 is defined as a method parameter of type String, variable2 is defined as an int type, when making an assignment like this simple type of Spring will help us automatically converted, on how to convert a complex type content will be mentioned in the follow-up .

  In the above code, we can see the path variable labeled variable1 is when we are using the @PathVariable, and when used in marking variable2 is @PathVariable ( "variable2"). Both what difference does it?

  The first case to go to the default template to find the parameter name with the same variable URI, but this is only when using the debug mode before they can be compiled, while the second case is clearly defined use is the URI template variable2 variable. When not using debug mode to compile, or variable name is required to be used with the parameter names are not the same time, we must use the second way is clear that the use of URI template which variable.

   In addition to using URI templates, define variables in addition to the request path, @ RequestMapping also supports wildcard "*" . As the following code I can use /myTest/whatever/wildcard.do access to the Controller testWildcard method.

@Controller
@RequestMapping ( "/myTest" )
public class MyController {
    @RequestMapping ( "*/wildcard" )
    public String testWildcard() {
       System. out .println( "wildcard------------" );
       return "wildcard" ;
    }  
}

(B) using the request parameters to @RequestParam binding HttpServletRequest method parameter controller

Example 4

 @RequestMapping ( "requestParam" )
   public String testRequestParam( @RequestParam(required=false) String name, @RequestParam ( "age" ) int age) {
       return "requestParam" ;
    } 

In the above code using @ RequestParam  bound HttpServletRequest parameters from the parameter name to the controller method name, age parameter to the controller binding method parameters age.

  It is noteworthy and @PathVariable like when you do not explicitly specify which parameters taken from the request, Spring is in the code will take the default parameters parameters of the same name more debug compilation method in the case of, if not the debug compiler will report an error. In addition, when the parameter name parameters and methods need to bind the request is not the same time, also need to @ RequestParam  clearly pointed out which parameters to be binding. In the above access code if i /requestParam.do?name=hello&age=1 Spring will then request the name of the hello request parameter assigned parameter name corresponding to the processing method, the values of the parameters corresponding to the age of 1 is given to a process method parameters age.

  In @ RequestParam  in addition to specifying which parameter binding property value, there are a property required, which indicates whether the parameters specified in the request attribute must be present, the default is true, meaning must exist, when there is no error. In the above code, we specify the name of the required parameters of the property is false, without specifying age of required attributes, if this time when we visit /requestParam.do without passing parameters, the system will throw an exception, because the age parameters It must exist, but we have not specified. And if, when we visit /requestParam.do?age=1 would be a normal visit, because we have to pass the parameters age, and the parameter name not be necessary, it can not pass.

Value (iii) use the cookie to bind @CookieValue method parameters Controller

Example 5

@RequestMapping ( "cookieValue" )
    public String testCookieValue( @CookieValue ( "hello" ) String cookieValue, @CookieValue String hello) {
       System. out .println(cookieValue + "-----------" + hello);
       return "cookieValue" ;
    }

In the above code we use @ CookieValue  binding on the method parameter values to a cookie. Binding total above two parameters, one is bound to explicitly specify the name for the value of the cookie hello, one is not specified. Use not specified in the form of rules and @ PathVariable , @ RequestParam  rule is the same, that will automatically acquire the parameters with the same name as the method cookie value in the debug compilation mode.

(Iv) using @RequestHeader binding annotation header information to the Controller HttpServletRequest method parameters

Example 6

@RequestMapping ( "testRequestHeader" )
public String testRequestHeader( @RequestHeader ( "Host" ) String hostAddr, @RequestHeader String Host, @RequestHeader String host ) {
    System. out .println(hostAddr + "-----" + Host + "-----" + host );
    return "requestHeader" ;
}

In the above code we use  @ RequestHeader  binding method parameters HttpServletRequest host request header to the Controller. The above methods are three parameters will be assigned the same value, so we can know when the first binding request parameters to method parameters and rules  @ PathVariable  , @ RequestParam  and  @ CookieValue  is the same, that does not specify which bind parameter to the method parameters when compiled in debug mode will use the parameter name as an argument to be bound.

  But one thing @ RequestHeader  with the other three binding is not the same, and that is in use @ RequestHeader  time is not case-sensitive, namely @RequestHeader ( "Host"), and @RequestHeader ( "host") Bind It is the Host header.                               

  Remember @ PathVariable  , @ RequestParam  and @ CookieValue  in it is case sensitive.

(E) @RequestMapping some advanced applications

  In addition to specifying a path request attribute value, there are other attributes can be specified in RequestMapping, as params, method, and headers. Such attributes may be used to narrow the mapping request.

1.params property

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 use the params @RequestMapping attribute specifies three parameters which are for purposes of request parameters, which represent the value of the parameter must be equal param1 value1, param2 parameter must be present, the value does not matter, the parameter param3 must not exist, and only when requested /testParams.do three parameters to meet specified conditions to access to this method. Therefore, when the access request can correctly /testParams.do?param1=value1¶m2=value2 testParams to the method, when the request is not able /testParams.do?param1=value1¶m2=value2¶m3=value3 normal access to this method, the in the params parameter specifies parameters @RequestMapping inside param3 it can not exist.

~ Back to see even more of the original bloggers where there is a complete oh

Guess you like

Origin www.cnblogs.com/doyi111/p/11877798.html