天天看点

SpringMVC数据的处理

1.提交数据的处理

  a)提交的域名名称和处理方法参数一致即可。

   提交的数据:

   http://localhost:8080/06springmvc_data/hello.do?name=zhangsan

   处理方法:

@RequestMapping("/hello")
	public String hello(String name){
		System.out.println(name);
		return "index.jsp";
	}      

  b)如果域名名称和处理方法参数不一致。

   http://localhost:8080/06springmvc_data/hello.do?uname=lisi

@RequestMapping("/hello")
public String hello(@RequestParam("uname")String name){
    // @RequestParam("uname") uname是提交的域的名称
	System.out.println(name);
	return "index.jsp";
}      

  c)如果提交的是一个对象

   要求提交的表单域名和对象的属性名一致,参数使用对象即可。

   http://localhost:8080/06springmvc_data/user.do?name=liubei&pwd=1234

@RequestMapping("/user")
	public String user(User user){
		System.out.println(user);
		return "index.jsp";
	}      

  实体类

public class User {
	private int id;
	private String name;
	private String pwd;
	//省略了get/set方法
  }      

2.将数据显示到UI层

  a)通过ModelAndView----需要视图解析器

@Override
public ModelAndView handleRequest(HttpServletRequest req, 
	    HttpServletResponse resp) throws Exception {	
	ModelAndView mv = new ModelAndView();
	//封装要显示到视图中的数据
	//相当于req.setAttribute("msg","hello springmvc");
	mv.addObject("msg","hello springmvc");
	//视图名
	mv.setViewName("index"); //WEB-INF/jsp/hello.jsp
	return mv;
    }      

 b)通过ModelMap----不需要视图解析器

   ModelMap需要作为处理方法的参数

public String hello(@RequestParam("uname")String name,ModelMap model){
	//相当于request.setAttribute("NAME",name);
	model.addAttribute("NAME",name);
	System.out.println(name);
	return "index.jsp";
    }	      

ModelAndView和ModelMap

相同点:

    都可以将数据封装显示表示层页面中。

继续阅读