SpringMVC common annotations (notes used)

1、@Controller

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 some annotations to define @RequestMapping and @RequestParam etc. 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 HttpServletRequest and HttpServletResponse HttpServlet other objects, which may be a flexible process parameter is acquired by the Controller.

@Controller for marking on 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 processor requests. @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. There are two ways:

  (1) is defined MyController bean objects SpringMVC profile.

  (2) tells the SpringMVC Spring configuration file where to look for the mark @Controller Controller controller.

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

2、@RequestMapping

RequestMapping is a process for annotation request address mapping, it can be used for class or method. For the class, all the methods in response to the request class are represented in the address as the parent path.

RequestMapping notes six attributes, let her be divided into three categories description (below the corresponding example).

1、 value, method;

value: Specifies the physical address of the request, the address may be specified URI Template mode (will be described later);

method: method specifies the type of request, GET, POST, PUT, DELETE and the like;

2、consumes,produces

consumes: submit a request specifying process of the content type (Content-Type), for example, application / json, text / html;

produces: content type of the returned request only if the request header (the Accept) containing the specified type will return to type;

3、params,headers

params: Specifies the request must contain certain parameter values, before allowing the processing method.

headers: Specifies the request must contain certain specified header value, in order for this method to process the request.

3、@Resource和@Autowired

Use @Resource and @Autowired are injected bean do, in fact, not @Resource Spring annotations, its package is javax.annotation.Resource, you need to import, but injected into the Spring annotation support.

1, common

Both can be written in the field and setter methods. If both are written in the field, you do not need to write a setter method.

2, different points

(1)@Autowired

Spring @Autowired annotation is provided, the package need to import org.springframework.beans.factory.annotation.Autowired; only according byType injection.

public class TestServiceImpl {
    // 下面两种@Autowired只要使用一种即可
    @Autowired
    private UserDao userDao; // 用于字段上
    
    @Autowired
    public void setUserDao(UserDao userDao) { // 用于属性的方法上
        this.userDao = userDao;
    }
}

@Autowired annotation in accordance with the type (the byType) dependent objects assembled, by default it requires dependent objects must be present, if the null value is allowed, it may be required attribute set to false. If we want to use by name (byName) to assemble, can be combined @Qualifier annotation used together. as follows:

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

(2)@Resource

@Resource default automatic injector according ByName provided by the J2EE, need to import the package javax.annotation.Resource. @Resource has two important attributes: name and type, and Spring will @Resource annotation name attribute resolves to the bean's name, the type attribute is resolved to the type of bean. So, if you use the name attribute is used byName automatic injection strategy, and is used when using the type attribute byType automatic injection strategy. If the name is neither developed nor developing type attribute, then the policy will automatically injected using byName by reflection.

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 @Resource on a setter method, because it is more consistent with object-oriented thinking through the set, get to operate the property, rather than directly to the operating property.

@Resource assembly sequence:

① If you specify the name and type, from the Spring context to find a unique match of bean assembled, can not find an exception is thrown.

② If the name is specified, from the context, find the name (id) match bean assembled, can not find an exception is thrown.

③ If the type is specified, from the context find a unique bean similar matches for assembly, can not find or find more, will throw an exception.

④ If neither specified name, and no specified type, according to the automatic assembly byName manner; if there is no match, then the match is a backoff primitive type, if a match is automatically assembled.

@Resource effect equivalent to @Autowired, but @Autowired automatically injected in accordance with byType.

4、@ModelAttribute和 @SessionAttributes

Representative are: the Controller of all methods before calling, perform this @ModelAttribute method can be used for annotations and method parameters, you can put this @ModelAttribute characteristics, application in BaseController among all Controller inherit BaseController, can be realized in when calling Controller, the first implementation @ModelAttribute method.

@SessionAttributes value into the session scope is about to write in the class above.

See the following specific example: using @ModelAttribute and save data transfer and @SessionAttributes

5, @ PathVariable

Request for the URL template variable parameter is mapped to a processing method, i.e. extraction uri template variable as a parameter. 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";  
     }  
}

6、@requestParam

@requestParam primarily for acquisition parameters SpringMVC background controlling layer, a similar one is request.getParameter ( "name"), which has three common parameters: defaultValue = "0", required = false, value = "isApp"; defaultValue represents set the default value, required copper over whether it is necessary to set the boolean parameter passed in, value value indicates acceptance of an incoming parameter type.

7、@ResponseBody

Action: The Controller annotation for the object returned by the method, by an appropriate body HttpMessageConverter conversion area after a specified data format, and writes the Response object.

When to use it: return to the page data is not html tags, but some other data formats (such as json, xml, etc.);

8、@Component

Equivalent to the common comment when you do not know which layer classes return to use, but not recommended.

9、@Repository

Dao layer for the annotation, annotation daoImpl above category.

Guess you like

Origin www.cnblogs.com/xiaoquan-blog/p/12163608.html