数据处理
提交数据
1、提交的域名称和处理方法的参数名一致
提交数据 : http://localhost:8080/hello?name=allen
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
输出
allen
2、提交的域名称和处理方法的参数名不一致
提交数据 : 请求地址为: localhost:8080/user/test1?username=allen
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
输出
allen
3、提交的是一个对象
实体类 User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private int age;
}
提交数据 : 请求地址为:http://localhost:8080/user/test2?id=1&name=tsdk&age=18
处理方法 :
//请求地址为: localhost:8080/user/test2?id=1&name=tsdk&age=18
//注意:前端请求参数与实体类字段名必须一致,否则无法匹配前端请求参数,默认为null
@GetMapping("/test2")
public String test2(User user){
//1.接受前端参数, 输出在 console
System.out.println(user);
//2.视图跳转
return "test";
}
注意:前端请求参数与实体类字段名必须一致,否则无法匹配前端请求参数,默认为null
回显数据
1、通过ModelAndView
实现 Controller 接口
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
返回 ModelAndView
@Controller
public class ControllerMV {
//请求地址: localhost:8080/test1
@RequestMapping("/test1")
public ModelAndView test(ModelAndView mv){
mv.addObject("msg","hello, mv");
mv.setViewName("test");
return mv;
}
}
2、通过Model
@Controller //代表这个类会被Spring接管
//被@Controller注解的类中的所有方法,如果返回值是String,并且有具体页面可以跳转,那么就会被视图解析器解析到
public class ControllerTest2 {
@RequestMapping("/t2")
public String test(Model model){
model.addAttribute("msg","test2");
return "test";
}
//可以实现 test.jsp 复用,即视图复用
@RequestMapping("/t3")
public String test3(Model model){
model.addAttribute("msg","test3");
return "test";
}
}
3、通过ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}