springboot学习随笔(三):Controller参数映射

时间:2022-02-16 15:44:36

接上章内容,我们看看浏览器参数如何映射到我们的Controller层

我们新建UserController和User实

springboot学习随笔(三):Controller参数映射

User.java

package com.example.main;

import java.io.Serializable;

public class User implements Serializable {

    /**
*
*/
private static final long serialVersionUID = -7359143284242091031L; private Long id;
private String name;
private Integer age; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} }

UserController.java

package com.example.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.example.main.User; @RestController
public class UserController { @RequestMapping("/user")
public User user(Long id,String name,int age){
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(18);
return user;
}
}

参数映射的方式有三种:

第一种:参数映射

@RestController
public class UserController { @RequestMapping("/user")
public User user(Long id,String name,int age){
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
return user;
}
}
在浏览器访问,携带参数
springboot学习随笔(三):Controller参数映射

第二种:对象映射

  

@RequestMapping("/user")
public User user(User user){
return user;
}
在浏览器访问,携带参数

springboot学习随笔(三):Controller参数映射

第三种:通过ServletRequest对象

@RequestMapping("/user")
public User user(ServletRequest request){
Long id=Long.valueOf(request.getParameter("id"));
String name =request.getParameter("name");
int age =Integer.parseInt(request.getParameter("age")) ;
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
return user;
}

springboot学习随笔(三):Controller参数映射