接受请求参数
1、提交的域名称和处理方法的参数名一致
提交数据:http://localhost:8080/hello?name=stitch
处理方法
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
后台输出:stitch
2、提交的域名称和处理方法的参数名不一致
提交数据:http://localhost:8080/hello?username=stitch
处理方法:
//@RequestParam("username") : username提交的域的名称
@RequestMapping("/hello")
public String hello(@RequsestParam("username") String name){
System.out.println(name);
return "hello";
}
后台输出:stitch
3、提交的是一个对象
要求提交的表单域和提交对象的属性名一致,接收参数使用对象即可。
(1)实体类
package indi.stitch.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int id;
private int age;
}
(2)提交数据:http://localhost:8080/user/t2?name=stitch&id=1&age=18
(3)处理方法:
@GetMapping("/t2")
public String test2(User user) {
System.out.println(user);
return "test";
}
注意:如果使用对象,前端提传递的参数名和对象名必须一直,否则接收到的参数为null.
数据显示到前端
1、ModelAndView
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "ControllerTest1");
mv.setViewName("test");
return mv;
}
2、Model
@RequestMapping("/m1/t1")
public String test(Model model) {
model.addAttribute("msg", "ModelTest1");
return "/WEB-INF/jsp/test.jsp";
}
3、ModelMap
@GetMapping("/t3")
public String test3(ModelMap modelMap) {
modelMap.addAttribute("msg", "testModelMap");
return "test";
}