zoukankan      html  css  js  c++  java
  • 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;
    	}
    
    }
    

      

  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    微信小程序TodoList
    C语言88案例-找出数列中的最大值和最小值
    C语言88案例-使用指针的指针输出字符串
  • 原文地址:https://www.cnblogs.com/achengmu/p/9140420.html
Copyright © 2011-2022 走看看