在实际开发中,Controller取得数据(可以在Controller中处理,当然也可以来源于业务逻辑层),传给页面,常用的方式有:
后台程序如下:
@RequestMapping(value="/receiveData",method=RequestMethod.GET)
public ModelAndView StartPage() {
ModelMap map=new ModelMap();
User user=new User();
user.setPassword("123456");
user.setUserName("ZhangSan");
map.put("user", user);
return new ModelAndView("receiveControllerData",map);
}
页面程序如下:
<body>
<h1>receive Data From Controllerh1>
<br>
用户名:${user.userName }
<br>
密码:${user.password }
body>
html>
注意:ModelAndView总共有七个构造函数,其中构造函中参数model就可以传参数。具体见ModelAndView的文档,model是一个Map对象,在其中设定好key与value值,之后可以在视图中取出。
从参数定义Map
@ModelAttribute
public void model(Model model){
User user=new User("xiaoming","123456");
//传对象
model.addAttribute("user",user);
//传字符串
model.addAttribute("string","后台传递过来的字符串");
//传map
Map<String,User> map=new HashMap<String, User>();
map.put("user1",user);
model.addAttribute("map",map);
//传递列表
List<User> list=new ArrayList<User>();
list.add(user);
list.add(user);
model.addAttribute("list",list);
}
这里把需要的字符串,map,list,对象,都用model来存储,然后在前台提取。
前台jsp代码:
<h2>从后台获取的用户名和密码:<%=request.getAttribute("user").toString()%>h2>
<h2>${user.username} ${user.password}h2>
<h2>${string}h2>
<h2>后台传过来的map${map.get("user1").toString()}h2>
<h2>后台传过来的列表${list.get(0)}h2>
js是无法读取el表达式的,所以,通常后台与js的通信是通过一种轻量级的传输方式来进行的,那就是json。所以,在后台我们需要向前台传递json,然后前台来读取展示。
后台Controller: 下面是专为json的两个方法,JSONArray用来转数组,字符串,list,JSONObject用来转map,对象。
//可以把实体类,实体类数组,list,map,字符串,等等转化为json形式
public static String toJson1(Object result)
{
if(result!=null){
JSONArray obj=JSONArray.fromObject(result);
return(obj.toString());
}
return null;
}
public static String toJson2(Object result)
{
if(result!=null){
JSONObject obj=JSONObject.fromObject(result);
return obj.toString();
}
return null;
}
下面是model函数的完整版:
@ModelAttribute
public void model(Model model){
User user=new User("xiaoming","123456");
//传对象
model.addAttribute("user",user);
//传字符串
model.addAttribute("string","后台传递过来的字符串");
//传map
Map<String,User> map=new HashMap<String, User>();
map.put("user1",user);
model.addAttribute("map",map);
//传递列表
List<User> list=new ArrayList<User>();
list.add(user);
list.add(user);
model.addAttribute("list",list);
//对象转json
model.addAttribute("json_user",toJson2(user));
//字符串转json
model.addAttribute("json_string",toJson1("['json is easy']"));//一定要放进[]里
//list转json
model.addAttribute("json_list",toJson1(list));
//map转json
model.addAttribute("json_map",toJson2(map));
}
然后是index页面的js:
<script type="text/javascript">
var x1=${json_user}
alert(x1.password)
var x2=${json_string}
alert(x2)
var x3=${json_list}
alert(x3[0].username)
//要这样读取map
var x4=eval("("+'${json_map}'+")")
alert(x4["user1"].password)
</script>
jsp页面同上
<center>
<h2>从后台获取的用户名和密码:<%=request.getAttribute("user").toString()%>h2>
<h2>${user.username} ${user.password}h2>
<h2>${string}h2>
<h2>后台传过来的map${map.get("user1").toString()}h2>
<h2>后台传过来的列表${list.get(0)}h2>
center>
@modelAttribute在函数参数上使用,在页面端可以通过HttpServletRequest传到页面中去
@RequestMapping(value="/receiveData3",method=RequestMethod.GET)
public ModelAndView StartPage3(@ModelAttribute("user") User user) {
user.setPassword("123456");
user.setUserName("ZhangSan");
return new ModelAndView("receiveControllerData");
}
@RequestMapping(value="/receiveData5",method=RequestMethod.GET)
public ModelAndView StartPage5(HttpServletRequest request) {
User user=new User();
user.setPassword("123456");
user.setUserName("ZhangSan");
HttpSession session=request.getSession();
session.setAttribute("user", user);
return new ModelAndView("receiveControllerData");
}
页面程序如下:
<h2>利用HttpServletRequest传数据h2>
<form action="loginToJson">
用户名:<input name="name" /> 密码:<input name="pass" /> <input
type="submit" value="登陆">
form>
后台程序段如下:
@ResponseBody
@RequestMapping(value="/loginToJson",method=RequestMethod.POST)
public String loginToJson(HttpServletRequest request) {
User user = new User();
user.setUserName(request.getParameter("name"));
user.setPassword(request.getParameter("pass"));
return JSON.toJSONString(user);
}
前台程序如下:
<h2>利用函数参数传数据h2>
<form action="loginByVariable" method="post">
用户名:<input name="name" /> 密码:<input name="pass" />
<input type="submit" value="登陆">
form>
后台程序如下:
@RequestMapping(value="/loginByVariable",method=RequestMethod.POST)
public String loginToSession(HttpServletRequest request,ModelMap
map,String name,String pass) {
User user = new User();
user.setUserName(name);
user.setPassword(pass);
map.put("user", user);
System.out.println(user);
return "mySession";
}
注意:前台中的name属性的值,必须和后台函数参数中的String name中的形参名一致,否则从后台取不到值。
前置条件,对象的定义代码:
注意这里,User对象的属性名为userName和password,并有getter和setter属性
public class User{
@Override
public String toString() {
return "User [userName=" + userName + ", password=" + password + "]";
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String userName;
private String password;
}
前台程序如下:
注意:userName和password必须和对象属性名称一致。
<h2>利用函数参数对象传数据h2>
<form action="loginByObject" method="post">
用户名:<input name="userName" /> 密码:<input name="password" /> <input
type="submit" value="登陆">
form>
后台程序如下:
@RequestMapping(value="/loginByObject",method=RequestMethod.POST)
public String loginToSession(ModelMap map,User user) {
User user1 = new User();
user1.setUserName(user.getUserName());
user1.setPassword(user.getPassword());
System.out.println(user1+" Object");
map.put("user", user1);
return "mySession";
}
前台代码如下:
<br>
<h2>利用函数参数@RequestParam参数传递据h2>
<form action="loginByRequestParm" method="post">
用户名:<input name="name" /> 密码:<input name="pass" /> <input
type="submit" value="登陆">
form>
后台程序如下:
@RequestMapping(value="/loginByRequestParm",method=RequestMethod.POST)
public String loginToSessiona(HttpServletRequest request,ModelMap map,
@RequestParam("name") String UserName,@RequestParam String pass) {
User user = new User();
user.setUserName(UserName);
user.setPassword(pass);
map.put("user", user);
System.out.println(user+"requestParam");
return "mySession";
}
注意:@RequestParam(“name”)中如果有参数,name必须为页面中属性的值,如果没有参数,则参数名,必须和页面中属性的值相同,如页面中pass,则在@RequestParam中,则可以不指定参数,但形参的名字必须为pass
具体代码如下:
@Controller
public class TestController {
@RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)
public String getLogin(@PathVariable("userId") String userId,
@PathVariable("roleId") String roleId){
System.out.println("User Id : " + userId);
System.out.println("Role Id : " + roleId);
return "hello";
}
@RequestMapping(value="/product/{productId}",method = RequestMethod.GET)
public String getProduct(@PathVariable("productId") String productId){
System.out.println("Product Id : " + productId);
return "hello";
}
@RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",
method = RequestMethod.GET)
public String getRegExp(@PathVariable("regexp1") String regexp1){
System.out.println("URI Part 1 : " + regexp1);
return "hello";
}
}
@RequestParam和@PathVariable的用法与区别 可以看这篇总结:
SpringMVC中@RequestParam和@PathVariable的用法与区别