ContentNegotiatingViewResolver多种输出格式实例: json/jsp/xml/xls/pdf

本例用的是javaConfig配置

以pizza为例。

json输出需要用到的包:

jackson-databind 2.4.1.3
jackson-annotations 2.4.1

  

pdf需要用到的包:

lowagie itext 4.2.1

  

xls需要用到的包:

Apache POI 3.10-beta2

  

xml包

spring-oxm

  

访问地址:

http://localhost:8080/gugua9/hello/aaa.xml

http://localhost:8080/gugua9/hello/aaa.json

http://localhost:8080/gugua9/hello/aaa

http://localhost:8080/gugua9/hello/aaa.xls

http://localhost:8080/gugua9/hello/aaa.pdf

pom.xml配置:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>gugua4</groupId>
<artifactId>gugua8</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>gugua8 Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<springVersion>4.3.5.RELEASE</springVersion>
</properties> <dependencies> <!-- spring-test支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency> <!-- spring模块库 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency> <!-- Needed for XML View (with JAXB2) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${springVersion}</version>
</dependency> <!-- Needed for JSON View -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.4</version>
</dependency> <!-- Needed for PDF View -->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency> <!-- Needed for XLS View -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-beta2</version>
</dependency> <!-- Servlet dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- servlet(HttpServletRequest,HttpServletResponse) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency> </dependencies> <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>gugua8</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin> <!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin> </plugins>
</pluginManagement>
<finalName>gugua8</finalName>
</build>
</project>

  

注意可能会发生的几个错误:

解决maven项目Cannot change version of project facet Dynamic web module to 3.0/3.1

https://www.cnblogs.com/achengmu/p/9101669.html

maven项目Java resources 上面有个红叉但是代码里面并没有什么报错

https://www.cnblogs.com/achengmu/p/9106953.html

pizza.java

package springmvc.model;

import java.util.ArrayList;
import java.util.List; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "pizza")
public class Pizza { private String name;
private String flavor;
private List<String> toppings = new ArrayList<String>(); public Pizza()
{ } public Pizza(String name){
this.name = name;
this.flavor = "spicy";
this.toppings.add("Cheese");
this.toppings.add("bakon");
} public String getName() {
return name;
} @XmlElement
public void setName(String name) {
this.name = name;
} public String getFlavor() {
return flavor;
} @XmlElement
public void setFlavor(String flavor) {
this.flavor = flavor;
} public List<String> getToppings() {
return toppings;
} public void setToppings(List<String> toppings) {
this.toppings = toppings;
} }

  

AppController.java

package springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import springmvc.model.Pizza; @Controller
public class AppController { @RequestMapping(value="/pizza/{name}", method=RequestMethod.GET)
public String getPizza( ModelMap model, @PathVariable(value="name") String name)
{
model.addAttribute("message", name); Pizza pizza = new Pizza(name);
model.addAttribute("pizza", pizza); return "test"; } }

  

初始化

AppInitializer.java

package springmvc.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class[] { AppConfig.class };
} @Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
} @Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] { "/" };
} }

  

配置
AppConfig.java

package springmvc.configuration;

import java.util.ArrayList;
import java.util.List; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; import springmvc.model.Pizza;
import springmve.viewresolver.ExcelViewResolver;
import springmve.viewresolver.Jaxb2MarshallingXmlVierResolver;
import springmve.viewresolver.JsonViewResolver;
import springmve.viewresolver.PdfViewResolver; import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
@EnableWebMvc
@ComponentScan(basePackages="springmvc")
public class AppConfig extends WebMvcConfigurerAdapter{ @Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
// TODO Auto-generated method stub
//super.configureContentNegotiation(configurer);
configurer.ignoreAcceptHeader(true).defaultContentType(MediaType.TEXT_HTML);
} @Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager)
{
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager); List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
resolvers.add(jspViewResolver());
resolvers.add(jaxb2MarshallingViewResolver());
resolvers.add(jsonViewResolver());
resolvers.add(excelViewResolver());
resolvers.add(pdfVierResolver()); resolver.setViewResolvers(resolvers);
return resolver; } @Bean
public ViewResolver jaxb2MarshallingViewResolver()
{
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Pizza.class);
return new Jaxb2MarshallingXmlVierResolver(marshaller); }
@Bean
public ViewResolver jsonViewResolver()
{
return new JsonViewResolver();
} @Bean
public ViewResolver jspViewResolver()
{
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
} @Bean
public ViewResolver excelViewResolver()
{
return new ExcelViewResolver();
} @Bean
public ViewResolver pdfVierResolver()
{
return new PdfViewResolver();
}
}

  

