亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
@RequestMapping
@RequestParam
@PathVariable
@ResponseBody
@RequestBody
@CookieValue
@RequestHeader
@ExceptionHandler
Home Java JavaBase The use of 5 commonly used annotations in springmvc

The use of 5 commonly used annotations in springmvc

Jul 01, 2020 pm 05:25 PM
springmvc

Five common annotations of springmvc: 1. @RequestMapping, which is an annotation used to process request address mapping; 2. @RequestParam, which is used to map the request parameter area data to the parameters of the function processing method; 3. @PathVariable, used to set request variables.

The use of 5 commonly used annotations in springmvc

@RequestMapping

is an annotation used to handle request address mapping
Applicable to classes and methods. Used on a class, it means that all methods in the class that respond to requests use this address as the parent path.

Attribute

value: Specifies the actual address of the request. The value can be an ordinary specific value, or it can be specified as a type of value containing a certain variable (URI Template Patterns with Path Variables)
can be specified as a type of value containing regular expressions (URI Template Patterns with Regular Expressions)
method: Specify the requested method type, GET, POST, PUT, DELETE, etc.
consumes: Specify the submission content type (Content-Type) for processing the request, such as application/json, text/html
produces: Specify the returned content type, only When the (Accept) type in the request header contains the specified type, it will return
params: The specified request must contain certain parameter values ??before the method can process it
headers: The specified request must contain certain specified header values ??in order for this method to process the request

??1.處理get請求:?@RequestMapping(value?=?"index",method?=?RequestMethod.GET)
??2.springboot錯誤處理(使用app客戶端返回json格式,使用瀏覽器返回html錯誤頁)
???@RequestMapping(produces?=?"text/html")
??3.方法僅處理request?Content-Type為“application/json”類型的請求
???@RequestMapping(value?=?"/pets",?consumes="application/json")
??4.僅處理請求中包含了名為“myParam”,值為“myValue”的請求
???@RequestMapping(value?=?"/pets/{petId}",?params="myParam=myValue")?
??5.僅處理request的header中包含了指定“Refer”請求頭和對應值為“http://www.rxy.com/”的請求
???@RequestMapping(value?=?"/pets",?headers="Referer=http://www.rxy.com/")

@RequestParam

is used to map the request parameter area data to the function processing method
Applicable to the parameters: method parameters

Attributes

value/name: Both attributes refer to the parameter name, that is, the request parameter name of the input parameter ( Usually form name attribute)
required: Whether it is required, the default is true, which means that the request must have corresponding parameters, otherwise an exception will be thrown
defaultValue: Default Value, indicating the default value if there is no parameter with the same name in the request. When setting this parameter, required is automatically set to false

??如果是原子類型,不管加沒加注解,都必須有值,否則拋出異常,如果允許空值請使用包裝類代替
??index(@RequestParam?Integer?num){}??表示該參數(shù)必須傳遞,值允許為空
??表示該參數(shù)非必須,如果不傳則默認為0
??getPageData(@RequestParam(name="pageNum",defaultValue="0")?String?pageNo,?String?pageSize)

@PathVariable

is used to map template variables in the request URL Go to the parameters of the function processing method, that is, take out the variables in the uri template as parameters
Applicable: method parameters

Attributes

value: Specify the url template variable name, if the name is the same as the method parameter If the names are different, they need to be specified, otherwise they can be omitted.

????@RequestMapping("/index/{id}")
?????????public?String?index(@PathVariable("id")?String?sdf){
???????????System.out.println(sdf);
???????????return?"index";
?????}

@ResponseBody

This annotation is used to pass the appropriate to the object returned by the Controller method. After HttpMessageConverter is converted to the specified format, it is written to the body data area of ??the Response object. By default, springmvc is returned in the form of json (Use jackson converter)
Applicable: method, when the data returned is not a page with html tags, but data in some other format (such as json, xml, etc.), use
to compare: @RequestBody Convert the HTTP request body to a suitable HttpMessageConverter object
@ResponseBody Return the content or object as the HTTP response body, and call the Adapter conversion object suitable for HttpMessageConverter, write Output stream

@RequestBody

1. This annotation is used to read the body part of the Request request, parse it using the system's default configured HttpMessageConverter, and then bind the corresponding data to the object to be returned. on the object
2. Then bind the object data returned by HttpMessageConverter to the parameters of the method in the controller
Applicable: method parameters, for the Content-Type of the request: application/json, application/xml must use this Note
For application/x-www-form-urlencoded, if the request method is put, it is required,
It is optional for POST/GET method (that is, it is not necessary, because @RequestParam, @ModelAttribute can also be processed)
For multipart/form-data, @RequestBody cannot handle data in this format
Attribute: required: Whether it is required, the default is true, indicating that the request must have corresponding parameters, otherwise an exception will be thrown
Example: Usually the front-end using this annotation sends an ajax request, then the request part is as follows:

