最近在写spring boot项目,写起来感觉有点繁琐,为了简化spring boot中的Controller开发,对ModelAndView进行简单的扩展,实现net mvc中ActionResult的写法

asp.net core mvc中控制器中提供了IActionResult接口来返回Aciton结果,可以用来返回视图view或者json,当然也可以实现接口返回自定义结果,当时写EasyCMS的时候实现过一个HtmlResult用来返回模板渲染生成的HTML内容,在asp.net core mvc中开发非常简便,那么我们可以看下在asp.net core mvc中的写法

//返回视图
[HttpGet]
public IActionResult Index(){
return View();
} //返回json
[HttpGet]
public IActionResult GetJson(){
return Json();
} //返回字符串
[HttpGet]
public IActionResult GetJson(){
return Content();
}

再来看下在spring boot中原始的写法是啥样子的

    //返回index页面
@GetMapping("/index")
public String index() {
return "home/index";
} //或者
@GetMapping("/tesView")
public ModelAndView tesView(){ return new ModelAndView("/home/testView");
} //返回json
@GetMapping("/getJson")
@ResponseBody
public Hashtable<String,Object> getJson(){
Hashtable<String,Object> data=new Hashtable<>();
data.put("status",true);
data.put("message","message from json");
return map;
}

可以看到spring boot默认的写法并不是很简化,比如使用String返回视图view的时候必须指定视图路径,返回json比如添加@ResponseBody注解,

而使用ModelAndView 当视图路径和路由一致时是可以简化不写视图路径的 ,所以我们可以对ModelAndView来进一步扩展来简化控制器的开发,统一返回view或者json

1,首先定义一个ActionResult

public class ActionResult extends ModelAndView {
public ActionResult()
{
super();
}
public ActionResult(View view)
{
super(view);
}
}

2,在BaseController中来封装 ActionResult ,来提供统一的返回结果

package com.easycms.framework.web;

import cn.hutool.core.util.StrUtil;
import com.easycms.constant.JacksonConstants;
import com.easycms.framework.domain.DataTableDto;
import com.easycms.framework.domain.ResultAdaptDto;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import java.util.Hashtable; public class BaseController { /**
* 返回页面
*/
//public String view(String url){
// return url;
//}
/**
* 页面跳转
*/
public String redirect(String url)
{ return StrUtil.format("redirect:{}", url);
}
/**
*
* @author yushuo
* @description //返回视图view
* @date 14:15 2021/2/4
* @param
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult view() { return view(null);
}
/**
*
* @author yushuo
* @description //返回视图view
* @date 14:15 2021/2/4
* @param [viewpath]
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult view(String viewPath) {
return view(viewPath,null);
}
/**
*
* @author yushuo
* @description //返回视图view
* @date 14:15 2021/2/4
* @param [model]
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult view(Object model) {
return view(null, model);
} /**
*
* @author yushuo
* @description //返回视图view
* @date 14:15 2021/2/4
* @param [viewpath, model]
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult view(String viewpath, Object model) {
ActionResult r = new ActionResult();
r.setViewName(viewpath);
r.addObject("model", model);
return r;
} /**
*
* @author yushuo
* @description //返回json
* @date 14:15 2021/2/4
* @param [Hashtable<String,Object> data]
* @return org.springframework.web.servlet.ModelAndView
**/
protected ActionResult json(Hashtable<String,Object> data) {
ActionResult modelAndView = new ActionResult(JacksonConstants.mappingJackson2JsonView);
modelAndView.addObject("message", null);
modelAndView.addObject("code",0);
modelAndView.addObject("status",true);
modelAndView.addObject("data", data);
return modelAndView;
} /**
*
* @author yushuo
* @description //返回json
* @date 14:15 2021/2/4
* @param [ResultAdaptDto data]
* @return org.springframework.web.servlet.ModelAndView
**/
protected ActionResult json(ResultAdaptDto data) {
ActionResult modelAndView = new ActionResult(JacksonConstants.mappingJackson2JsonView);
// modelAndView.addObject(data);
modelAndView.addObject("message", null);
modelAndView.addObject("code",0);
modelAndView.addObject("status",true);
modelAndView.addObject("data", data.getData());
return modelAndView;
} /**
*
* @author yushuo
* @description //返回json
* @date 14:15 2021/2/4
* @param [DataTableDto data]
* @return org.springframework.web.servlet.ModelAndView
**/
protected ActionResult json(DataTableDto data) {
ActionResult modelAndView = new ActionResult(JacksonConstants.mappingJackson2JsonView);
modelAndView.addObject(data);
return modelAndView;
} /**
*
* @author yushuo
* @description //请求失败
* @date 14:20 2021/2/4
* @param [message]
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult error(String message){
ActionResult modelAndView = new ActionResult(JacksonConstants.mappingJackson2JsonView);
modelAndView.addObject("message", message);
modelAndView.addObject("code",0);
modelAndView.addObject("status",false);
return modelAndView;
} /**
*
* @author yushuo
* @description //请求失败
* @date 14:20 2021/2/4
* @param
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult error(){
ActionResult modelAndView = new ActionResult(JacksonConstants.mappingJackson2JsonView);
modelAndView.addObject("message", "请求失败");
modelAndView.addObject("code",0);
modelAndView.addObject("status",false);
return modelAndView;
} /**
*
* @author yushuo
* @description //请求失败
* @date 14:20 2021/2/4
* @param [message]
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult ok(String message){
ActionResult modelAndView = new ActionResult(JacksonConstants.mappingJackson2JsonView);
modelAndView.addObject("message", message);
modelAndView.addObject("code",0);
modelAndView.addObject("status",true);
return modelAndView;
} /**
*
* @author yushuo
* @description //请求成功
* @date 14:20 2021/2/4
* @param
* @return com.easycms.framework.web.ActionResult
**/
protected ActionResult ok(){
ActionResult modelAndView = new ActionResult(JacksonConstants.mappingJackson2JsonView);
modelAndView.addObject("message", "操作成功");
modelAndView.addObject("code",0);
modelAndView.addObject("status",true);
return modelAndView;
}
}

