Annotations are commonly used in SpringMVC

  • RequestParam
  • RequestBody
  • PathVaribale
    • Let’s take a look at RESTFUL urls
  • RequestHeader
  • CookieValue
  • ModelAttribute
    • Decorated methods have return values
    • The decorated method has no return value
  • SessionAttribute

RequestParam

instructions

Function:

Assigns the named parameter in the request to the parameter in the controller.

Properties:

Value: specifies the name of the request parameter.

Required: Whether this parameter must be provided in the request parameter. Default value: true. Indicates that this parameter must be provided. If this parameter is not provided, an error will be reported.

Code sample

The JSP code:

<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/1/25 Time: 10:48 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html; Charset =UTF-8" language=" Java "%>< HTML ><head> <title> </head><body> <! <a href="anno/testRequestParam? name=keafmd">RequestParam</a><br/> </body></html>12345678910111213141516171819Copy the code

Controller code:

package com.Keafmd.controller; import com.Keafmd.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import java.util.Date; import java.util.Map; /** * Keafmd ** @className: AnnoConteoller * @description: Annotation controller * @author: cool conan * @date: 2021-01-2510:50 */@Controller@RequestMapping("/anno")public class AnnoConteoller {/** * requestParams annotation use * @param username * @return */ @RequestMapping("/testRequestParam") public String testRequestParam(@RequestParam(value="name") String username){// @requestParam (value="name") must pass name,required: String clazz = Thread.CurrentThread ().getStackTrace()[1].getClassName(); String method = Thread.CurrentThread ().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+clazz+" - "+method); System.out.println("username:"+username); return "success"; }} 12345678910111213141516171819202122232425262728293031323334353637383940414243Copy the code

Output result:

Execution: com. Keafmd. Controller. AnnoConteoller - testRequestParamusername: keafmd12Copy the code

So if we pass the name in href we’re going to assign it to username.

RequestBody

instructions

Function:

Used to get the request body content. Key =value&key=value… Structured data.

The GET request mode is not applicable.

Properties:

Required: Whether the request body is required. The default value is true. When the value is true, an error is reported in the GET request mode. If the value is false, the GET request returns null.

Code sample

The JSP code:

<form action="anno/testRequestBody" method="post"> <input type="text" name="age" /><br/> <br/> < form type="submit" value=" submit" ></form>123456Copy the code

Controller code:

RequestBody */ @requestMapping ("/testRequestBody")public String testRequestBody(@requestBody String body){ String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); System.out.println("body:"+body); return "success"; } 1234567891011Copy the code

Output result:

Execution: testRequestBodybody: uname = Keafmd&age = 21 & birthday = 12 2000-01-01Copy the code

PathVaribale

Let’s take a look at RESTFUL urls

REST (Representational State Transfer) describes an architectural style of network system, such as a Web application. It is important to note that REST does not have a clear standard, but rather a style of design.

instructions

Function:

Used to bind placeholders in urls. For example: request url /delete/{id}, this {id} is the URL placeholder.

Url support placeholders were added after spring3.0. Is an important indicator of SpringMVC’s support for REST-style urls.

Properties:

Value: Specifies the placeholder name in the URL.

Required: Whether placeholders must be provided.

Code sample

The JSP code:

<a href="anno/testPathVariable/10">testPathVariable</a><br/>1
Copy the code

Controller code:

/*** PathVariable* @param id* @return*/@RequestMapping("/testPathVariable/{sid}")public String TestPathVariable (@pathvariable (name="sid") String ID){// Obtain the current method name String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); System.out.println("id:"+id); return "success"; } 12345678910111213Copy the code

Output result:

TestPathVariableid :1012 is executedCopy the code

RequestHeader

instructions

Function:

Used to get the request header.

Properties:

Value: Provides the header name

Required: Whether this header is required

Tip:

It is not usually used in real development

Code sample

The JSP code:

<a href="anno/testRequestHeader">testRequestHeader</a><br/>1
Copy the code

Controller code:

* @param head* @return*/ @requestMapping ("/testRequestHeader")public String TestRequestHeader (@requestheader (value = "Accept") String head){// Get the name of the current method Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); System.out.println("head:"+head); return "success"; } 1234567891011121314Copy the code

Output result:

Performed: testRequestHeaderhead: text/HTML, application/XHTML + XML, application/XML. Q = 0.9, image/webp image/apng, * / *; Q = 0.8, application/signed - exchange; v=b312Copy the code

CookieValue

instructions

Function:

Used to pass the value specifying the cookie name to the controller method parameter.

Properties:

Value: Specifies the name of the cookie.

Required: Whether this cookie is required.

Code sample

The JSP code:

<a href="anno/testCookieValue">testCookValue</a><br/>1
Copy the code

Controller code:

/** * CookieValue * @requestMapping ("/testCookieValue")public String TestCookieValue (@cookievalue (value = "JSESSIONID") String CookieValue){// Get the current method name String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); System.out.println("cookievalue:"+cookievalue); return "success"; } 1234567891011121314Copy the code

Output result:

Execution: testCookieValuecookievalue: DCCFE2C1F975AC04D4F55973ADA5C89C12Copy the code

ModelAttribute

instructions

Function:

This annotation is a new addition to Spring VC4.3. It can be used to modify methods and parameters.

Appears on a method to indicate that the current method is executed before the controller’s method. It can modify methods that have no return value or methods that have a concrete return value.

Appears on a parameter and gets the specified data to assign to the parameter.

Properties:

Value: key used to obtain data. The key can be the attribute name of the POJO or the key of the map structure.

Application Scenarios:

When the form submission data is not the complete entity-class data, ensure that fields without submission data use the original data of the database object.

Code sample

The JSP code:

<form action="anno/testModelAttribute" method="post"> User name: <input type="text" name="uname" /><br/> User age: <input type="text" name="age" /><br/> < form type="submit" value=" submit" ></form>12345Copy the code

Decorated methods have return values

Controller code:

/** * ModelAttribute * @return */ @RequestMapping("/testModelAttribute")public String testModelAttribute(User user){ // String method = Thread.CurrentThread ().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); System.out.println(user); return "success"; } @modelattributePublic User showUser(String uname){String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); User user = new User(); user.setUname(uname); user.setAge(20); user.setBirthday(new Date()); return user; } 12345678910111213141516171819202122232425Copy the code

Output result:

TestModelAttributeUser {uname=' Conan ', age=21, birthday=Mon Jan 25 19:34:46 CST 2021}12Copy the code

The decorated method has no return value

Note: If no value is returned, the Map is used to return the parameter. The testModelAttribute parameter User is preceded by @modelAttribute (” ABC “) to receive the data from the Map.

Controller code:

/** * ModelAttribute * @return */ @RequestMapping("/testModelAttribute")public String TestModelAttribute (@modelAttribute (" ABC ")User User){// Get the current method name String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); System.out.println(user); return "success"; } @modelattributePublic void showUser(String uname, Map<String,User> map){ String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); User user = new User(); user.setUname(uname); user.setAge(20); user.setBirthday(new Date()); map.put("abc",user); } 12345678910111213141516171819202122232425Copy the code

Output result:

TestModelAttributeUser {uname=' Conan ', age=21, birthday=Mon Jan 25 19:32:20 CST 2021}12Copy the code

SessionAttribute

instructions

Function:

Used to share parameters between controller methods that execute multiple times.

Properties:

Value: Specifies the name of the saved attribute

Type: Specifies the type of data to store.

Code sample

The JSP code:

< a href = "anno/testSessionAttributes" > deposit SessionAttributes < / a > < br / > < a Href = "anno/getSessionAttributes" > get SessionAttributes < / a > < br / > < a Href = "anno/delSessionAttributes" > remove SessionAttributes < / a > < br / > 123Copy the code

Controller code:

Note: add @sessionAttributes (value = {” MSG “}) to the top of the class.

package com.Keafmd.controller; import com.Keafmd.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.support.SessionStatus; import java.util.Date; import java.util.Map; /** * Keafmd ** @className: AnnoConteoller * @description: Annotation controller * @author: cool conan * @date: 2021-01-2510:50 */@Controller@RequestMapping("/anno") @sessionAttributes (value = {" MSG "} Class AnnoConteoller {** ** SessionAttributes; Add MSG * @requestMapping */ @requestMapping ("/testSessionAttributes") public String testSessionAttributes(Model Model) String method = Thread.CurrentThread ().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); // The bottom layer will be saved in the Request field model.addattribute (" MSG "," Booty Conan "); return "success"; } @requestMapping ("/getSessionAttributes") public String @requestMapping ("/getSessionAttributes") public String GetSessionAttributes (ModelMap ModelMap){// Get the current method name String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); String MSG = (String) modelmap.get (" MSG "); System.out.println(msg); return "success"; } @requestMapping ("/delSessionAttributes") public String * @requestMapping ("/delSessionAttributes") public String DelSessionAttributes (SessionStatus SessionStatus) {// Get the current method name String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println(" execute: "+" "+method); . / / cleared from the session domain sessionStatus setComplete (); return "success"; }} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646 5666768697071727374757677Copy the code

Click Save -> Get -> Clear -> Get.

Output result:

Performed: testSessionAttributes performed: getSessionAttributes cattle to coax conan performed: delSessionAttributes performed: getSessionAttributesnull123456Copy the code

MSG and {MSG} and MSG and {sessionScope} can be used to retrieve the contents of the session field stored on the class above: ${requestScope} gets the content stored in the testSessionAttributes method into the Request field in success.jsp.

That’s all for common annotations in SpringMVC.

Pay attention!

Remember to like + comment + forward oh ~