4.0、springmvc-Restful风格的实现

4.0、springmvc-Restful风格的实现

前端url 携带参数格式如下:

'/add/'+a+'/'+b

RestfulController.java文件

package com.hkl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class RestfulController {
    @GetMapping("/add/{a}/{b}")
    public String add(@PathVariable int a, @PathVariable int b, Model model) {
        int msg = a + b;
        model.addAttribute("msg",msg);
        return "hello";
    }
    @PostMapping("/add/{a}/{b}")
    public String add2(@PathVariable int a, @PathVariable int b, Model model) {
        int msg = a + b;
        model.addAttribute("msg",msg);
        return "hello";
    }
}

使用Restful风格编码的优点:

·代码简洁

·代码高效

·代码安全性得到提升

使用时注意一下几点即可:

        ·在方法上加上@GetMapping注解即表示该方法通过Get的方式访问@PostMapping则表示

post方式访问。当然还有其他几种访问的方式但是使用的最多的就是Get和Post方式。也可以使用

@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.POST)这种方式来设置访问方式。

        ·@PathVariable表示路径变量,在方法的形参前加上该注解,即可使用"/add/{a}/{b}"这种方

式来传递参数,这样在前端页面的url路径中不会暴露代码的参数是什么,安全性大大提高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值