当前位置:网站首页>@Detailed explanation of requestmapping usage
@Detailed explanation of requestmapping usage
2022-07-29 07:29:00 【A salted fish..】
List of articles
Tips : The following is the main body of this article ,Java The series of learning will be continuously updated
@RequestMapping brief introduction
stay Spring MVC in ,@RequestMapping The purpose of the annotation is to associate the request with the controller method that processes the request , Establish a mapping relationship .
@RequestMapping It can modify classes , You can also modify methods . When decorating classes and methods , The access address is class + Method .
Take a look at the source code :
// Target These two attributes in represent @RequestMapping Annotations can be used on methods and classes
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
String name() default "";
String[] value() default {
};
String[] path() default {
};
RequestMethod[] method() default {
};
String[] params() default {
};
String[] headers() default {
};
String[] consumes() default {
};
String[] produces() default {
};
}
@RequestMapping In addition to name() Outside the returned string , There are seven properties .
| Property name | Attribute specification |
|---|---|
| value、path | Specify the requested url Address .value and path It's the same thing , They can replace each other .value Is the default property , therefore @RequestMapping(value=“/example”) and @RequestMapping(“/example”) It is equivalent. . |
| method | Specify the requested method type , GET( check )、POST( increase )、PUT( Change )、DELETE( Delete ) etc. |
| params | Appoint request Some parameter values must be included in , To be handled by this method . |
| headers | Appoint request Some of the specified header value , To have the method process the request . |
| consumes | Specifies the submitted content type to process the request (Content-Type), for example application/json, text/html; |
| produces | Specify the type of content returned , Only when the request In the request header (Accept) The specified type is included in the type to return ; |
1. value attribute
value Property matches the request mapping by the request address of the request .valuel Property is an array of string types , Indicates that the request mapping can match the request corresponding to multiple request addresses ,value Property must be set .
1-1 Use a : Simple jump html page
@Controller // Must use Controller annotation
public class Demo1 {
// Routing rule registration : Visit the address of the page
@RequestMapping("/test1")
public String sayTest1() {
// Jump to templates Under the demo2.html
return "demo2";
}
}
// Access address : http://localhost:8080/test1
perhaps
@Controller // Must use Controller annotation
@ResponseBody // Return to one text/html Information ( Non view file )
public class Demo2 {
// Routing rule registration : Visit the address of the page
@RequestMapping("/test2")
public String sayTest2() {
return "<h1>hello,this is Test</h1>";
}
}
// Access address : http://localhost:8080/test2
1-2 Use two : Jump html page + Model Data binding
1. First you have to create a data entity class
import lombok.Data;
// @Data Annotations in lombok Next , Can save code space
// With @Data annotation , We don't need to write it manually get、set、toString And the construction method , It has these methods built in
@Data
public class Student {
private final String name;
private final String brief;
private final String birthday;
}
2. Create a view file (just-a-view.html), Internal custom data object
<!DOCTYPE html>
<html lang="zh-hans">
<head>
<meta charset="UTF-8">
<title> Just a view file | It is actually a template file </title>
</head>
<body>
<h1 th:text="${person.name}"> The content here will be replaced </h1>
<p th:text="${person.brief}"> The content here will be replaced </p>
<p th:text="${person.birthday}"> The content here will be replaced </p>
</body>
</html>
3. after Controller Conduct Model Data binding
@Controller
public class DemoController {
// Support all HTTP Method ,@RequestMapping The default is get Method request
@RequestMapping("/hello")
public String hello(Model model) {
Student student = new Student(" Zhang San ", " I am Zhang San. , I'm pleased to meet you ", "2000-07-26");
// Forward data , It can be transferred to , Through the expression ${} Can be obtained
model.addAttribute("person", student);
return "just-a-view";
}
}
// Access address : http://localhost:8080/hello
2. method attribute
@RequestMapping Medium method It is mainly used to define what kind of requests are received from the browser .
Http The specification defines a variety of ways to request resources , There are four basic , Respectively :GET( check )、POST( increase )、PUT( Change )、DELETE( Delete ), and URL Then it is used to locate resources on the network, which is equivalent to the function of address , Cooperate with four request modes , Can realize the right URL Add, delete, modify and query the corresponding resources .
2-1 Process through GET A request sent by
@Controller
public class UserController1 {
// Only support GET Method
@RequestMapping(value = "/login1", method=RequestMethod.GET)
public String login1() {
return "success";
}
// It can be abbreviated as
@GetMapping("/login2")
public String login2() {
return "success";
}
}
// Access address : http://localhost:8080/login1
At this time , If the request from the browser is not GET Words , You will receive an error prompt returned by the browser , That is, you have to link .
2-2 Process through POST A request sent by
@Controller
public class UserController2 {
// Only support POST Method
@PostMapping("/login3")
public String login3() {
return "success";
}
}
At this time , The request must be sent in the form , Otherwise, you will receive an error prompt returned by the browser
<form action="user/login" method="post">
<input type="submit" value=" Use Post Send a request "/>
</form>
2-3 Processing multiple requests
@Controller
public class UserController3 {
// Support HTTP GET and POST Method
@RequestMapping(value = "/login4", method = {
RequestMethod.GET, RequestMethod.POST})
public String login4() {
return "success";
}
}
3. params attribute
params Attribute represents the request parameter , That is, add in URL Key value pairs on , Multiple request parameters are expressed in & separate .
Defining entity classes :
@Data
public class Cat {
public final String name;
public final int age;
}
Unwanted params Properties :
@Controller
public class ParamsController {
@GetMapping("/cat1")
@ResponseBody
public Cat createCat() {
// The return object will be JSON Output after sequence
return new Cat(" kitten ", 3);
}
}
// Access address : http://localhost:8080/cat1
// Web results :{"name":" kitten ","age":3}
3-1 Request parameters are attribute values
@Controller
public class ParamsController {
@GetMapping("/cat2")
@ResponseBody
public Cat createCat2(String name, String age) {
return new Cat(name, age);
}
// Type the address : http://localhost:8080/cat3?name= millet &age=6
@GetMapping(value = "cat3", params={
"name= millet ","age=4"})
@ResponseBody
public Cat createCat3(String name, String age) {
return new Cat(name, age);
}
// Fixed address : http://localhost:8080/cat3?name= millet &age=6
}
3-2 Request parameters are objects
@Controller
public class ParamsController {
@GetMapping("/cat4")
@ResponseBody
public Cat createCat4(Cat cat) {
// You can request directly with objects . As long as you can pass parameters correctly ,Spring Objects are constructed internally
return cat;
}
}
// Type the address : http://localhost:8080/cat3?name= millet &age=6
4. headers attribute
adopt @RequestMapping Medium headers attribute , You can restrict requests from clients
@Controller
public class HeadersController {
// It means to receive only requests from the local machine
@RequestMapping(path = "/login", headers="Host=localhost:8080")
public String login() {
return "success";
}
}
5. produces attribute
produces Property specifies the content type returned , Only when the request In the request header (Accept) The specified type is included in the type to return .
public class DemoController {
// Specify the output format as text, Font is utf-8
@RequestMapping(value = "/hello", produces = "text/plain; charset=utf-8")
@ResponseBody
public String hello(@RequestParam(value = "target", defaultValue = " The world ") String target) {
// Set up target The default value is “ The world ”, If the request specifies target Value , Then the specified value is output
return " Hello , " + target;
}
}
// Type the address : http://localhost:8080/hello
// Output results : Hello , The world
// Type the address : http://localhost:8080/hello?target= millet
// Output results : Hello , millet
summary
Begin to learn Spring It's been a week , My feeling is that it is difficult to start . You don't need to know the principle of a framework to use it , This really saves a lot of trouble for development . But for beginners , It's really difficult , Because there are too many things in it , If there is no accumulation of time , It's hard for you to know so many tools in a short time , Let alone understand the principle .
But it will be normal ,“ Everything is difficult at the beginning ”. All we can do is work hard slowly . This article is just a summary of the beginner , The follow-up needs to be constantly supplemented and improved !!!
summary :
Tips : Here is a summary of the article :
The above is today's learning content , This article is about SpringMVC Learning from , I know another annotation @RequestMapping, And learned its various uses . After that, the learning content will be continuously updated !!!
边栏推荐
- 09 bloom filter
- Gin routing, parameters, output
- [OpenGL] use of shaders
- 利用C语言巧妙实现棋类游戏——三子棋
- Segger's hardware anomaly analysis
- 信用卡购物积分
- CDC source can quit after reading MySQL snapshot split
- Thinkphp6 realizes database backup
- Gin parameter validation
- [summer daily question] Luogu p6320 [coci2006-2007 4] sibice
猜你喜欢

