Spring mvc common annotation tags

@Controller

In SpringMVC, the controller Controller is responsible for processing the requests distributed by DispatcherServlet. It encapsulates the data requested by the user into a Model after being processed by the business processing layer, and then returns the Model to the corresponding View for display.

SpringMVC provides a very easy way to define Controller, you don't need to inherit a specific class or implement a specific interface, just use @Controller to mark a class as Controller, and then use some annotations such as @RequestMapping and @RequestParam to define The mapping between URL requests and Controller methods, so that the Controller can be accessed by the outside world.

In addition, the Controller does not directly depend on HttpServlet objects such as HttpServletRequest and HttpServletResponse, which can be flexibly obtained through the method parameters of the Controller.

@Controller is used to mark a class, and the class marked with it is a SpringMVC Controller object. The dispatch handler will scan the methods of the annotated class and detect if the method is annotated with @RequestMapping.

@Controller just defines a controller class, and the method annotated with @RequestMapping is the processor that actually handles the request. Just using the @Controller tag on a class doesn't really mean it's a SpringMVC controller class, because Spring doesn't know it yet.

So how to do Spring to recognize it? At this time, we need to hand over this controller class to Spring to manage. There are two ways:

  • Define the MyController bean object in the SpringMVC configuration file.

  • In the SpringMVC configuration file tell Spring where to find the Controller controller marked as @Controller.

<!--方式一-->
<bean class="com.host.app.web.controller.MyController"/>
<!--方式二-->
< context:component-scan base-package = "com.host.app.web" /><!--路径写到controller的上一层(扫描包详解见下面浅析)-->

@RequestMapping

RequestMapping is an annotation for processing request address mapping, which can be used on classes or methods. Used on a class, indicating that all methods in the class that respond to requests use this address as the parent path.

The RequestMapping annotation has six attributes. Let's divide it into three categories for description (there are corresponding examples below).

value, method;

value: specifies the actual address of the request, the specified address can be in URI Template mode (will be explained later);

method: specifies the method type of the request, GET, POST, PUT, DELETE, etc.;

consumes,produces

consumes: Specify the submitted content type (Content-Type) of the processing request, such as application/json, text/html;

produces: specifies the returned content type, which is only returned when the (Accept) type in the request header contains the specified type;

params,headers

params: Specifies that the request must contain certain parameter values ​​for this method to process.

headers: The specified request must contain certain specified header values ​​in order for this method to process the request.

@Resource和@Autowired

Both @Resource and @Autowired are used for bean injection. In fact, @Resource is not a Spring annotation. Its package is javax.annotation.Resource, which needs to be imported, but Spring supports the injection of this annotation.

common ground

Both can be written on fields and setter methods. If both are written on the field, then there is no need to write the setter method.

difference

  • @Autowired

@Autowired is the annotation provided by Spring, which needs to import the package org.springframework.beans.factory.annotation.Autowired; it is only injected according to byType.

public class TestServiceImpl {
    // 下面两种@Autowired只要使用一种即可
    @Autowired
    private UserDao userDao; // 用于字段上

    @Autowired
    public void setUserDao(UserDao userDao) { // 用于属性的方法上
        this.userDao = userDao;
    }
}

The @Autowired annotation is to assemble the dependent object according to the type (byType). By default, it requires that the dependent object must exist. If null values ​​are allowed, you can set its required property to false. If we want to use assembly by name (byName), we can use it in conjunction with the @Qualifier annotation. as follows:

public class TestServiceImpl {
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao; 
}
  • @Resource

@Resource is automatically injected according to ByName by default, provided by J2EE, and the package javax.annotation.Resource needs to be imported. @Resource has two important attributes: name and type, and Spring resolves the name attribute of the @Resource annotation to the name of the bean, and the type attribute resolves to the type of the bean. Therefore, if the name attribute is used, the automatic injection strategy of byName is used, and the automatic injection strategy of byType is used when the type attribute is used. If neither the name nor the type attribute is specified, the strategy will be automatically injected using byName through the reflection mechanism.

public class TestServiceImpl {
    // 下面两种@Resource只要使用一种即可
    @Resource(name="userDao")
    private UserDao userDao; // 用于字段上

    @Resource(name="userDao")
    public void setUserDao(UserDao userDao) { // 用于属性的setter方法上
        this.userDao = userDao;
    }
}

Note: It is best to put @Resource on the setter method, because this is more in line with the object-oriented idea, and operate attributes through set and get instead of directly operating attributes.

@Resource assembly order:

① If both name and type are specified, the only matching bean will be found from the Spring context for assembly, and an exception will be thrown if not found.

② If name is specified, the bean with the matching name (id) will be searched from the context for assembly, and an exception will be thrown if it is not found.

③ If type is specified, it will find a similar matching unique bean from the context for assembly. If it is not found or find more than one, an exception will be thrown.

④ If neither name nor type is specified, it will be assembled automatically according to the byName method; if there is no match, it will fall back to a primitive type for matching, and if it matches, it will be automatically assembled.

The role of @Resource is equivalent to @Autowired, except that @Autowired is automatically injected according to byType.

@ModelAttribute和 @SessionAttributes

@ModelAttribute: Before all methods of the Controller are called, this @ModelAttribute method is executed first, which can be used in annotations and method parameters. This @ModelAttribute feature can be applied to BaseController, and all Controllers inherit BaseController, which can be implemented in the call Controller, execute the @ModelAttribute method first.

@SessionAttributes: Put the value in the session scope and write it on the class.

PathVariable

It is used to map the template variables in the request URL to the parameters of the function processing method, that is, take the variables in the uri template as parameters. Such as:

@Controller  
public class TestController {  
     @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)  
     public String getLogin(@PathVariable("userId") String userId,  
         @PathVariable("roleId") String roleId){  
         System.out.println("User Id : " + userId);  
         System.out.println("Role Id : " + roleId);  
         return "hello";  
     }  
     @RequestMapping(value="/product/{productId}",method = RequestMethod.GET)  
     public String getProduct(@PathVariable("productId") String productId){  
           System.out.println("Product Id : " + productId);  
           return "hello";  
     }  
     @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",  
           method = RequestMethod.GET)  
     public String getRegExp(@PathVariable("regexp1") String regexp1){  
           System.out.println("URI Part 1 : " + regexp1);  
           return "hello";  
     }  
}

@requestParam

@requestParam is mainly used to obtain parameters in the SpringMVC background control layer, similar to request.getParameter("name"), which has three common parameters: defaultValue = "0", required = false, value = "isApp"; defaultValue means Set the default value, the required copper and boolean set whether it is a parameter that must be passed in, and the value value indicates the accepted incoming parameter type.

@ResponseBody

Function: This annotation is used to convert the object returned by the Controller method into the specified format through the appropriate HttpMessageConverter, and then write it to the body data area of ​​the Response object.

Timing of use: When the returned data is not a page of HTML tags, but data in some other format (such as json, xml, etc.);

@Component

Equivalent to a generic annotation, used when it is not known to which layer some classes belong, but not recommended.

@Repository

Used to annotate the dao layer, annotated on the daoImpl class.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325949744&siteId=291194637