?????????$.ajax({
???????????type:?"POST",
???????????url:"/role/saveRole",
???????????contentType:"application/json",
???????????data:?JSON.stringify(_self.form)...

Note: contentType cannot be omitted, data must be converted into a json string through stringify
Then the corresponding The method can be written like this:

@RequestMapping(value?=?"/saveRole",method?=?RequestMethod.POST)
public?String?saveRole(@RequestBody?People?requestJson)?{}

If the front-end passes an array of objects, the backend can also use List to accept it directly. This is the most practical way to bind List data

@CookieValue

You can bind the cookie value in the Request header to the parameters of the method
Applicable to: method parameters

獲取cookie中的JSESSIONID
public?String?index(@CookieValue("JSESSIONID")?String?cookie){}

@RequestHeader

You can bind the Request The value of the request header part is bound to the parameters of the method
Applicable to: method parameters

獲取請求中Accept-Encoding值,返回gzip,?deflate,?br
public?String?index(@RequestHeader("Accept-Encoding")?String?host){return?host;}

@ExceptionHandler

注解在方法上,表示該方法用于處理特定的異常,處理范圍是當前類,如果想要全局捕獲異常,需要使用@ControllerAdvice
當一個Controller中有多個HandleException注解出現(xiàn)時,那么異常被哪個方法捕捉呢?這就存在一個優(yōu)先級的問題
ExceptionHandler的優(yōu)先級是:在異常的體系結構中,哪個異常與目標方法拋出的異常血緣關系越緊密,就會被哪個捕捉到
屬性:value: 需要處理的異常類型集合(Class)
在當前Controller有兩個處理異常的方法,當訪問/index時,頁面顯示: json data

package?com.rxy.controller;

@Controller
public?class?HelloController?{
????
????@ExceptionHandler({?ArithmeticException.class?})
????@ResponseBody
????public?String?handleArithmeticException(Exception?e)?{
????????e.printStackTrace();
????????return?"json?data";
????}
????
????@ExceptionHandler({?IOException.class?})
????public?String?handleIOException(Exception?e)?{
????????e.printStackTrace();
????????//返回錯誤頁面
????????return?"error";
????}

????@RequestMapping("/index")
????public?String?index(){
????????int?i?=?10?/?0;
????????return?"index";
????}

}

The above is the detailed content of The use of 5 commonly used annotations in springmvc. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

What are the differences between SpringBoot and SpringMVC? What are the differences between SpringBoot and SpringMVC? Dec 29, 2023 am 10:46 AM

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

What are the differences between spring and springmvc What are the differences between spring and springmvc Dec 29, 2023 pm 05:02 PM

The difference between spring and springmvc: 1. Positioning and functions; 2. Core functions; 3. Application areas; 4. Extensibility. Detailed introduction: 1. Positioning and functions. Spring is a comprehensive application development framework that provides dependency injection, aspect-oriented programming, transaction management and other functions. It is designed to simplify the development of enterprise-level applications, and Spring MVC is the Spring framework. A module in it is used for the development of Web applications and implements the MVC pattern; 2. Core functions and so on.

What is the difference between SpringBoot and SpringMVC? What is the difference between SpringBoot and SpringMVC? Dec 29, 2023 pm 05:19 PM

SpringBoot and SpringMVC are two frameworks commonly used in Java development. They are both provided by the Spring framework, but they have some differences in functions and usage methods. This article will introduce the characteristics and differences of SpringBoot and SpringMVC respectively. 1. Features of SpringBoot: Simplified configuration: SpringBoot greatly simplifies the project configuration process through the principle of convention over configuration. It can automatically configure the parameters required by the project, and developers

What are the differences between springboot and springmvc What are the differences between springboot and springmvc Jun 07, 2023 am 10:10 AM

The differences between springboot and springmvc are: 1. Different meanings; 2. Different configurations; 3. Different dependencies; 4. Different development times; 5. Different productivity; 6. Different ways to implement JAR packaging function; 7. Whether batch processing is provided Function; 8. Different functions; 9. Different community and documentation support; 10. Whether deployment descriptors are required.

How to use Java's SpringMVC interceptor How to use Java's SpringMVC interceptor May 13, 2023 pm 02:55 PM

The role of interceptor SpringMVC's interceptor is similar to the filter in Servlet development, which is used to pre-process and post-process the processor. Interceptors are connected into a chain in a certain order, and this chain is called an interceptor chain (InterceptorChain). When an intercepted method or field is accessed, the interceptors in the interceptor chain will be called in the order they were previously defined. Interceptors are also the specific implementation of AOP ideas. The difference between interceptors and filters: Filter (Filter) The scope of use of interceptor (Intercepter) is part of the servlet specification and can be used by any JavaWeb project. Spri

Compare the similarities and differences between SpringBoot and SpringMVC Compare the similarities and differences between SpringBoot and SpringMVC Dec 29, 2023 am 08:30 AM

Analyzing the similarities and differences between SpringBoot and SpringMVC SpringBoot and SpringMVC are very important development frameworks in the Java field. Although they are both part of the Spring framework, there are some obvious differences in usage and functionality. This article will compare SpringBoot and SpringMVC and analyze the similarities and differences between them. First, let's learn about SpringBoot. SpringBo

Using SpringMVC for Web service processing in Java API development Using SpringMVC for Web service processing in Java API development Jun 17, 2023 pm 11:38 PM

With the development of the Internet, Web services are becoming more and more common. As an application programming interface, JavaAPI is constantly launching new versions to adapt to different application scenarios. As a popular open source framework, SpringMVC can help us easily build web applications. This article will explain in detail how to use SpringMVC for Web service processing in JavaAPI development, including configuring SpringMVC, writing controllers, and using

See all articles