一个例子胜过千言万语,直接上代码

SpringMVC的Controller控制器返回值详解

SpringMVC Controller 返回值几种类型

Spring MVC 更灵活的控制 json 返回(自定义过滤字段)   另1

/**
*
* @return Bean
*/
@RequestMapping("/Test")
@ResponseBody
public TestBean test (){
log.debug("Test function");
TestBean testBean=new TestBean();
testBean.setName("haha");
return testBean;
}
/**
*
* @return Bean List
*/
@RequestMapping("/TestList")
@ResponseBody
public List<TestBean> testList (){
log.debug("TestList function");
List<TestBean> testBeanList=new ArrayList<TestBean>();
TestBean testBean1=new TestBean();
testBean1.setName("haha");
TestBean testBean2=new TestBean();
testBean2.setName("hehe");
testBeanList.add(testBean1);
testBeanList.add(testBean2);
return testBeanList;
} /**
*
* @return JSON Data
*/
@RequestMapping("/TestJSONObject")
public void testReturrnJSONWithoutBean(HttpServletRequest request,HttpServletResponse response) throws IOException{
log.debug("TestJSONObject function");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter writer=response.getWriter();
JsonObject jsonObject=new JsonObject();
jsonObject.addProperty("name","hehe jsonobject");
writer.println(jsonObject.toString());
writer.close();
} /**
*
* @return String
*/
@RequestMapping("/TestReturnPage")
@ResponseBody
public String testReturrnPage(){
log.debug("TestReturnPage");
return "/testpage";
} /**
* The difference between model and modelandview is just sematic
* */
/**
* @return JSON ModelAndView
*/
@RequestMapping("/TestReturnModel")
public String testReturnModel(Model model){
log.debug("testReturrnModel");
model.addAttribute("testmodel", "hello model");
return "testpage";
}
/**
* The difference between model and modelandview is just sematic
* */
/**
* @return JSON ModelAndView
*/
@RequestMapping("/TestReturnModelAndView")
public ModelAndView testReturnModelAndView(){
log.debug("testReturrnModel");
ModelAndView mav = new ModelAndView("testpage");
mav.addObject("testmodel", "hello test model");
return mav;
} /**
* 获取系统显示的菜单
*
* @param 无
* @return 返回JSON字符串,这是经过处理后的结构化树形数据。
*/
@RequestMapping(value = "/getShowedMenus", produces = "application/json; charset=utf-8")
@ResponseBody
public String getShowedMenus() {
JsonArray menus=new JsonArray();
try{
menus=platformMenuService.getMenusForShow();
}catch(Exception e)
{
logger.error(e.toString());
e.printStackTrace();
}
return menus.toString();
}
/**
* 从远程数据中心中注销登录
* @param request
* @param response
* @return 返回逻辑值
*/
@RequestMapping("/logout")
@ResponseBody
private boolean logout(HttpServletRequest request,HttpServletResponse response)
{
boolean retVal=false;
try{ }catch(Exception e){
logger.error(e.toString());
}
return retVal;
}
/**
* 本地数据中心登录至远程数据中心。
* @param datacenterId
* @return 返回是否登录成功
*/
@RequestMapping(value="/login",produces = "application/json; charset=utf-8")
@ResponseBody
public Boolean login(String dcId,HttpServletRequest request,HttpServletResponse response) {
logger.info("datacenterId"+dcId);
dcId="12";
Boolean retVal=false;
try{
DatacatalogDatacenter dc=datacenterService.selectByPrimaryKey(dcId);
String url="http://localhost:8080/"+request.getContextPath()+"/rest/datacatalog/datacenter/server/login?&no=121";
String val=HttpUtils.HttpPost(url);
retVal=Boolean.parseBoolean(val);
//retObject=new JSONObject(detail);
}catch(Exception e){
logger.error(e.toString());
e.printStackTrace();
}
return retVal;
}
//使用request转向页面

@RequestMapping("/itemList2")
public void itmeList2(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 查询商品列表
List<Items> itemList = itemService.getItemList();
// 向页面传递参数
request.setAttribute("itemList", itemList);
// 如果使用原始的方式做页面跳转,必须给的是jsp的完整路径
request.getRequestDispatcher("/WEB-INF/jsp/itemList.jsp").forward(request, response);
} 也通过response实现页面重定向:
response.sendRedirect("url")
如:
@RequestMapping("/itemList2")
public void itmeList2(HttpServletRequest request, HttpServletResponse response) throws Exception {
PrintWriter writer = response.getWriter();
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
writer.write("{\"id\":\"123\"}");

第一种,通过request.setAttribute进行返回。

@RequestMapping(value="/welcomeF")
public String WelcomeF(User user,HttpServletRequest request){
System.out.println(user.toString());
/*通过setAttribute来设置返回*/
request.setAttribute("name", user.getName());
request.setAttribute("password", user.getPassword());
request.setAttribute("password", user.getHobby());
return "welcome";
} 第二种,通过ModelAndView进行返回。 @RequestMapping(value="/welcomeSeven")
public ModelAndView WelcomeSeven(User2 user2){
/*通过ModelAndView来返回数据*/
ModelAndView mav = new ModelAndView("welcome");
mav.addObject("name", user2.getName());
mav.addObject("date", user2.getUdate());
return mav;
} 第三种,通过model对象进行返回。 @RequestMapping(value="/welcomeEight")
public String WelcomeEight(User2 user2,Model model){
/*通过Model对象来返回数据*/
model.addAttribute("name", user2.getName());
model.addAttribute("date", user2.getUdate());
return "welcome";
} 第四种,通过Map对象进行返回。 @RequestMapping(value="/welcomeNine")
public String WelcomeNine(User2 user2,Map map){
/*通过Model对象来返回数据*/
map.put("name", user2.getName());
map.put("date", user2.getUdate());
return "welcome";
}

spring mvc返回json数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable

    @RequestMapping(value = { "/actor_details" }, method = { RequestMethod.POST })
@ResponseBody
public ResultObject actorDetails(@RequestBody ActorDetailsRequest req) {
logger.debug("查看{}主播信息", req.getAid());
if (req.getAid() == null || req.getAid().equals("null")
|| req.getAid().equals("")) {
return new ResultObject(ResultCode.NULL_PARAM);
}
ActorAndUser result = actorServiceImpl.queryActorData(req.getAid());
return new ResultObject(result);
}

ModelAndView

   @RequestMapping(method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView("/user/index");
modelAndView.addObject("xxx", "xxx");
return modelAndView;
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("xxx", "xxx");
modelAndView.setViewName("/user/index");
return modelAndView;
}

Map

响应的view应该也是该请求的view。等同于void返回。
@RequestMapping(method=RequestMethod.GET)
public Map<String, String> index(){
Map<String, String> map = new HashMap<String, String>();
map.put("1", "1");
//map.put相当于request.setAttribute方法
return map;
}
@RequestMapping("/demo2/show")
publicMap<String, String> getMap() {
Map<String, String> map = newHashMap<String, String>();
map.put("key1", "value-1");
map.put("key2", "value-2");
returnmap;
} 在jsp页面中可直通过${key1}获得到值, map.put()相当于request.setAttribute方法。
写例子时发现,key值包括 - . 时会有问题.

String

对于String的返回类型,笔者是配合Model来使用的;
@RequestMapping(method = RequestMethod.GET)2
public String index(Model model) {
String retVal = "user/index";
List<User> users = userService.getUsers();
model.addAttribute("users", users);
return retVal;
}
或者通过配合@ResponseBody来将内容或者对象作为HTTP响应正文返回(适合做即时校验);

    @RequestMapping(value = "/valid", method = RequestMethod.GET)
public @ResponseBody
String valid(@RequestParam(value = "userId", required = false) Integer userId,@RequestParam(value = "logName") String strLogName) {
return String.valueOf(!userService.isLogNameExist(strLogName, userId));
}

具体参考:https://blog.csdn.net/u011001084/article/details/52846791  太长了,没整理

@RequestMapping(value=”twoB.do”)
public void twoBCode(HttpServletRequest request,HttpServletResponse response) {
response.setContentType(“type=text/html;charset=UTF-8”);
String s = “一堆字符串……”;
response.getWriter().write(s);
return;
} 上面的太low,用下面的比较好
@RequestMapping(value=”getJosn.do”, produces=”text/html;charset=UTF-8”) 
@ResponseBody 
public String getTabJson(){ 
String json = “{“无主题”:”jjjjj”}”; 
return json; 
}

mvc 各种返回值的更多相关文章

  1. ASP.NET Core Mvc中空返回值的处理方式

    原文地址:https://www.strathweb.com/2018/10/convert-null-valued-results-to-404-in-asp-net-core-mvc/ 作者: F ...

  2. MVC方法返回值数据

    ModelAndView的作用以及用法 使用ModelAndView类用来存储处理完后的结果数据,以及显示该数据的视图.从名字上看ModelAndView中的Model代表模型,View代表视图,这个 ...

  3. Spring MVC controller返回值类型

    SpringMVC controller返回值类型: 1 String return "user":将请求转发到user.jsp(forword) return "red ...

  4. spring mvc ajax返回值乱码

    加入如下配置: <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHan ...

  5. MVC控制器返回值

    public ActionResult Index(string id)//主页 //参数string searchString 访问方式为index?searchString=xxxx .参数str ...

  6. MVC方法的返回值类型

    MVC方法返回值类型 ModelAndView返回值类型: 1.当返回为null时,页面不跳转. 2.当返回值没有指定视图名时,默认使用请求名作为视图名进行跳转. 3.当返回值指定了视图名,程序会按照 ...

  7. mvc 返回值

    mvc返回值为Model类型 public ActionResult Index(T result) { return View(result); } view中的对象即为页面中的Model数据,之后 ...

  8. Spring框架下的 “接口调用、MVC请求” 调用参数、返回值、耗时信息输出

    主要拦截前端或后天的请求,打印请求方法参数.返回值.耗时.异常的日志.方便开发调试,能很快定位到问题出现在哪个方法中. 前端请求拦截,mvc的拦截器 import java.util.Date; im ...

  9. Asp.net MVC 中Controller返回值类型ActionResult

    [Asp.net MVC中Controller返回值类型] 在mvc中所有的controller类都必须使用"Controller"后缀来命名并且对Action也有一定的要求: 必 ...

随机推荐

  1. git的使用学习(七)githup和码云的使用

    1.使用GitHub 我们一直用GitHub作为免费的远程仓库,如果是个人的开源项目,放到GitHub上是完全没有问题的.其实GitHub还是一个开源协作社区,通过GitHub,既可以让别人参与你的开 ...

  2. Android与H5互调

    前言 微信,微博,微商,QQ空间,大量的软件使用内嵌了H5,这个时候就需要了解Android如何更H5交互的了:有些外包公司,为了节约成本,采用Android内嵌H5模式开发,便于在IOS上直接复用页 ...

  3. 51nod 1050 循环数组最大子段和【环形DP/最大子段和/正难则反】

    1050 循环数组最大子段和 基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题  收藏  关注 N个整数组成的循环序列a[1],a[2],a[3],…,a[n],求该 ...

  4. Codeforces 777C Alyona and Spreadsheet(思维)

    题目链接 Alyona and Spreadsheet 记a[i][j]为读入的矩阵,c[i][j]为满足a[i][j],a[i - 1][j], a[i - 2][j],......,a[k][j] ...

  5. Codeforces 746G New Roads (构造)

                                                                            G. New Roads                 ...

  6. IT人为了自己父母和家庭,更得注意自己的身体和心理健康

    我前一阵在一家互联网公司,工作节奏是995,忙的时候,要晚上10点才能离开公司,有时候周六还得加班.自己感觉身体状况有所下降,且听说其它一个组,在体检后多少都查出问题来,细思极恐. 有时候确实忙,那么 ...

  7. codevs——1220 数字三角形(棋盘DP)

     时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题解       题目描述 Description 如图所示的数字三角形,从顶部出发,在每一结点可以选择向左走或 ...

  8. XSY 1749 tree

    题目大意 给定一棵基环树, 问你有多少条路径的长度\(\ge K\). 点数\(\le 10^5\) Solution 基环树分治模板题. 我是这样做的: 加边的时候用并查集维护点的连通性, 少加入环 ...

  9. js中高效拼接字符串

    写在前面 面试的过程,很有可能面试到c#那种方式拼接字符串更高效,然后就会引申到js中的拼接方式.这也是我在面试中遇到的问题,当时,也真没比较过js中到底哪种方式更高效.然后,跟猜测一样,说了使用数组 ...

  10. 解决Ubuntu下gedit中文乱码的情况

    windows下简体中文多用GBK编码 (或GB2312, GB18030), 而linux下多用UTF-8编码. 因此,一般来说在微软平台编辑的中文txt不能在ubuntu下直接打开查看,除非在保存 ...