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. having使用的时机

    where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据,条件中不能包含聚组函数,使用where条件显示特定的行. having 子句的作用是筛选满足条件的 ...

  2. 洛谷P2444 病毒【AC自动机】

    题目描述 二进制病毒审查委员会最近发现了如下的规律:某些确定的二进制串是病毒的代码.如果某段代码中不存在任何一段病毒代码,那么我们就称这段代码是安全的.现在委员会已经找出了所有的病毒代码段,试问,是否 ...

  3. | unauthenticated user (1130, "Host '127.0.0.1' is not allowed to connect to this MySQL server")

    mysql> show processlist;+----+----------------------+-----------------+------+---------+------+-- ...

  4. 解决SpringMVC中文乱码

    第一种:表单提交后controller获得中文参数后乱码解决方案 注意: 1: form表单提交方式为必须为post,get方式下面spring编码过滤器不起效果 2: jsp页面编码设置为UTF-8 ...

  5. php版本管理工具composer安装及使用

    类似于web前端有gulp,webpack,grunt.php也有专门的包安装管理和安装工具,即composer. composer官网:https://getcomposer.org      中文 ...

  6. Day24-26 项目练习(图书商城)

    图书商城 环境搭建 导入原型 用户模块 分类模块 图书模块 购物车模块 订单模块   2 功能分析 前台 用户模块: 注册 激活 登录 退出 分类模块: 查看所有分类 图书模块: 查询所有图书 按分类 ...

  7. mysql 数据操作 多表查询 子查询 带比较运算符的子查询

    带比较运算符的子查询 #比较运算符:=.!=.>.>=.<.<=.<> #查询大于所有人平均年龄的员工名与年龄 思路 先拿到所有人的平均年龄然后 再用另外一条sql ...

  8. TCP协议通讯工作原理

    TCP协议通讯工作原理   一.TCP三次握手 传输控制协议(Transport Control Protocol)是一种面向连接的,可靠的传输层协议.面向连接是指一次正常的TCP传输需要通过在TCP ...

  9. 工具推荐. 在线unix, 在线python/perl脚本测试环境

    在线python, perl, javascript, Lisp, Ruby等  http://melpon.org/wandbox/ 正则表达式在线测试工具 http://tools.jb51.ne ...

  10. java 中list进行动态remove处理

    java中遍历 list遇到需要动态删除arraylist中的一些元素 的情况 错误的方式 for(int i = 0, len = list.size(); i < len; i++){ if ...