自定义springmvc视图解析器
来源:互联网 发布:呼市吉林大学网络教育 编辑:程序博客网 时间:2024/06/06 02:48
前言
springmvc的视图解析器java程序员应该都很清楚,只要使用的是springmvc框架,那么最终从服务端吐出来的数据都需要经过视图解析器的解析。或者是返回html页面、或者是返回json数据、再或者返回xml、xls等等。
由于spring良好的开放性,我们可以很轻易的继承AbstractView,实现自己的视图解析器,来向调用端吐出合适的数据展现样式。
接下来我们一起看一个自定义的视图解析器,这个解析器将模型中的属性、属性值以及在属性上标记的注释信息打印出来,以html页面的形式吐出给调用方。
解析结果示例
实现步骤概览
- 首先我们需要自定义一个视图类,这个类要继承springmvc的AbstractView,并实现其中唯一的抽象方法:
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
- 将解析器集成到springmvc项目中。
View实现
public class AttibuteExplainView extends AbstractView { public static final String DEFAULT_CONTENT_TYPE = "application/explain"; //指定解析的MediaType类型 public AttibuteExplainView(){ setContentType(DEFAULT_CONTENT_TYPE); } @Override //执行Model对象解析 protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html"); for (Map.Entry<String, Object> entry : model.entrySet()) { if (!(entry.getValue() instanceof BindingResult)) { Object returnModel = entry.getValue(); AttributeExplainPrinter printer = new AttributeExplainPrinter(new HtmlMarkConvertor()); String html = printer.getExplainInfo(returnModel); response.setContentLength(html.getBytes().length); response.getOutputStream().write(html.getBytes()); //这里仅解析model中第一个不是BindingResult的结果,也就是说仅解析了一个Model对象 //一般来说我们向前端返回的也是一个对象,所以这样是没有问题的 break; } } }}
里面的AttributeExplainPrinter是一个自定义的类,用来实现对java对象属性、属性值及注释信息的提取。
application/explain是自定义的媒体类型,必须和下一步xml中一致。浏览器支持的媒体类型,可以见这里:http://blog.csdn.net/a123638/article/details/50313485
借助ContentNegotiatingViewResolver集成自定义View
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="order" value="1" /> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> <entry key="ae" value="application/explain"></entry> </map> </property> <property name="defaultViews"> <list> <!-- JSON 视图 --> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> </bean> <!-- 属性解析视图 --> <bean class="com.dangdang.ae.base.spring.AttibuteExplainView"></bean> </list> </property> <property name="ignoreAcceptHeader" value="true" /> </bean>
源代码和使用范例见:https://github.com/ZhangShufan15/attribute-explain
0 0
- 自定义springmvc视图解析器
- springmvc自定义视图解析器
- springMvc自定义视图及解析器
- springMVC 自定义视图及解析器
- springMVC(9)------自定义视图解析器
- SpringMVC使用自定义视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- springMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- SpringMVC视图解析器
- 应用哈希对字符串问题进行高效处理
- MFC 点击按钮,弹出另一个对话框
- 基于iTop-4412的U-Boot 2017移植[0]:Exynos4412基础
- 算法课第六周 贪心算法
- UML之初识
- 自定义springmvc视图解析器
- 递推递归-I
- 访问web-inf下的jsp
- ARP欺骗
- Jetty 的工作原理以及与 Tomcat 的比较(转载)
- Problem G: 来开个书店吧
- 2017年院赛B题 N个数求和
- 翻转二叉树
- gg