相关的插件

json实现

package springmve.viewresolver;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView; public class JsonViewResolver implements ViewResolver { public View resolveViewName(String viewName, Locale locale) throws Exception {
// TODO Auto-generated method stub
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setPrefixJson(true);
return view;
} }

  

spring的xml

package springmve.viewresolver;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver; import org.springframework.oxm.Marshaller;
import org.springframework.web.servlet.view.xml.MarshallingView; public class Jaxb2MarshallingXmlVierResolver implements ViewResolver { private Marshaller marshaller; public Jaxb2MarshallingXmlVierResolver(Marshaller marshaller)
{
this.marshaller = marshaller;
} public View resolveViewName(String viewName, Locale locale) throws Exception {
// TODO Auto-generated method stub
MarshallingView view = new MarshallingView();
view.setMarshaller(marshaller);
return view;
} }

  

excel-xls的实现(spring-AbstractExcelView)

package springmve.viewresolver;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.servlet.view.document.AbstractExcelView; import springmvc.model.Pizza; public class ExcelView extends AbstractExcelView { @Override
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub Pizza pizza = (Pizza) model.get("pizza"); //创建工作簿
Sheet sheet = workbook.createSheet("sheel");
//工作簿样式
CellStyle style = workbook.createCellStyle();
style.setFillBackgroundColor(IndexedColors.GREY_40_PERCENT.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER); Row row = null;
Cell cell = null;
int rowCount = 0;
int colCount = 0; //create-table
row = sheet.createRow(rowCount++); cell = row.createCell(colCount++);
cell.setCellStyle(style);
cell.setCellValue("name"); cell = row.createCell(colCount++);
cell.setCellStyle(style);
cell.setCellValue("flavor"); cell = row.createCell(colCount++);
cell.setCellStyle(style);
cell.setCellValue("toppings"); //set-value
row = sheet.createRow(rowCount++);
colCount = 0;
row.createCell(colCount++).setCellValue(pizza.getName());
row.createCell(colCount++).setCellValue(pizza.getFlavor()); StringBuffer toppings = new StringBuffer();
for(String topping: pizza.getToppings())
{
toppings.append(topping);
toppings.append(" ");
}
row.createCell(colCount++).setCellValue(toppings.toString()); //for(int i = 0; i<3; i++)
//{
// sheet.autoSizeColumn(i);
//} } }

  

package springmve.viewresolver;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver; public class ExcelViewResolver implements ViewResolver { @Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
// TODO Auto-generated method stub
ExcelView view = new ExcelView();
return view;
} }

  

pdf的实现(spring-AbstractPdfView)

package springmve.viewresolver;

import java.awt.Color;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.document.AbstractPdfView; import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter; import springmvc.model.Pizza; public class PdfView extends AbstractPdfView { @Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub Pizza pizza = (Pizza) model.get("pizza"); PdfPTable table = new PdfPTable(3);
//对齐方式
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBackgroundColor(Color.lightGray); //表头
table.addCell("name");
table.addCell("flavor");
table.addCell("toppings"); //内容
table.addCell(pizza.getName());
table.addCell(pizza.getFlavor()); StringBuffer toppings = new StringBuffer();
for(String topping: pizza.getToppings())
{
toppings.append(topping);
toppings.append(" ");
}
table.addCell(toppings.toString());
document.add(table); } }

  

package springmve.viewresolver;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver; public class PdfViewResolver implements ViewResolver { @Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
// TODO Auto-generated method stub
PdfView view = new PdfView();
return view;
} }

  

