Home > Java > JavaBase > body text

SpringMVC common annotations

Guanhui
Release: 2020-06-04 16:35:25
Original
2859 people have browsed it

SpringMVC common annotations

SpringMVC common annotations

1, @Controller

In SpringMVC, the controller Controller Responsible for processing 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 simple way to define a Controller. You don't need to inherit a specific class or implement a specific interface. You only need to use @Controller to mark a class as a Controller, and then use some annotations such as @RequestMapping and @RequestParam to define it. Mapping between URL requests and Controller methods, so that the Controller can be accessed by the outside world. In addition, Controller does not directly depend on HttpServlet objects such as HttpServletRequest and HttpServletResponse. They can be flexibly obtained through the method parameters of Controller.

@Controller is used to mark a class. The class marked with it is a SpringMVC Controller object. The dispatch processor will scan the method of the annotated class and detect whether 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. Simply using the @Controller mark on a class cannot truly say that it is a controller class of SpringMVC, because Spring does not recognize it at this time. So how do you use Spring to recognize it? At this time, we need to hand over this controller class to Spring for management. There are two ways:

 (1) Define the bean object of MyController in the SpringMVC configuration file.

 (2) In the SpringMVC configuration file, tell Spring where to find the Controller marked @Controller.

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

2. @RequestMapping

RequestMapping is an annotation used to handle request address mapping and can be used on classes or methods. Used on a class, it means that all methods in the class that respond to requests use this address as the parent path.

The RequestMapping annotation has six attributes. Below we divide it into three categories for explanation (there are corresponding examples below).

1. value, method;

value: Specify the actual address of the request. The specified address can be URI Template mode (will be explained later);

method: Specify Requested method type, GET, POST, PUT, DELETE, etc.;

2, consumes, produces

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

produces: Specify the content type to be returned, and it will be returned only if the (Accept) type in the request header contains the specified type;

3, params, headers

params: The specified request must contain certain parameter values ​​before it can be processed by this method.

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

3, @Resource and @Autowired

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

1. Common points

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

2. Differences

(1)@Autowired

@Autowired is an annotation provided by Spring and needs to import the package org.springframework.beans.factory.annotation.Autowired; Only inject according to byType.

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

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

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

(2) @Resource

@Resource is automatically injected by ByName by default, provided by J2EE, and needs to import the package javax.annotation.Resource. @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 byName automatic injection strategy is used, and when the type attribute is used, the byType automatic injection strategy is used. If neither the name nor the type attribute is specified, the byName automatic injection strategy will be used 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;
    }
}
Copy after login

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

@Resource assembly sequence:

① If name and type are specified at the same time, the only matching bean will be found from the Spring context for assembly. If it is not found, an exception will be thrown.

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

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

④如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配。

@Resource的作用相当于@Autowired,只不过@Autowired按照byType自动注入。

4、@ModelAttribute和 @SessionAttributes

代表的是:该Controller的所有方法在调用前,先执行此@ModelAttribute方法,可用于注解和方法参数中,可以把这个@ModelAttribute特性,应用在BaseController当中,所有的Controller继承BaseController,即可实现在调用Controller时,先执行@ModelAttribute方法。

@SessionAttributes即将值放到session作用域中,写在class上面。

具体示例参见下面:使用 @ModelAttribute 和 @SessionAttributes 传递和保存数据

5、@PathVariable

用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。如:

@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";  
     }  
}
Copy after login

6、@requestParam

@requestParam主要用于在SpringMVC后台控制层获取参数,类似一种是request.getParameter("name"),它有三个常用参数:defaultValue = "0", required = false, value = "isApp";defaultValue 表示设置默认值,required 铜过boolean设置是否是必须要传入的参数,value 值表示接受的传入的参数类型。

7、@ResponseBody

作用: 该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

8、@Component

相当于通用的注解,当不知道一些类归到哪个层时使用,但是不建议。

9、@Repository

用于注解dao层,在daoImpl类上面注解。

 推荐教程:《Java教程



The above is the detailed content of SpringMVC common annotations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template