thinkphp6 实现数据库备份

WPF interface layout must know basis
Scala higher order (IX): pattern matching in Scala

PAT甲级 1146 拓扑顺序

How to establish EDI connection with Scania in Scania?

CMOS芯片制造全工艺流程

1 - background project construction

女研究生做“思维导图”与男友吵架!网友:吵架届的“内卷之王”....

QT专题:基础部件(按钮类,布局类,输出类,输入类,容器类)

Prometheus与Grafana
随机推荐
Thinkphp6 realizes database backup
Scala higher order (IX): pattern matching in Scala
Round avatar of user list and follow small blocks
1 - background project construction
女研究生做“思维导图”与男友吵架!网友:吵架届的“内卷之王”....
1-后台项目搭建
[OpenGL] use of shaders
【暑期每日一题】洛谷 P6320 [COCI2006-2007#4] SIBICE
【WPF】通过动态/静态资源实现语言切换
亚马逊云助手小程序来啦!
Leetcode 209. subarray with the smallest length (2022.07.28)
Other basic monitoring items of ZABBIX
如何与斯堪尼亚SCANIA建立EDI连接?
Getting started with JDBC
计算程序运行时间 demo
Summer summary (II)
Description of rollingfileappender attribute in logback
Error 1045 (28000) access denied for user 'root' @ 'localhost' solution
Meta configuration item of route
ef core 读取text类型慢_ef core读取大字符串字段慢