2.1.3 url传递参数的三种方式
URL请求参数传递
原SupController代码:
点击展开代码
package com.example.mystore.controller;
import org.springframework.ui.Model; // 必须是这个!
import com.example.mystore.core.Result;
import com.example.mystore.entity.Supplier;
import com.example.mystore.service.SupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class SupController {
@Autowired
private SupService supService;
@GetMapping("/index")
public String init(Model model){
Result result = new Result();
result.setCode(100);
result.setMsg("初始状态");
model.addAttribute("result",result);
return "index";
}
@RequestMapping("/check")
public String loginCheck(Model model, Supplier supplier){
model.addAttribute("scode",supplier.getScode());
model.addAttribute("spassword",supplier.getSpassword());
Result result = supService.checkSupplier(supplier);
model.addAttribute("result",result);
if (result.getCode() == 200) {
Supplier supObj = (Supplier) result.getData();
model.addAttribute("sname", supObj.getSname());
model.addAttribute("sweixin", supObj.getSweixin());
model.addAttribute("tel", supObj.getTel());
return "home";
}else return "index";
}
}
1.形参名(无注解)接收参数
(1)控制器编程
修改控制器SupController,代码如下
1 |
|
(2)运行
启动项目,打开浏览器,在地址栏中输入http://localhost:8080/index/check?scode=SXLC001A&&spassword=888
(3)说明
1.要求url传递参数名与控制器方法的参数名必须一致
2.参数与路径中间隔一个?,各参数之间用&&或&分隔
3.@RequestMapping(“/check”)可用以下形式代替
@RequestMapping(value = “check” ,method = RequestMethod.GET)
@GetMapping(“/check”)
@GetMapping(value = “check”)
2.路径(@PathVariable)传递参数
(1)控制器编程
在SupController类中添加loginCheckbyPath方法
1 | //路径@PathVariable传递参数 |
(2)运行
启动项目,在浏览器地址栏中输入http://localhost:8080/index/checkbypath/SXLC001A/888
3.用@RequestParam映射参数
(1)控制器编程
在SupController类中添加loginCheckByPara方法
1 | //使用@RequestParam映射参数 |
(2)运行
启动项目,在浏览器地址栏中输入http://localhost:8080/index/checkbypara?scode=SXLC001A
省略密码回车
4.总结
通过url传递参数有三种方式,一种是直接通过url传递参数,第二种是直接通过路径传递参数,第三种是支持参数映射和默认值的参数传递
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 star!