search
HomeJavajavaTutorialspringmvc common annotations

springmvc common annotations

Jul 20, 2019 pm 04:18 PM
javaspring

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";
     }

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";
    }

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";
    }

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";
      }

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();

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

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

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";
    }

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

 <body>
      ${user.username}
 </body>

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";
    }
}

  结合上一个例子的代码,加了@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
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools