【SpringMVC】SpringMVC中@RequestMapping 注解的相关用法。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/example")
public class ExampleController {
// 处理GET请求
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody String handleGetRequest() {
return "Received GET request";
}
// 处理POST请求
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody String handlePostRequest() {
return "Received POST request";
}
// 处理PUT请求
@RequestMapping(method = RequestMethod.PUT)
public @ResponseBody String handlePutRequest() {
return "Received PUT request";
}
// 处理DELETE请求
@RequestMapping(method = RequestMethod.DELETE)
public @ResponseBody String handleDeleteRequest() {
return "Received DELETE request";
}
}
这个例子中,我们定义了一个控制器ExampleController
,它使用@RequestMapping
注解来处理对/example
路径的不同HTTP请求方法。@ResponseBody
注解被用来指示Spring MVC将返回的字符串直接写入HTTP响应体,而不是解析为视图名称。这样,我们可以根据请求类型返回不同的响应,展示了如何在Spring MVC中处理不同的HTTP方法。
评论已关闭