Springmvc05-return
1. 承载信息的对象
- Model、Map<String, Object>、ModelMap
package com.caorui.handlers;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@Scope("prototype")
@RequestMapping("/springmvc")
public class MyController {
@RequestMapping("/hello")
public String hello(String username, int age, Model model, Map<String, Object> map, ModelMap modelMap ) {
System.out.println(username + " " + age);
model.addAttribute("username", username);
map.put("age", age);
modelMap.addAttribute("gender", "female");
return "welcome";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
欢迎页面!+${username}+${age} + ${gender}
</body>
</html>
2. 设置响应编码格式、封装json对象返回给success
- 设置响应编码格式
@RequestMapping(value = “/hello”, produces = “text/html;charset=utf-8”) //响应编码格式 - 封装json对象返回给success(data)
@ResponseBody //放在方法上, 把返回的值封装成对象返回给success
package com.caorui.handlers;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.caorui.pojo.Star;
@Controller
@Scope("prototype")
@RequestMapping("/springmvc")
public class MyController {
@RequestMapping(value = "/hello", produces = "text/html;charset=utf-8")
@ResponseBody
public String hello() {
return "china:瓷器";
}
}
- 直接在controller里拼装json字符串,在页面用eval()方法转换成json对象
package com.caorui.handlers;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@Scope("prototype")
@RequestMapping("/springmvc")
public class MyController {
@RequestMapping(value = "/hello", produces = "text/html;charset=utf-8")
public void hello(HttpServletResponse response) throws IOException {
String json = "{\"name\":\"weilong\",\"flavor\":\"hot\"}";
response.getWriter().println(json);
}
}