怎样调用RequestMapping
时间: 2023-11-21 14:51:11 浏览: 10
要调用RequestMapping,需要在Spring MVC的控制器类中定义一个方法,并在该方法上添加@RequestMapping注解。例如:
```
@Controller
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
```
在上面的例子中,我们定义了一个控制器类MyController,并在其中定义了一个方法hello()。该方法上添加了@RequestMapping注解,表示当用户访问/hello路径时,会调用该方法。
相关问题
RequestMapping
@RequestMapping是Spring MVC框架中的注解之一,用于将HTTP请求映射到特定的处理方法(即控制器中的方法)。它可以用于类级别和方法级别。在类级别上使用@RequestMapping将为该类中的所有请求路径提供基本请求映射。而在方法级别上使用@RequestMapping,则可以将特定的请求路径映射到该方法。
例如,以下代码演示了如何在类级别上使用@RequestMapping:
```
@Controller
@RequestMapping("/example")
public class ExampleController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
```
在上述示例中,我们将@RequestMapping注解应用于类级别,这意味着该类中的所有映射方法都将以“/example”作为基本URL。此外,我们还将@RequestMapping注解应用于sayHello()方法,将其映射到“/example/hello”路径。因此,当请求“/example/hello”时,控制器将调用sayHello()方法并返回“Hello, World!”字符串。
@RequestMapping使用
@RequestMapping是Spring MVC框架中的注解,用于将请求映射到控制器的处理方法上。通过在方法上添加@RequestMapping注解,可以指定请求的URL路径、请求方法、请求参数、请求头等信息,从而匹配到对应的处理方法进行处理。例如:
```java
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public String getUser(@RequestParam("id") int id) {
User user = userService.getUserById(id);
return user.toString();
}
}
```
上面的代码中,@Controller注解表示该类是一个控制器,@RequestMapping注解指定了请求的URL路径为"/user",getUser方法使用@RequestMapping注解指定了请求的URL路径为"/get",请求方法为GET,请求参数为"id"。当用户请求"/user/get?id=1"时,就会调用getUser方法,传入id=1的参数,并返回对应的User对象的字符串表示。