ContentNegotiatingViewResolver多种输出格式实例: json/jsp/xml/xls/pdf的更多相关文章

  1. Spring4 MVC ContentNegotiatingViewResolver多种输出格式实例

    本文演示支持多种输出格式,这里 Spring4 MVC应用程序使用了 Spring ContentNegotiatingViewResolver .我们将生成应用程序输出XML,JSON,PDF,XL ...

  2. Spring4 MVC ContentNegotiatingViewResolver多种输出格式实

    前段时间在一个项目里面发现,针对Excel的处理没有一个公用的视图,来个下载的需求就要自己去写一堆POI的东西,终于有一天给我也来了几个,还是按照以前的方式来写,写多了真心想吐,后面想想还是有必要整个 ...

  3. REST服务使用@RestController实例,输出xml/json

    REST服务使用@RestController实例,输出xml/json 需要用到的服务注解 org.springframework.web.bind.annotation.RestControlle ...

  4. JSON与XML的区别比较

    1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许 ...

  5. JSON与XML优缺点对比分析

    本文从各个方面向大家对比展示了json和xml的优缺点,十分的全面细致,有需要的小伙伴可以参考下. 1. 定义介绍 1.1 XML定义 扩展标记语言 (Extensible Markup Langua ...

  6. JSON与XML的区别

    1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许 ...

  7. [转]JSON与XML的区别比较

    1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许 ...

  8. JSON与XML的区别比较(转)

    原文链接:JSON与XML的区别比较 1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以 ...

  9. Json&XML比较

    1.定义 1.1 XML定义 扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许用 ...

随机推荐

  1. Linux常用命令大全(转载)

    最近都在和Linux打交道,这方面基础比较薄弱的我只好买了本鸟哥的书看看,感觉还不错.我觉得Linux相比windows比较麻烦的就是很多东西都要用命令来控制,当然,这也是很多人喜欢linux的原因, ...

  2. postgresql----Btree索引

    当表数据量越来越大时查询速度会下降,像课本目录一样,在表的条件字段上创建索引,查询时能够快速定位感兴趣的数据所在的位置.索引的好处主要有加速带条件的查询,删除,更新,加速JOIN操作,加速外键约束更新 ...

  3. poj1821 Fence【队列优化线性DP】

    Fence Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 6122   Accepted: 1972 Description ...

  4. D. Little Artem and Dance---cf669D(模拟)

    题目链接:http://codeforces.com/problemset/problem/669/D 给你n个数,一开始是1 2 3 4 5 6 ... n 这样的 现在有两个操作,第一个操作是所有 ...

  5. 双态运维分享之:业务场景驱动的服务型CMDB

    最近这几年,国内外CMDB失败的案例比比皆是,成功的寥寥可数,有人质疑CMDB is dead?但各种业务场景表明,当下数据中心运维,CMDB依然是不可或缺的一部分,它承载着运维的基础,掌握运维的命脉 ...

  6. Logback配置讲解

    复制文件并粘贴到项目下: logback.xml: <?xml version="1.0" encoding="UTF-8"?> <confi ...

  7. python装饰器的应用案例

    目录 一.过程编程 二.面向装饰器和函数的编程 三.二的加强版 一.过程编程 (一)需求:打印菱形 1.空格.*号组成的菱形 2.输入菱形上半部分的行数即可打印 3.支持循环输入 (二)代码 from ...

  8. python多线程为什么不能利用多核cpu

    GIL 与 Python 线程的纠葛 GIL 是什么东西?它对我们的 python 程序会产生什么样的影响?我们先来看一个问题.运行下面这段 python 程序,CPU 占用率是多少? # 请勿在工作 ...

  9. samba文件共享服务配置一(共2节)

    一.samba服务简介 Samba是在Linux和UNIX系统上实现SMB协议的一个免费软件,由服务器及客户端程序构成.SMB(Server Messages Block,信息服务块)是一种在局域网上 ...

  10. 2.4 The Object Model -- Computed Properties and Aggregate Data with @each(计算的属性和使用@each聚合数据)

    1. 通常,你可能有一个计算的属性依赖于数组中的所有元素来确定它的值.例如,你可能想要计算controller中所有todo items的数量,以此来确定完成了多少任务. export default ...