SpringMVC的Restful风格

RestFul风格

概念

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

功能

资源:互联网所有的事物都可以被抽象为资源

资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。

分别对应 添加、 删除、修改、查询。

传统方式操作资源:

http://localhost/item?id=1

RESTFUL风格

http://localhost/item/1

测试:

环境我这里就不在一一搭建了,可以看上个博客

代码:

@Controller
public class HelloController {
    @GetMapping("/sum/{a}/{b}")
    public String getSum(@PathVariable String a,@PathVariable String b, Model model){
        String sum = a+b;
        model.addAttribute("msg",sum);
        return "hello";
    }
}

这样在浏览器就可以这样请求了:sum/1/2

页面跳转方式:

基于视图解析器存在的情况

1.页面转发

    @GetMapping("/test")
    public String forward( Model model){
        model.addAttribute("msg","hello,SpringMVC");
        // 转发
        return "hello";
    }

2.重定向

    @GetMapping("/test2")
    public String redirect(){
        // 重定向
        return "redirect:/index.jsp";
    }

扩展:

如果没有使用Restful风格,可能出现的传参问题

例如:

    @GetMapping("/test3")
    public String redirect(int num, Model model){
        model.addAttribute("msg",num);
        return "hello";
    }

传参必须与num名字一致,否则会报错,例:/test3/username=3,这是错误的写法,但是如果我们想用username怎么办,这里引入一个注解:

@RequestParam

public String redirect(@RequestParam("username") int num, Model model)

这样就规定参数名字必须要为注解里面的值,一般在开发中,我们都是需要加上这个注解的。

posted @   JamieChyi  阅读(11)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示