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) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许用 ...
随机推荐
- js判断移动端和PC端跳转不同页面
方法一: /* * * 判断PC端与WAP端 */ var mobile_bs = { versions: function() { var u = navigator.userAgent; retu ...
- 软件IT
软件IT 周期: 攻防:攻击性板块 范畴:科技板块 业务:软件,互联网,人工智能,区块链... 行情主要因素: 主要问题:新领域,成长不确定性高 投资策略: 个股:科大讯飞,中国软件,用友网络,浪潮信 ...
- Day22 文件上传下载和javaMail
day22总结 文件上传概述 1 文件上传的作用 例如网络硬盘!就是用来上传下载文件的. 在智联招聘上填写一个完整的简历还需要上传照片呢. 2 文件上传对页面的要求 上传文件的要求比较多,需要 ...
- Git版本控制工具安装与配置
这里太多,我写在这里方便复制: sudo yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel curl-dev ...
- jquery序列化表单以及回调函数的使用
在开发项目中.将前台的值传给后台,有时的JSP表单中的值有一两个,也有所有的值,假设这时一个个传,必然不是非常好的办法,所以使用jQuery提供的表单序列化方法,能够非常好的解决问题.同一时候能够封装 ...
- Scala的类与类型
类和类型 List<String>和List<Int>类型是不一样的,但是jvm运行时会采用泛型擦除.导致List<String>和List<Int>都 ...
- Thymeleaf使用说明
Thymeleaf使用说明 javascript操作: a.<script type="text/javascript" th:inline="javascript ...
- Codeforces Round #530 (Div. 2) Solution
A. Snowball 签. #include <bits/stdc++.h> using namespace std; ], d[]; int main() { while (scanf ...
- Vue学习笔记之Webpack介绍
在这里我仅仅的是对webpack做个讲解,webpack这个工具非常强大,解决了我们前端很繁琐的一些工具流程繁琐的事情.如果感兴趣的同学,简易还是看官网吧. 中文链接地址:https://www.we ...
- bzoj1601 / P1550 [USACO08OCT]打井Watering Hole(堆优化prim)
P1550 [USACO08OCT]打井Watering Hole 对于自己建水库的情况,新建一个虚拟结点,和其他点的边权即为自建水库的费用 这样问题就转化为一个裸最小生成树问题了. 这里用堆优化 ...