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

What are the commonly used annotations in springmvc?

Apr 21, 2020 pm 04:15 PM
springmvc

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

What are the differences between SpringBoot and SpringMVC? What are the differences between SpringBoot and SpringMVC? Dec 29, 2023 am 10:46 AM

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

What is the difference between SpringBoot and SpringMVC? What is the difference between SpringBoot and SpringMVC? Dec 29, 2023 pm 05:19 PM

SpringBoot and SpringMVC are two frameworks commonly used in Java development. They are both provided by the Spring framework, but they have some differences in functions and usage methods. This article will introduce the characteristics and differences of SpringBoot and SpringMVC respectively. 1. Features of SpringBoot: Simplified configuration: SpringBoot greatly simplifies the project configuration process through the principle of convention over configuration. It can automatically configure the parameters required by the project, and developers

What are the differences between springboot and springmvc What are the differences between springboot and springmvc Jun 07, 2023 am 10:10 AM

The differences between springboot and springmvc are: 1. Different meanings; 2. Different configurations; 3. Different dependencies; 4. Different development times; 5. Different productivity; 6. Different ways to implement JAR packaging function; 7. Whether batch processing is provided Function; 8. Different functions; 9. Different community and documentation support; 10. Whether deployment descriptors are required.

What are the differences between spring and springmvc What are the differences between spring and springmvc Dec 29, 2023 pm 05:02 PM

The difference between spring and springmvc: 1. Positioning and functions; 2. Core functions; 3. Application areas; 4. Extensibility. Detailed introduction: 1. Positioning and functions. Spring is a comprehensive application development framework that provides dependency injection, aspect-oriented programming, transaction management and other functions. It is designed to simplify the development of enterprise-level applications, and Spring MVC is the Spring framework. A module in it is used for the development of Web applications and implements the MVC pattern; 2. Core functions and so on.

Using SpringMVC for Web service processing in Java API development Using SpringMVC for Web service processing in Java API development Jun 17, 2023 pm 11:38 PM

With the development of the Internet, Web services are becoming more and more common. As an application programming interface, JavaAPI is constantly launching new versions to adapt to different application scenarios. As a popular open source framework, SpringMVC can help us easily build web applications. This article will explain in detail how to use SpringMVC for Web service processing in JavaAPI development, including configuring SpringMVC, writing controllers, and using

How to use Java's SpringMVC interceptor How to use Java's SpringMVC interceptor May 13, 2023 pm 02:55 PM

The role of interceptor SpringMVC's interceptor is similar to the filter in Servlet development, which is used to pre-process and post-process the processor. Interceptors are connected into a chain in a certain order, and this chain is called an interceptor chain (InterceptorChain). When an intercepted method or field is accessed, the interceptors in the interceptor chain will be called in the order they were previously defined. Interceptors are also the specific implementation of AOP ideas. The difference between interceptors and filters: Filter (Filter) The scope of use of interceptor (Intercepter) is part of the servlet specification and can be used by any JavaWeb project. Spri

Compare the similarities and differences between SpringBoot and SpringMVC Compare the similarities and differences between SpringBoot and SpringMVC Dec 29, 2023 am 08:30 AM

Analyzing the similarities and differences between SpringBoot and SpringMVC SpringBoot and SpringMVC are very important development frameworks in the Java field. Although they are both part of the Spring framework, there are some obvious differences in usage and functionality. This article will compare SpringBoot and SpringMVC and analyze the similarities and differences between them. First, let's learn about SpringBoot. SpringBo

See all articles