SpringMVC可以通过URL扩展名或请求参数来控制服务端的资源输出类型。
- SpringMVC:多视图[JSP,JSON,Excel,XML]混合输出__XML配置方式【http://blog.csdn.net/fly910905/article/details/79057245】
maven 依赖
<!--配置jsp jstl的支持-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
</dependency>
<!-- Needed for XML View(with JAXB2) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Needed for JSON View -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.1</version>
</dependency>
<!-- Needed for PDF View -->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
<scope>compile</scope>
</dependency>
<!-- Needed for XLS View -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
视图解析器
package com.newcapec.config;
import com.newcapec.util.ExcelViewResolver;
import com.newcapec.util.PdfViewResolver;
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.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.servlet.view.xml.MarshallingView;
import java.util.ArrayList;
import java.util.List;
/**
* @Title: 视图解析器--配置类
* @ClassName: com.newcapec.cloudpay.controller.util.SpringMvcConfig.java
* @Description:
*
* @Copyright2016-2018 新开普 - Powered By 研发中心
* @author: 王延飞
* @date: 2018-01-1416:52
* @version V1.0
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.newcapec.cloudpay.controller")
publicclassSpringMvcConfigextendsWebMvcConfigurerAdapter {
/*
* Configure ContentNegotiationManager
*/
@Override
publicvoidconfigureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
// 设置默认的MIME类型,如果没有指定拓展名或请求参数,则使用此默认MIME类型解析视图
.defaultContentType(MediaType.TEXT_HTML)
// 是否不适用请求头确定MIME类型
.ignoreAcceptHeader(true)
/*使用拓展名类型,不注释以下三行将使用参数(type)的方法访问*/
// 是否根据路径拓展名确定MIME类型
.favorPathExtension(false)
// 是否使用参数来确定MIME类型
.favorParameter(false)
// 上一个属性配置为true,我们指定type请求参数判断MIME类型
.parameterName("type");
}
/*
* Configure ContentNegotiatingViewResolver
*/
@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolverresolver=newContentNegotiatingViewResolver();
// 设置优先级
resolver.setOrder(1);
// 添加ContentNegotiationManager
resolver.setContentNegotiationManager(manager);
/*设置默认的候选视图,如果有合适的MIME类型,将优先从以下选择视图,找不到再在整个Spring容器里寻找已注册的合适视图 */
List<View> views = newArrayList<View>();
views.add(newMappingJackson2JsonView());
views.add(newMarshallingView());
resolver.setDefaultViews(views);
/*自定义视图解析器,或者对已有的视图进行个性化配置*/
// Define all possible view resolvers
List<ViewResolver> resolvers = newArrayList<ViewResolver>();
/*resolvers.add(jaxb2MarshallingXmlViewResolver());
resolvers.add(jsonViewResolver());*/
resolvers.add(jspViewResolver());
resolvers.add(pdfViewResolver());
resolvers.add(excelViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide XML output Uses JAXB2 marshaller to
* marshall/unmarshall POJO's (with JAXB annotations) to XML
*/
/* @Bean
public ViewResolver jaxb2MarshallingXmlViewResolver() {
Jaxb2Marshallermarshaller=newJaxb2Marshaller();
marshaller.setClassesToBeBound(Pizza.class);
returnnewJaxb2MarshallingXmlViewResolver(marshaller);
}*/
/*
* Configure View resolver to provide JSON output using JACKSON library to
* convert object in JSON format.
*/
/* @Bean
public ViewResolver jsonViewResolver() {
returnnewJsonViewResolver();
}*/
/*
* Configure View resolver to provide PDF output using lowagie pdf library to
* generate PDF output for an object content
*/
@Bean
public ViewResolver pdfViewResolver() {
returnnewPdfViewResolver();
}
/*
* Configure View resolver to provide XLS output using Apache POI library to
* generate XLS output for an object content
*/
@Bean
public ViewResolver excelViewResolver() {
returnnewExcelViewResolver();
}
/*
* Configure View resolver to provide HTML output This is the default format
* in absence of any type suffix.
*/
@Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolverviewResolver=newInternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
自定义Excel解析器
package com.newcapec.config;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
publicclassExcelViewResolverimplementsViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale)throws Exception {
ExcelViewview=newExcelView();
return view;
}
}
package com.newcapec.config;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
publicclassExcelViewextendsAbstractExcelView {
@Override
protectedvoidbuildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
RspBaseVOrspBaseVO= (RspBaseVO) model.get("RspBaseVO");
HSSFSheetsheet= workbook.createSheet("返回结果");//创建一页
HSSFRowheader= sheet.createRow(0);//创建第一行
header.createCell(0).setCellValue("返回码");
header.createCell(1).setCellValue("返回信息");
HSSFRowrow= sheet.createRow(1);
row.createCell(0).setCellValue(rspBaseVO.getCode());
row.createCell(1).setCellValue(rspBaseVO.getMsg());
}
}
自定义PDF解析器
package com.newcapec.config;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
publicclassPdfViewResolverimplementsViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale)throws Exception {
PdfViewview=newPdfView();
return view;
}
}
package com.newcapec.config;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.Map;
publicclassPdfViewextendsAbstractPdfView {
@Override
protectedvoidbuildPdfDocument(Map<String, Object> model,
Document document, PdfWriter writer, HttpServletRequest request,
HttpServletResponse response) throws Exception {
RspBaseVOrspBaseVO= (RspBaseVO) model.get("RspBaseVO");
PdfPTabletable=newPdfPTable(2);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
table.getDefaultCell().setBackgroundColor(Color.lightGray);
table.addCell("返回码");
table.addCell("返回信息");
table.addCell(rspBaseVO.getCode());
table.addCell(rspBaseVO.getMsg());
document.add(table);
}
}
实体
- import javax.xml.bind.annotation.XmlRootElement;
/**
* @Title: 返回响应值--基类
* @ClassName:RspBaseVO.java
* @Description:
*
* @Copyright2016-2017 - Powered By 研发中心
* @author: 王延飞
* @date:2018年1月12日 上午07:43:41
* @version V1.0
*/
@XmlRootElement
publicclassRspBaseVO {
private String code; // 返回码
private String msg; // 返回信息
// private String data; // 业务参数
public String getCode() {
return code;
}
publicvoidsetCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
publicvoidsetMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return"RspBaseVO [code=" + code + ", msg=" + msg + "]";
}
}
controller
/***
* .json(?type=json) -- 返回JSON
* .excel(?type=excel) -- 返回Excel
* .xml(?type=xml) -- 返回XML
* 为空-- 返回JSP
*/
@RequestMapping(value="/multiview/{code}/{msg}", method=RequestMethod.GET)
public String multiViewTest(@PathVariable String code,@PathVariable String msg, Model model) {
RspBaseVOrspBaseVO=newRspBaseVO();
rspBaseVO.setCode(code);
rspBaseVO.setMsg(msg);
model.addAttribute("RspBaseVO",rspBaseVO);
return"/com/test/codeTest";
}
jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>多视图混合输出-状态码</title>
</head>
<body>
code : ${RspBaseVO.code} <br/>
msg : ${RspBaseVO.msg}
</body>
</html>