您好,登录后才能下订单哦!
SpringBoot2中Controller接收参数的方式是怎样的,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
地址传值
@PathVariable
获取路径参数。即url/{id}这种形式。
? 传值
@RequestParam
获取查询参数。即url?name=这种形式
用注解@RequestParam绑定请求参数到方法入参
当请求参数username不存在时会有异常发生,可以通过设置属性required=false解决,例如: @RequestParam(value=“username”, required=false)
Body参数
//application/jason
@PostMapping(path = “/demo1”)
public void demo1(@RequestBody Person person) {
无注解(form提交)
//form-data
@PostMapping(path = “/demo1”)
public void demo1(Person person) {
请求头参数以及Cookie
@RequestHeader
2、@CookieValue
例子
java代码:
@GetMapping("/demo3")
public void demo3(@RequestHeader(name = “myHeader”) String myHeader,
@CookieValue(name = “myCookie”) String myCookie) {
System.out.println(“myHeader=” + myHeader);
System.out.println(“myCookie=” + myCookie);
也可以这样
@GetMapping("/demo3")
public void demo3(HttpServletRequest request) {
System.out.println(request.getHeader(“myHeader”));
for (Cookie cookie : request.getCookies()) {
if (“myCookie”.equals(cookie.getName())) {
System.out.println(cookie.getValue());
//请求头参数以及Cookie
@RequestMapping("request5")
public String test5(@RequestHeader(name ="Header") String Header,
@CookieValue(name ="cookie1") String cookie1,
@CookieValue(name ="cookie2") String cookie2){
return "Header:"+Header+"cookie1:"+cookie1+"cookie2"+cookie2;
}
//Cookie
@GetMapping("/ee")
public String ee(@RequestHeader(name="myHeader") String myHeader,@CookieValue(name="myCookie") String myCookie){
System.out.println("myHeader=" + myHeader);
System.out.println("myCookie=" + myCookie);
return "---------"+myHeader+"============="+myCookie;
}
表单的参数写在Controller相应的方法的形参中
适用于get方式提交,不适用于post方式提交。
/**
* 1.直接把表单的参数写在Controller相应的方法的形参中
* @param username
* @param password
* @return
*/
@RequestMapping("/addUser1")
public String addUser1(String username,String password) {
System.out.println(“username is:”+username);
@ModelAttribute注解获取POST请求的FORM表单数据
/**
* 使用@ModelAttribute注解获取POST请求的FORM表单数据
* @param user
* @return
*/
@RequestMapping(value="/addUser5",method=RequestMethod.POST)
public String addUser5(@ModelAttribute(“user”) UserModel user) {
System.out.println(“username is:”+user.getUsername());
System.out.println(“password is:”+user.getPassword());
return “demo/index”;
测试代码
Controller
package com.zz.controller;
import java.util.HashMap;
import java.util.Map;
import com.zz.entity.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("test")
public class TestController {
//路径传值
@RequestMapping("t1/{p1}")
public Map t1(@PathVariable("p1") String paramter1){
Map map=new HashMap();
map.put("rs",paramter1);
return map;
}
//? 传值
@RequestMapping("t2")
public Map t2(@RequestParam("p1") String paramter1)
{
System.out.println(paramter1);
Map map=new HashMap();
map.put("rs",paramter1);
return map;
}
//Body参数
//application/jason
@RequestMapping("t3")
public Map t3(@RequestBody User person){
Map map=new HashMap();
map.put("rs",person.getName());
return map;
}
// 无注解(form提交)
//form-data
@RequestMapping("t4")
public Map t4(User person){
Map map=new HashMap();
map.put("rs",person.getName());
return map;
}
// 请求头参数以及Cookie
@RequestMapping("t5")
public Map t5(@RequestHeader(name ="myHeader") String myHeader,
@CookieValue(name = "myCookie") String myCookie){
System.out.println("myHeader=" + myHeader);
System.out.println("myCookie=" + myCookie);
Map map=new HashMap();
map.put("rs",myHeader);
return map;
}
// 表单的参数写在Controller相应的方法的形参中
// 适用于get方式提交,不适用于post方式提交。
@RequestMapping("t6")
public Map t6(String name,String pwd){
Map map=new HashMap();
map.put("rs",name);
return map;
}
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 实例</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>测试</h3>
<button type="button" id="t1" class="btn">t1</button>
<button type="button" id="t2" class="btn btn-primary">t2</button>
<button type="button" id="t3" class="btn btn-secondary">t3</button>
<button type="button" id="t4" class="btn btn-success">t4</button>
<button type="button" id="t5" class="btn btn-info">t5</button>
<button type="button" id="t6" class="btn btn-warning">t6</button>
</div>
<script>
$(document).ready(function(){
// 在这里写你的代码...
$("#t1").click(function(){
$.get("test/t1/jacky", function(data){
alert("Data Loaded: " + data.rs);
});
})
$("#t2").click(function(){
$.get("test/t2?p1=jerry", function(data){
alert("Data Loaded: " + data.rs);
});
})
$("#t3").click(function(){
var data = {"name" :"petter","pwd" : "123"}
$.ajax({
url : "test/t3",
async : false,
type : "POST",
contentType : 'application/json',
dataType : 'json',
data :JSON.stringify(data),
success : function(data) {
alert("Data Loaded: " + data.rs);
}
});
})
$("#t4").click(function(){
var data = {"name" :"petter","pwd" : "123"}
$.ajax({
url : "test/t4?name=jacky",
async : false,
type : "POST",
contentType : 'form-data',
success : function(data) {
alert("Data Loaded: " + data.rs);
}
});
})
// 暂时不通
$("#t5").click(function(){
var data = {"name" :"petter","pwd" : "123"}
$.ajax({
url : "test/t5",
async : false,
type : "POST",
contentType : 'application/json',
dataType : 'json',
headers: {
'Header':"from header",
'Cookie':'sdfs'
},
data :JSON.stringify(data),
success : function(data) {
alert("Data Loaded: " + data.rs);
}
});
})
$("#t6").click(function(){
$.get("test/t6?name=jerry&pwd=234", function(data){
alert("Data Loaded: " + data.rs);
});
})
});
</script>
</body>
</html>
SpringBoot Form post 提交 跳转失败 解决办法
报错日志:tSupportedException: Request method ‘POST’ not supported
解决:post controller方法里面 通过 return “redirect:/index/toIndex”; 执行get的跳转controller
package com.zz.controller;/**
* @Description: 描述
* @Author: Bsea
* @CreateDate: ${Date}
*/
import com.zz.config.DataValidationException;
import com.zz.entity.Member;
import com.zz.form.MemberForm;
import com.zz.service.MemberService;
import com.zz.util.FormUtil;
import com.zz.util.ResultVOUtil;
import com.zz.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
/**
* @Description: java类作用描述
* @Author: Bsea
* @CreateDate: 2019/10/16$ 21:27$
*/
@Api(value = "会员控制器")
@Controller
@RequestMapping("index")
public class IndexController {
@Resource
MemberService memberService;
@ApiOperation(value = "添加会员", notes = "根据名字查找会员")
@ApiImplicitParam(name = "name", value = "会员名字", required = true, dataType = "String",paramType = "path")
@PostMapping("add")
public String add(@Valid MemberForm member, BindingResult bindingResult){
System.out.println(member);
if(bindingResult.hasErrors()){
throw new DataValidationException("验证错误");
}
Member member1=new Member();
BeanUtils.copyProperties(member,member1);
if(memberService.add(member1)!=null){
return "redirect:/index/toIndex";
}else{
return "redirect:/index/toIndex";
}
}
@RequestMapping("toIndex")
public String toIndex(){
return "/index2.html";
}
}
关于SpringBoot2中Controller接收参数的方式是怎样的问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。