3,BaseController中用到的JacksonConstants

package com.easycms.constant;

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import java.text.SimpleDateFormat;
import java.util.TimeZone; /**
* @author yushuo
* @className
* @descripton TODO
* @date 2021/2/5 13:47
**/
public class JacksonConstants { /**
* @author yushuo
* @description //jackson ObjectMapper
* @date 13:52 2021/2/5
* @param
* @return
**/
public static ObjectMapper objectMapper;
/**
* @author yushuo
* @description //jackson MappingJackson2HttpMessageConverter
* @date 13:52 2021/2/5
* @param
* @return
**/
public static MappingJackson2HttpMessageConverter jackson2HttpMessageConverter;
/**
* @author yushuo
* @description //jackson MappingJackson2JsonView
* @date 13:52 2021/2/5
* @param
* @return
**/
public static MappingJackson2JsonView mappingJackson2JsonView;
static {
objectMapper=objectMapper();
jackson2HttpMessageConverter=jackson2HttpMessageConverter();
mappingJackson2JsonView=mappingJackson2JsonView();
} /**
*
* @author yushuo
* @description //jackson配置jackson2HttpMessageConverter
* @date 13:49 2021/2/5
* @param []
* @return org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
**/
private static MappingJackson2HttpMessageConverter jackson2HttpMessageConverter(){
return new MappingJackson2HttpMessageConverter(objectMapper());
} /**
*
* @author yushuo
* @description //jackson配置 objectMapper
* @date 13:51 2021/2/5
* @param []
* @return com.fasterxml.jackson.databind.ObjectMapper
**/
private static ObjectMapper objectMapper(){
final Jackson2ObjectMapperBuilder builder=new Jackson2ObjectMapperBuilder();
final ObjectMapper objectMapper=builder.build();
SimpleModule simpleModule=new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE,ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER,true); objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return objectMapper;
}
/**
*
* @author yushuo
* @description //jackson配置
* @date 13:49 2021/2/5
* @param []
* @return org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
**/
private static MappingJackson2JsonView mappingJackson2JsonView(){
return new MappingJackson2JsonView(objectMapper());
}
}

4,实际使用

返回视图

    @GetMapping("/login")
public ActionResult login(){ return view("/home/login");
} //或者
@GetMapping("/login")
public ActionResult login(){ return view();
}
//或者
@GetMapping("/login")
public ActionResult login(){
ModelMap model=new ModelMap();
model.put("author","yushuo");
return view(model);
}

返回json

@GetMapping("/getJson")
public ActionResult getJson(String id){
Hashtable<String,Object> data=new Hashtable<>();
data.put("id",id);
return json(result);
}

这样是不是就比原始的控制器开发简化多了呢

可以使用统一ActionResult来返回视图view或者json,整体代码风格看起来也更统一

