Home Java javaTutorial springmvc common annotations

springmvc common annotations

Jul 20, 2019 pm 04:18 PM
java spring

springmvc common annotations

Recommended tutorial: Spring Tutorial

##1. Component-type annotations:

1. @Component Add the @Component annotation before the class definition, and it will be Spring Container identification and conversion to beans.

2. @Repository annotates the Dao implementation class (special @Component)

3. @Service is used to annotate the business logic layer, (special @Component)

4. @Controller is used to annotate the control layer, ( Special @Component)

The above four annotations are all annotated on the class. The annotated class will be initialized as a bean by spring and then managed uniformly.

springmvc common annotations

## 2. Request and parameter type annotations:

1. @RequestMapping: used to process request address mapping, which can be applied to classes and methods.

Value: Define the mapping address of the request request

Method: Define the method of request address request, including [GET , POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.] The get request is accepted by default. If the request method is different from the defined method, the request will not succeed.

Params: Define the parameter values ​​that must be included in the request request.

Headers: Define that the request request must contain certain specified request headers, such as: RequestMapping(value = "/something", headers = "content-type=text/*" ) indicates that the request must contain the Content-type header of "text/html", "text/plain" to be a matching request.

●consumes: Define the type of content requested to be submitted.

●produces: Specify the content type to be returned. Only when the (Accept) type in the request header contains the specified type will it be returned

@RequestMapping(value="/requestTest.do",params = {"name=sdf"},headers = {"Accept-Encoding=gzip, deflate, br"},method = RequestMethod.GET)
     public String getIndex(){
         System.out.println("请求成功");
         return "index";
     }
Copy after login

The above code indicates that the request method is a GET request. The request parameters must include the parameter name=sdf, and then the request header must have the type header Accept-Encoding=gzip, deflate, br.

springmvc common annotations

In this way, a request can be constrained through annotations.

2.@RequestParam: used to get the value of the incoming parameter

Value: the name of the parameter

required: definition Whether the incoming parameter is required, the default is true, (similar to the params attribute of @RequestMapping)

@RequestMapping("/requestParams1.do")
    public String requestParams1(@RequestParam(required = false) String name){
        System.out.println("name = "+name);
        return "index";
    }
    @RequestMapping("/requestParams2.do")
    public String requestParams2(@RequestParam(value = "name",required = false) String names){
        System.out.println("name = "+names);
        return "index";
    }
Copy after login

The two methods of entering parameters are the same. When the name of the declared value is displayed, enter the parameter The parameter name is the same as the value. If there is no explicit declaration, as declared in the first way, the input parameter name is the same as the function parameter variable name.

##3.@PathViriable: used to define path parameter values

●value: the name of the parameter

●required: defines whether the incoming parameter is a required value

@RequestMapping("/{myname}/pathVariable2.do")    public String pathVariable2(@PathVariable(value = "myname") String name){
        System.out.println("myname = "+name);        return "index";
    }
Copy after login

This path declares {myname} as a path parameter, then this path will be Any value, @PathVariable will be able to get the value of the path based on value.


4.@ResponseBody: Acting on the method, the entire return result can be returned in a certain format, such as json or xml format .

 @RequestMapping("/{myname}/pathVariable2.do")
      @ResponseBody
      public String pathVariable2(@PathVariable(value = "myname") String name){
          System.out.println("myname = "+name);
          return "index";
      }
Copy after login

springmvc common annotations

## It returns not a page, but the string " index" is printed directly on the page, which is actually similar to the following code.

PrintWriter out = resp.getWriter();
 out.print("index");
 out.flush();
Copy after login

5、@CookieValue:用于获取请求的Cookie值

 @RequestMapping("/requestParams.do")
      public String requestParams(@CookieValue("JSESSIONID") String cookie){
          return "index";
      }
Copy after login

6、@ModelAttribute:

  用于把参数保存到model中,可以注解方法或参数,注解在方法上的时候,该方法将在处理器方法执行之前执行,然后把返回的对象存放在 session(前提时要有@SessionAttributes注解) 或模型属性中,@ModelAttribute(“attributeName”) 在标记方法的时候指定,若未指定,则使用返回类型的类名称(首字母小写)作为属性名称。 

@ModelAttribute("user")
    public UserEntity getUser(){
        UserEntity userEntityr = new UserEntity();
        userEntityr.setUsername("asdf");
        return userEntityr;
    }

    @RequestMapping("/modelTest.do")
    public String getUsers(@ModelAttribute("user") UserEntity user){
        System.out.println(user.getUsername());
        return "/index";
    }
Copy after login

  如上代码中,使用了@ModelAttribute("user")注解,在执行控制器前执行,然后将生成一个名称为user的model数据,在控制器中我们通过注解在参数上的@ModelAttribute获取参数,然后将model应用到控制器中,在jsp页面中我们同样可以使用它,

 <body>
      ${user.username}
 </body>
Copy after login

7、@SessionAttributes

  默认情况下Spring MVC将模型中的数据存储到request域中。当一个请求结束后,数据就失效了。如果要跨页面使用。那么需要使用到session。而@SessionAttributes注解就可以使得模型中的数据存储一份到session域中。配合@ModelAttribute("user")使用的时候,会将对应的名称的model值存到session中,

@Controller
@RequestMapping("/test")
@SessionAttributes(value = {"user","test1"})
public class LoginController{
    @ModelAttribute("user")
    public UserEntity getUser(){
        UserEntity userEntityr = new UserEntity();
        userEntityr.setUsername("asdf");
        return userEntityr;
    }

    @RequestMapping("/modelTest.do")
    public String getUsers(@ModelAttribute("user") UserEntity user ,HttpSession session){
        System.out.println(user.getUsername());
        System.out.println(session.getAttribute("user"));
        return "/index";
    }
}
Copy after login

  结合上一个例子的代码,加了@SessionAttributes注解,然后请求了两次,第一次session中不存在属性名为user的值,第二次请求的时候发现session中又有了,这是因为,这是因为第一次请求时,model数据还未保存到session中请求结束返回的时候才保存,在第二次请求的时候已经可以获取上一次的model了

1068779-20171027175359008-1504110330 (1).png

注意:@ModelAttribute("user") UserEntity user获取注解内容的时候,会先查询session中是否有对应的属性值,没有才去查询Model。

The above is the detailed content of springmvc common annotations. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles