Common annotations of spring MVC

1.@RequestParam

      1. It is used to receive the parameters passed by the method before the parameters passed by the method (it is an annotation that accepts common parameters in spring MVC)

      2. Attribute: name in value request parameter

required: whether this parameter is provided in the request parameters. The default value is true

defaultValue: Specifies the default value of the parameter

 @RequestMapping("/user")
 @Controller
 public class QuickController {
     @RequestMapping("/testRequestParam")
    public String testRequestParam(@RequestParam("username")String username,@RequestParam(value = "age",required = false,defaultValue = "0")Integer age){
        System.out.println(username +",,," + age);
        return "index";
    }
 }
 <form action="user/testRequestParam" method="post">
      full name:<input type="text" name="username"><br>
      Age:<input type="text" name="age"><br>
      <input type="submit" value="testRequestParam">

  </form>

Enter the name and age, and the console will get the entered name and age

 

 

2.@Controller

     1.@Controller is used to mark a class. The class marked with it is a springmvc Controller object, that is, a controller class. Spring uses the scanning mechanism to find all annotation based controller classes. It is usually used in conjunction with the annotation based @ RequestMapping method.

    2. The annotation has a default method. The return type is String, and the default value of value is null

package org.springframework.stereotype;

@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
@org.springframework.stereotype.Component
public @interface Controller {
    @org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class)
    java.lang.String value() default "";
}

3.@RequestMapping

     1. In spring MVC, @ RequestMapping is used to map requests. It is also used to specify which URL requests the controller can handle. Quite a servlet in the web XML configuration

     2.@RequestMapping has six attributes. Generally, there are three attributes commonly used in projects: value, method and produces

value: Specifies the actual address of the request

method: Specifies the type of request, mainly including GET, post, put and delete. The default is GET

Productions: specify the return content type productions = "application / JSON; charset = UTF-8"

@RequestMapping(value = "/user",produces="application/json;charset=UTF-8")
@Controller
public class QuickController {
     @RequestMapping(value = "/testPost",method = RequestMethod.POST)
    public String testPost(){
        System.out.println("quickMethod running.....");
        return "index";
    }
}
<form action="user/testPost" method="post">
  <input type="submit" value="testPost">
</form>

4.@SessionAttributes

   1. The parameters can be shared among multiple requests. The configuration needs to store the data range in the session, @ SessionAttributes can only be used on the class definition.

      2.

@SessionAttributes(value = {"user"},types = {String.class})

The attribute named user and the attribute of type String in the model are added to the session.

@SessionAttributes(value = {"user"},types = {String.class})
@RequestMapping("/user")
@Controller
public class QuickController {
    @RequestMapping("/testSessionAttribute")
   public String testSessionAttribute(Map<String,Object> map){
        User user = new User();
        user.setName("LBJ");
        user.setAge(37);
       Car car = new Car();
       car.setKind("aodi");
       user.setCar(car);
       map.put("user",user);
       map.put("a","wc");
       map.put("inter",new Integer(12));
       return "index";
   }
}

 

<a href="user/testSessionAttribute">testSessionAttribute</a>
request:${requestScope.user};${requestScope.a};${requestScope.inter}
<br>
session:${sessionScope.user};${sessionScope.a};${sessionScope.inter}

Obviously, session didn't get the value of 12

 

5.@ModelAttribute

     1.@ModelAttribute can be used to decorate methods and parameters

Used in methods: the methods annotated by @ ModelAttribute will be executed before the execution of each method of this controller. You can modify the methods without return value or the methods with specific return value.

Used on parameters: the parameters passed from the client will be injected into the specified object by name

Application scenario: when the data submitted by the form is not complete entity data, ensure that the fields that do not submit data use the original data of the database object.

@RequestMapping("/user")
@Controller
public class QuickController {
    @RequestMapping("/testModuleAttribute")
    public String testModuleAttribute(User user){
        System.out.println(user);
        return "index";

   }
<form action="user/testModuleAttribute" method="post">
    <input type="text" name="name">
    <input type="submit" value="testModuleAttribute">
  </form>

At this point, we can only get the name

When we add @ ModelAttribute

 @ModelAttribute
    public void test(Map<String,User> map){
        System.out.println("1111");
        User user = new User();
        user.setName("Gurry");
        user.setAge(31);
        map.put("user",user);

   }

You can get the name and age while entering the name

 

6.@PathVariable

   1. The placeholder parameter in the URL can be bound to the input parameter of the controller processing method through @ PathVariable: {xxx} placeholder in the URL can be bound to the input parameter of the method through @ PathVariable("xxx")

       2.@PathVariable can receive multiple parameters but cannot receive objects

@RequestMapping("/user")
@Controller
public class QuickController {
     @RequestMapping(value = "/testPathVariable/{id}")
    public String testPathVariable(@PathVariable("id") Integer id){
        System.out.println("testPathVariable running....." + id);
        return "index";
    }
}

 

<a href="user/testPathVariable/12">testPathVariable</a>

 

7.@ResponseBody  

     1.@ The function of the ResponseBody annotation is to convert the object returned by the controller method into the specified format through an appropriate converter and write it into the body area of the response object. Usually, JSON data or XML data are returned. Using this annotation, the view processor will not be used.

Return string without @ ResponseBody annotation requires response getWriter. write();

 @RequestMapping("/testString")
    public void testString(HttpServletResponse response){
        try {
            response.getWriter().print("hello");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

After adding @ ResponseBody annotation

 @RequestMapping("/testResponsebody")
    @ResponseBody
    public String testResponsebody(){
       return "abcdefg";
    }

 8.@RequestHeader

        1.@ The requestheader annotation is used to get the request header

        2. Attribute value: provide message header name. Parameter value is String type

required: whether there must be a message header. The default value is true

defaultValue: the default value when the request header variable binding fails

 @RequestMapping("/testHead")
    public String testHead(@RequestHeader(value = "Accept") String myHeader){
        System.out.println("testHead");
        System.out.println(myHeader);

        return "index";
    }

 

 <a href="user/testHead">testHead</a>

The deployment is successful. The console obtains the value of the request header

 

 

 

 

 

 

 

 

Keywords: Java Spring Spring MVC mvc

Added by Sgt.Angel on Fri, 25 Feb 2022 14:21:11 +0200