springboot中扩展ModelAndView实现net mvc的ActionResult效果的更多相关文章

  1. springboot中model,modelandview,modelmap的区别与联系

    springboot 中Model,ModelAndView,ModelMap的区别与联系 Model是一个接口,它的实现类为ExtendedModelMap,继承ModelMap类 public c ...

  2. spring扩展点之四:Spring Aware容器感知技术,BeanNameAware和BeanFactoryAware接口,springboot中的EnvironmentAware

    aware:英 [əˈweə(r)] 美 [əˈwer] adj.意识到的;知道的;觉察到的 XXXAware在spring里表示对XXX感知,实现XXXAware接口,并通过实现对应的set-XXX ...

  3. springboot学习笔记:5.spring mvc(含FreeMarker+layui整合)

    Spring Web MVC框架(通常简称为"Spring MVC")是一个富"模型,视图,控制器"的web框架. Spring MVC允许你创建特定的@Con ...

  4. 如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧

    做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...

  5. SpringBoot微服务架构下的MVC模型总结

    SpringBoot微服务架构下的MVC模型产生的原因: 微服务概念改变着软件开发领域,传统的开源框架结构开发,由于其繁琐的配置流程 , 复杂的设置行为,为项目的开发增加了繁重的工作量,微服务致力于解 ...

  6. SpringBoot中对SpringMVC的自动配置

    https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developin ...

  7. SpringBoot:扩展SpringMVC、定制首页、国际化

    目录 扩展使用SpringMVC 如何扩展SpringMVC 为何这么做会生效(原理) 全面接管SpringMVC 首页实现 页面国际化 SpringBoot扩展使用SpringMVC.使用模板引擎定 ...

  8. Springboot启动扩展点超详细总结,再也不怕面试官问了

    1.背景 Spring的核心思想就是容器,当容器refresh的时候,外部看上去风平浪静,其实内部则是一片惊涛骇浪,汪洋一片.Springboot更是封装了Spring,遵循约定大于配置,加上自动装配 ...

  9. 教你在你的应用程序中扩展使用dynamic类型

    教你在你的应用程序中扩展使用dynamic类型 相信大家在开发中经常会接触到mvc中的ViewBag,有心的同学会,发现这就是一个dynamic类型,查看源码一谈究竟,本文也是根据dynamic来扩展 ...

随机推荐

  1. 转载-notepad++ zend-coding使用

    转载-notepad++ zend-coding使用   zen-Coding是一款快速编写HTML,CSS(或其他格式化语言)代码的编辑器插件,这个插件可以用缩写方式完成大量重复的编码工作,是web ...

  2. 剑指offer 面试题10:斐波那契数列

    题目描述 大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0).n<=39 编程思想 知道斐波拉契数列的规律即可. 编程实现 class Solu ...

  3. upload-labs 1-21关通关记录

    0x01: 检查源代码,发现JS前端验证,关闭JS即可连接,或者手动添加.php,或者上传1.jpg,再抓包修改为php 0X02: if (($_FILES['upload_file']['type ...

  4. 18.java设计模式之中介者模式

    基本需求 智能家庭包括各种设备,闹钟.咖啡机.电视机.窗帘等 要看电视时,各个设备可以协同工作,自动完成看电视的准备工作,比如流程为:闹铃响起->咖啡机开始做咖啡->窗帘自动落下-> ...

  5. 爬虫+django,打造个性化API接口

    简述 今天也是同事在做微信小程序的开发,需要音乐接口的测试,可是用网易云的开放接口比较麻烦,也不能进行测试,这里也是和我说了一下,所以就用爬虫写了个简单网易云歌曲URL的爬虫,把数据存入mysql数据 ...

  6. 入门OJ:售货员的难题

    题目描述 某乡有n个村庄(1<n<15),有一个售货员,他要到各个村庄去售货,各村庄之间的路程s(0<s<1000)是已知的,且A村到B村与B村到A村的路大多不同.为了提高效率 ...

  7. Ubuntu18.04完全卸载mysql5.7并安装mysql8.0的安装方法

    Ubuntu18.04版本下,如果直接输入: sudo apt install mysql-server 命令,会默认安装mysql5.7版本,安装过程并没有提示输入密码,安装完成后也无法正常登录,这 ...

  8. QTextEdit的paste

    By 鬼猫猫 20130117 http://www.cnblogs.com/muyr/ 背景 QTextEdit中粘贴一大段文字时,EasyDraft中粘贴进去的文字们的格式就乱了,处于无格式.还有 ...

  9. windows中使用django时报错:A server error occurred. Please contact the administrator.

    这是因为在视图函数中使用了get函数,获取了不存在的数据例如:数据库中不存在一条name为hello1的数据,使用如下语句访问message = Message.objects.get(name='h ...

  10. 【python刷题】LRU

    什么是LRU? LRU是Least Recently Used的缩写,即最近最少使用,是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰.该算法赋予每个页面一个访问字段,用来记录一个页面自上次 ...