1. 程式人生 > >springmvc的前後端傳值

springmvc的前後端傳值

lis mod ttr attribute orm ces brush str get

一.後端傳值給前端

1.ModelAndView

@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
	String viewName=SUCCESS;
	ModelAndView model = new ModelAndView(viewName);
	model.addObject("time", new Date());
	return model;
		
}

  

2.map

@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){		
	map.put("names", Arrays.asList("Tom","maray","hery"));
	return SUCCESS;
}

  

3.ModelMap

@RequestMapping("/testModelMap")
public String testModleMap(ModelMap map){
	map.addAttribute("modelMapDate", "modelMapDate");
	return SUCCESS;
		
}

  

4.model

@RequestMapping("/testModel")
public String testModel(Model model){
	model.addAttribute("modelDate", "modelDate");
	return SUCCESS;		
}

5.使用servlet Api

二.前端向後臺傳值

1.pojo的值

後端java
@RequestMapping("/testPOJO")
public String testPOJO(User user){		
	System.out.println(user);
	return SUCCESS;
		
}
前端jsp
<form action="springmvc/testPOJO" method="post">
    	username:<input type="text" name="username">
    	<br>
    	pasword:<input type="password" name="password">
    	<br>
    	age:<input type="text" name="age">
    	<br>
    	email:<input type="text" name="email">
    	<br>
    	city:<input type="text" name="address.city">
    	<br>
    	stree:<input type="text" name="address.stree">
    	<br>
    	<input type="submit" value="提交">
    	
    </form> 

 2.利用@RequestParam註解參數

@RequestMapping("/testResquestParam")
public String testResquestParam(@RequestParam(value="username") String username,
	@RequestParam(value="age",required=false,defaultValue="14") int age,
	@RequestParam String email,
     double price){
  System.out.println("testResquestParam:"+username+" "+age+" "+email+" "+price);
  return SUCCESS;
}

 3.利用

@ModelAttribute,為對象傳值
@RequestMapping("/testModelAttribut")
public String testModelAttribut(@ModelAttribute User user,Map<String,Object> map){
	System.out.println("model"+user);
	System.out.println("map"+map.get("user"));
	return SUCCESS;	
}

  

 

springmvc的前後端傳值