接受参数以及数据回显
User.java
在上一节的aaoo例子中,新建一个com.pojo包,在包新建一个实体类
package com.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
UserController.java
在实际开发中,我们还有Dao,跟Service层的代码需要写,这里就直接省略。
package com.controller;
import com.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/user")
public class UserController {
/*
接受基本数据类型的参数
@RequestParam("id"),规定前端的参数名称,必须传localhost:8080://select?id=?,
如果传别的,则找不到,一般如果声明的参数 int id与前端传的id一直的话,可以省略该注解
但不建议省略,给每个前端要传的参数都加上。
*/
@RequestMapping("/select")
public String select(@RequestParam("id") int id, Model model) {
//省略了原生Servlet中,用req.getRequestParam......获取参数
System.out.println("前端接受的参数为" + id);
/*
调用业务层Dao层执行查询业务,这里省略。
*/
//将返回的结果传递给前端,即数据回显的方式
model.addAttribute("msg", "您查询的id为:" + id + ",未查询到相关结果");
//转发到相关视图
return "hello";
}
/*
注意,前端的参数名必须和实体类中的属性名称一致,如果不一致,则返回null
*/
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(User user, ModelMap model) {
/*数据回显的第二种方式,ModelMap
它继承了LinkedHashMap,属于Model的加强版,
* */
model.addAttribute("msg", user.toString());
return "hello";
}
}
测试: