Introducing 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
@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
@RequestMapping(value = "/something", method = RequestMethod.PUT)public void handle(@RequestBody String body, Writer writer) throws IOException { writer.write(body); }
6. @ResponseBody
@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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

PyCharm multi-line comment shortcut keys: Make code comments more convenient and require specific code examples. In daily programming work, code comments are a very important part. It not only improves the readability and maintainability of the code, but also helps other developers understand the intent and design ideas of the code. However, manually adding code comments is often a time-consuming and tedious task. In order to make our code comments more efficient, PyCharm provides shortcut keys for multi-line comments. In PyCharm, we can use Ctrl+/

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

Recommended computers suitable for students majoring in geographic information science 1. Recommendation 2. Students majoring in geographic information science need to process large amounts of geographic data and conduct complex geographic information analysis, so they need a computer with strong performance. A computer with high configuration can provide faster processing speed and larger storage space, and can better meet professional needs. 3. It is recommended to choose a computer equipped with a high-performance processor and large-capacity memory, which can improve the efficiency of data processing and analysis. In addition, choosing a computer with larger storage space and a high-resolution display can better display geographic data and results. In addition, considering that students majoring in geographic information science may need to develop and program geographic information system (GIS) software, choose a computer with better graphics processing support.

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

iCloud Keychain makes it easier to manage your passwords without relying on memorizing or guessing website or usernames. You can do this by adding notes to existing passwords for apps and websites in iCloud Keychain. In this post, we will explain how to add notes to the passwords you save in iCloud Keychain on iPhone. Requirements There are some requirements you need to meet to use this new feature in iCloud Keychain. iPhone running iOS 15.4 or later Passwords stored in iCloud Keychain A valid Apple ID A valid internet connection How to add notes to saved passwords It goes without saying that you should store some passwords in iCloud Keychain

Spring is an open source framework that provides many annotations to simplify and enhance Java development. This article will explain commonly used Spring annotations in detail and provide specific code examples. @Autowired: Autowired @Autowired annotation can be used to automatically wire beans in the Spring container. When we use the @Autowired annotation where dependencies are required, Spring will find matching beans in the container and automatically inject them. The sample code is as follows: @Auto
