ContentNegotiatingViewResolver多种输出格式实例: json/jsp/xml/xls/pdf
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的更多相关文章
- Spring4 MVC ContentNegotiatingViewResolver多种输出格式实例
本文演示支持多种输出格式,这里 Spring4 MVC应用程序使用了 Spring ContentNegotiatingViewResolver .我们将生成应用程序输出XML,JSON,PDF,XL ...
- Spring4 MVC ContentNegotiatingViewResolver多种输出格式实
前段时间在一个项目里面发现,针对Excel的处理没有一个公用的视图,来个下载的需求就要自己去写一堆POI的东西,终于有一天给我也来了几个,还是按照以前的方式来写,写多了真心想吐,后面想想还是有必要整个 ...
- REST服务使用@RestController实例,输出xml/json
REST服务使用@RestController实例,输出xml/json 需要用到的服务注解 org.springframework.web.bind.annotation.RestControlle ...
- JSON与XML的区别比较
1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许 ...
- JSON与XML优缺点对比分析
本文从各个方面向大家对比展示了json和xml的优缺点,十分的全面细致,有需要的小伙伴可以参考下. 1. 定义介绍 1.1 XML定义 扩展标记语言 (Extensible Markup Langua ...
- JSON与XML的区别
1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许 ...
- [转]JSON与XML的区别比较
1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许 ...
- JSON与XML的区别比较(转)
原文链接:JSON与XML的区别比较 1.定义介绍 (1).XML定义扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以 ...
- Json&XML比较
1.定义 1.1 XML定义 扩展标记语言 (Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许用 ...
随机推荐
- python环境杂谈
最近发现集群里的服务器上有多个python环境,版本相同的python也有多个,主要区别是site-packages里安装的模块不同,这样配置的好处是不同类型的项目可以使用自己的python环境,不会 ...
- javascript飞机大战-----007爆炸效果
要检验什么时候碰撞,我们必须了解什么时候不相撞.以上四种情况是不相撞的时候 首先在引擎里面写好什么时候碰撞什么时候不碰撞 /* 游戏引擎 */ var Engine = { //刚开始的游戏状态 ga ...
- 阿里云服务器被挖矿程序minerd入侵的终极解决办法[转载]
突然发现阿里云服务器CPU很高,几乎达到100%,执行 top c 一看,吓一跳,结果如下: root 386m S : /tmp/AnXqV -B -a cryptonight -o stratum ...
- 了解MIP(Mobile Instant Pages)
mip官网:https://www.mipengine.org/ 什么是mip? mip是百度在2016年提出的移动网页加速器项目.可以简单理解为是一个规范. mip能做什么? mip能帮助站 ...
- SpringCloud--Ribbon负载均衡
Ribbon实现客户端负载均衡 负载均衡:是对系统的高可用.网络压力的缓解和处理能力扩容的重要手段之一. 硬件负载均衡:主要通过在服务器节点之间安装专门用于负载均衡的设备: 软件负载均衡:通过在服务器 ...
- Silverlight中ListBox的数据绑定
在Silverlight中ListBox是一个非常强大的控件.总结下ListBox的绑定数据的方式. 首先,新建一个Book类, public class Book { public string B ...
- Spring boot maven 搭建框架
Spring Boot:目的:这个框架帮助开发者更容易地创建基于Spring的应用程序和服务,使得pring开发者能够最快速地获得所需要的Spring功能.优点:完全不需要XML配置,让spring应 ...
- linux软件源配置
实操(虚拟机安装): 下载VMware,然后按照如下教程安装虚拟机: https://jingyan.baidu.com/article/c275f6ba07e269e33d756714.html ...
- 【Loadrunner】通过loadrunner录制时候有事件但是白页无法出来登录页怎么办?
loadrunner录制脚本时候有事件但是一直白页怎么办? 解决办法:依次进行下方1.2.方法操作,如果还不行再进行3的操作. 1.勾选下图IE浏览器的Internet选项中“启用第三方浏览器拓展*” ...
- js-template-art【四】通过helper方法注册,调用外部方法
一.语法 模板代码中调用外部函数,需要通过helper方法注册 template.helper(name, callback) 二.使用[实例] 原文:http://blog.csdn.net/u01 ...