search
HomeJavajavaTutorialIntroducing commonly used annotation methods in spring mvc

This article mainly introduces the common annotations of spring mvc, and introduces similar annotations such as @RequestMapping, @RequestParam, @ModelAttribute and so on in detail. Those who are interested can learn more

Spring starts from version 2.5 To introduce annotations in programming, users can use similar annotations such as @RequestMapping, @RequestParam, @ModelAttribute, etc. So far, although the Spring version has undergone great changes, the features of annotations have been continued and continuously expanded, making the hands of the majority of developers easier. This is inseparable from the power of Annotation. Function, today we will take a look at the annotations commonly used in Spring MVC 4.

1. @Controller

Controller controller is a behavior defined through the service interface that provides access to the application. It interprets the user's takes input, converts it into a model and then renders the view to the user. Spring MVC uses @Controller to define controllers, which also allows components defined on the classpath to be automatically detected and automatically registered. If you want automatic detection to take effect, you need to introduce spring-context under the XML header file:


 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
  <context:component-scan base-package="org.springframework.samples.petclinic.web"/>
 
  <!-- ... --></beans>

2. @RequestMapping

We can use the @RequestMapping annotation to map a URL like "/favsoft" to the entire class or a specific processing method. Generally speaking, class-level annotations map a specific request path to the form controller, while method-level annotations simply map to a specific HTTP method request ("GET", "POST", etc.) or HTTP request parameters.


@Controller
@RequestMapping("/favsoft")
public class AnnotationController {
   
  @RequestMapping(method=RequestMethod.GET)
  public String get(){
    return "";
  }
   
  @RequestMapping(value="/getName", method = RequestMethod.GET)
  public String getName(String userName) {
    return userName;
  }
   
  @RequestMapping(value="/{day}", method=RequestMethod.GET)
  public String getDay(Date day){
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    return df.format(day);
  }
   
  @RequestMapping(value="/addUser", method=RequestMethod.GET)
  public String addFavUser(@Validated FavUser favUser,BindingResult result){
    if(result.hasErrors()){
      return "favUser";
    }
    //favUserService.addFavUser(favUser);
    return "redirect:/favlist";
  }
 
  @RequestMapping("/test")
  @ResponseBody
  public String test(){
    return "aa";
  }
   
}

@RequestMapping can act on both the class level and the method level. When it is defined at the class level, it indicates that all requests handled by this controller are mapped to the /favsoft path. You can use the method attribute in @RequestMapping to mark the method types it accepts. If the method type is not specified, you can use the HTTP GET/POST method to request data. However, once the method type is specified, you can only use that type to obtain data.

@RequestMapping You can use @Validated and BindingResult to jointly verify the input parameters. If the verification passes or fails, different views will be returned respectively.

@RequestMapping supports using URI templates to access URLs. A URI template is a URL-like string consisting of one or more variable names. When these variables have values, it becomes a URI.

3. @PathVariable

In Spring MVC, you can use @PathVariable to annotate method parameters and bind them to URI template variables. Value. As shown in the following code:


 String findOwner( String , Model model) {
  FavUser favUser = favUserService.findFavUser();
  model.addAttribute(
   ;
}

URI template "favusers/{favUserId}" specifies the name of the variable favUserId. When the controller processes this request, the value of favUserId will be Set to URI. For example, when there is a request like "favusers/favccxx", the value of favUserId is favccxx.

@PathVariable can have multiple annotations, like the following:


@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);
  Pet pet = owner.getPet(petId);
  model.addAttribute("pet", pet);  return "displayPet";
}

The parameters in @PathVariable can be any simple Types, such as int, long, Date, etc. Spring will automatically convert it to the appropriate type or throw a TypeMismatchException. Of course, we can also register to support additional data types.

If @PathVariable uses Map type parameters, Map will be filled in all URI template variables.

@PathVariable supports the use of regular expressions, which determines its super powerful properties. It can use placeholders in path templates, and can set specific prefix matching, suffix matching, etc. Define the format.

@PathVariable also supports matrix variables. Because they are not used much in real-life scenarios, I will not introduce them in detail. If you need children's shoes, please check the official website's documentation.

4. @RequestParam

@RequestParam binds the requested parameters to the parameters in the method, as shown in the following code. In fact, even if this parameter is not configured, the annotation will use this parameter by default. If you want to customize the specified parameters, set the required attribute of @RequestParam to false (such as @RequestParam (value="id", required=false)).

5. @RequestBody

##@RequestBody means that the method parameters should be bound to the HTTP request Body.


@RequestMapping(value = "/something", method = RequestMethod.PUT)public void handle(@RequestBody String body, Writer writer) throws IOException {
  writer.write(body);
}

If you feel that @RequestBody is not as good as @RequestParam, we can use HttpMessageConverter to transfer the body of the request to the method parameters. HttMessageConverser will exchange HTTP request messages between Object objects. conversion, but this is generally not done. It turns out that @RequestBody has greater advantages than @RequestParam when building REST architecture.


6. @ResponseBody

@ResponseBody is similar to @RequestBody. Its function is to input the return type directly into the HTTP response body. @ResponseBody is often used when outputting data in JSON format. The code is shown below:


@RequestMapping(value = "/something", method = RequestMethod.PUT)@ResponseBodypublic String helloWorld() {  return "Hello World";
}

7. @RestController

我们经常见到一些控制器实现了REST的API,只为服务于JSON,XML或其它自定义的类型内容,@RestController用来创建REST类型的控制器,与@Controller类型。@RestController就是这样一种类型,它避免了你重复的写@RequestMapping与@ResponseBody。


@RestController
public class FavRestfulController {
 
@RequestMapping(value="/getUserName",method=RequestMethod.POST)
public String getUserName(@RequestParam(value="name") String name){
return name;
}
}

8. HttpEntity

HttpEntity除了能获得request请求和response响应之外,它还能访问请求和响应头,如下所示:


@RequestMapping("/something")public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException {
  String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"));  byte[] requestBody = requestEntity.getBody();  // do something with request header and body

  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.set("MyResponseHeader", "MyValue");  return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}

9. @ModelAttribute

@ModelAttribute可以作用在方法或方法参数上,当它作用在方法上时,标明该方法的目的是添加一个或多个模型属性(model attributes)。该方法支持与@RequestMapping一样的参数类型,但并不能直接映射成请求。控制器中的@ModelAttribute方法会在@RequestMapping方法调用之前而调用,示例如下:


@ModelAttribute
public Account addAccount(@RequestParam String number) {
  return accountManager.findAccount(number);
}

@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
  model.addAttribute(accountManager.findAccount(number));  
  // add more ...
}

@ModelAttribute方法用来在model中填充属性,如填充下拉列表、宠物类型或检索一个命令对象比如账户(用来在HTML表单上呈现数据)。

@ModelAttribute方法有两种风格:一种是添加隐形属性并返回它。另一种是该方法接受一个模型并添加任意数量的模型属性。用户可以根据自己的需要选择对应的风格。

@ModelAttribute作用在方法参数上

当@ModelAttribute作用在方法参数上时,表明该参数可以在方法模型中检索到。如果该参数不在当前模型中,该参数先被实例化然后添加到模型中。一旦模型中有了该参数,该参数的字段应该填充所有请求参数匹配的名称中。这是Spring MVC中重要的数据绑定机制,它省去了单独解析每个表单字段的时间。

@ModelAttribute是一种很常见的从数据库中检索属性的方法,它通过@SessionAttributes使用request请求存储。在一些情况下,可以很方便的通过URI模板变量和类型转换器检索属性。

The above is the detailed content of Introducing commonly used annotation methods in spring mvc. 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
Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools