Home > Java > javaTutorial > What are the commonly used annotations in springmvc?

What are the commonly used annotations in springmvc?

青灯夜游
Release: 2020-05-16 18:02:56
Original
2820 people have browsed it

What are the commonly used annotations in springmvc?

Common SpringMVC annotations

1, @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.

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. At this time, we need to hand over this controller class to Spring for management. There are two ways to manage:

<!--方式一-->
<bean class="com.cqvie.handler.HelloWorld"/>
<!--方式二-->
< context:component-scan base-package = "com.cqvie" /> <!-- 路径写到controller的上一层 -->
Copy after login

In addition, Controller will not directly depend on HttpServletRequest and HttpServletResponse and other HttpServlet objects, they can be flexibly obtained through the method parameters of Controller. In order to have a preliminary impression of the Controller, let’s define a simple Controller:

package com.cqvie.handler;
import org.springframework.stereotype.Controller;
@Controller
public class HelloWorld {
    @RequestMapping("/helloworld")
    public String sayHello() {
        System.out.println("Hello World!");
        return "success";
    }
    
}
Copy after login

2, @RequestMapping

RequestMapping is a Annotations used to handle request address mapping 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 return value will be parsed into the actual physical view through the view parser. For the InternalResourceViewResolver view parser, the following parsing will be done:

The actual physical view is obtained through prefix returnVal suffix. , and then do the forwarding operation;

<!-- 配置视图解析器:如何把 handler 方法返回值解析为实际的物理视图 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/views/"></property>
         <property name="suffix" value=".jsp"></property>
     </bean>
Copy after login

The RequestMapping annotation has six attributes:

1), value

value: specifies the actual address of the request;

2), method;

method: Specify the method type of the request, GET, POST, PUT, DELETE, etc., explained after @PathVariable in the following example:

/**
     * Rest 风格的 URL(以 CRUD 为例):
     *         新增:/order POST
     *         修改:/order/1 PUT
     *         获取:/order/1 GET
     *         删除:/order/1 DELETE
     * @param id
     * @return
     */
    @RequestMapping(value = "/testRestPut/{id}", method = RequestMethod.PUT)
    public String testRestPut(@PathVariable int id) {
        System.out.println("testRestPut:" + id);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/testRestDelete/{id}", method = RequestMethod.DELETE)
    public String testRestDelete(@PathVariable int id) {
        System.out.println("testRestDelete:" + id);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/testRestPost/{id}", method = RequestMethod.POST)
    public String testRestPost(@PathVariable int id) {
        System.out.println("testRestPost:" + id);
        return SUCCESS;
    }
    
    @RequestMapping("/testRestGet")
    public String testRestGet() {
        System.out.println("testRestGet");
        return SUCCESS;
    }
Copy after login

3), consumes

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

4), produces

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

5), params

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

6), headers

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

@RequestMapping("/helloword/?/aa"), matching character:

● ?: Match one character of the file name

● *: Match all characters of the file name

● **: Match multi-layer paths

@RequestMapping("/testPojo") POJO class usage:

@RequestMapping("/testPojo")
    public String testPojo(User user) {
        System.out.println("testPojo:" + user);
        return "success";
    }
  @RequestMapping("/testPojo") Map用法:
  @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map) {
        map.put("names", Arrays.asList("Tomcat", "Eclipse", "JavaEE"));
        return "success";
    }
  @RequestMapping("/testPojo") ModelAndView用法:
  @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        String viewName = SUCCESS;
        ModelAndView modelAndView = new ModelAndView(viewName);
        modelAndView.addObject("time", new Date());
        return modelAndView;
    }
Copy after login

3. @Resource and @Autowired

@Resource and @Autowired are both 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 annotation provided for Spring, you need to import the package org.springframework.beans.factory. annotation.Autowired; only injected according to byType.

public class HelloWorld{
    // 下面两种@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 HelloWorld{ 
  @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 HelloWorld{
    // 下面两种@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.

4, @PathVariable

is used to map the template variables in the request URL to the parameters of the function processing method, that is, take out the uri template variables 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";  
     }  
}
Copy after login

5, @CookieValue

Function: Used to obtain the value in Cookie;

Parameter: value :Parameter name required: Whether it is required defaultValue: Default value

Use case:

/**
     * 获取 Session
     * JSESSIONID=411A032E02A2594698F6E3F4458B9CE4
     */
    @RequestMapping("/testCookieValue")
    public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) {
        System.out.println("JSESSIONID = " + sessionId);
        return "success";
    }
Copy after login

6、@RequestParam

@RequestParam用于将请求参数区数据映射到功能处理方法的参数上,用例:

/**
     * @RequestParam("id") 带参映射
     * @param id
     * @return
     */
    @RequestMapping("/testRequestParam")
    public String testRequestParam(@RequestParam("id") int id) {
        System.out.println("testRequestParam  " + id);
        return "success";
    }
Copy after login

7、@SessionAttributes

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

@SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外(value 属性值),

还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(types 属性值),用例:

package com.cqvie.yjq;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.cqvie.model.User;
@SessionAttributes(value = {"user"}, types = {String.class})
@RequestMapping("/springmvc")
@Controller
public class SessionAttributesTest {
    
    /**
     * @SessionAttributes
     *         除了可以通过属性名指定需要放到会话中的属性外(value 属性值),
     *         还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(types 属性值)。
     * 注意: 该注解只能放在类的上面,不能放在方法上面
     * 
     * @return
     */
    @RequestMapping("/testSessionAttributes")
    public String testSessionAttributes(Map<String, Object> map) {
        User user = new User(1, "刘邦", "qwe", "123", "辽宁");
        map.put("user", user);
        map.put("school", "重庆");
        return "success";
    }
}
Copy after login

8、@ModelAttribute

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

package com.cqvie.yjq;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.cqvie.model.User;
@Controller
@RequestMapping("/springmvc")
public class ModelAttributeTest {
    private static final String SUCCESS = "success";
    
    /**
     * 1.有 @ModelAttribute 标记的方法,会在每个目标方法执行之前被 SpringMVC 调用
     * 2.@ModelAttribute注解也可以修饰目标方法POJO类形的入参,其value的属性值有如下作用:
     *     1)SpringMVC会使用value属性值在implicitModel中查找对应的对象,若存在则直接传入到目标方法的入参中
     *     2)SpringMVC会以value为key,POJO类型的对象为value,存入的request中
     * 
     * @param id
     * @param map
     */
    @ModelAttribute
    public void getUser(@RequestParam(value = "id", required = false) int id,
            Map<String, Object> map) {
        //模拟数据库中获取对象
        User user = new User(1, "刘邦", "123", "023", "重庆");
        System.out.println("从数据库中获取一个对象:" + user);
        map.put("abc", user);
    }
    
    /**
     * 运行流程:
     *         1.执行@ModelAttribute注解修饰的方法,从数据库中取出对象,把对象放入Map中,键为:user;
     *         2.SpringMVC从Map中取出User对象,并把表单的请求参数赋值给该User对象的对应属性;
     *         3.SpringMVC把上述对象传入目标方法的参数。
     * 
     * 注意:在@ModelAttribute修饰的方法中,放入到Map时的键需要和目标方法入参类型的第一个字母小写的字符串一致
     * 
     * @param user
     * @return
     */
    @RequestMapping("/testModelAttribute")
    public String testModelAttribute(@ModelAttribute("abc") User user) {
        System.out.println("修改:" + user);
        return SUCCESS;
    }
}
Copy after login

9、@ResponseBody 

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

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

本文来自php中文网,java教程栏目,欢迎学习!

The above is the detailed content of What are the commonly used annotations in springmvc?. 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