8. Spring MVC4.1-ContentNegotiatingViewResolver

翻译 2015年11月19日 21:52:09
  • ContentNegotiatingViewResolver支持在Spring MVC下输出不同的格式;
  • ContentNegotiatingViewResolver是ViewResolver的一个实现;
  • ContentNegotiatingViewResolver使用request的媒体类型,根据扩展名选择不同的view输出不同的格式;
  • ContentNegotiatingViewResolver不是自己处理view,而是代理给不同的ViewResolver来处理不同的view;
  • 本例演示根据扩展名获得不同的页面;
  • jsp
    • view:WEB-INF/views/demoObj.jsp
    • viewResolver:UrlBasedViewResolverInternalResourceViewResolver
  • pdf
    • view:PdfView
    • viewResolver:PdfViewResolver
  • json
    • view:MappingJackson2JsonView
    • viewResolver:JsonViewResolver
  • xml
    • view:MarshallingView
    • viewResolver:XmlViewResolver
  • xls
    • view:XlsView
    • viewResolver:XlsViewResolver

8.2 示例

8.2.1 添加依赖

  • 依赖

    • json依赖03点睛Spring MVC 4.1-REST已添加
    • xml
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring-framework.version}</version>
    </dependency>
    • pdf
    <dependency>
      <groupId>com.lowagie</groupId>
      <artifactId>itext</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    • xls
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.10-beta2</version>
    </dependency>

8.2.2 定制view和viewResolve

8.2.2.1 pdf

8.2.2.1.1 view
 package com.wisely.view;

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 com.wisely.domain.DemoObj;

public class PdfView extends AbstractPdfView {

    @Override
    protected void buildPdfDocument(Map<String, Object> model,
            Document document, PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        DemoObj demoObj = (DemoObj) model.get("demoObj");

        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.getDefaultCell().setBackgroundColor(Color.lightGray);

        table.addCell("ID");
        table.addCell("NAME");

        table.addCell(demoObj.getId().toString());
        table.addCell(demoObj.getName());

        document.add(table);
    }

}
8.2.2.1.2 viewResolver
package com.wisely.viewresolver;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import com.wisely.view.PdfView;

public class PdfViewResolver implements ViewResolver{

    @Override
    public View resolveViewName(String viewName, Locale locale)
            throws Exception {
        return new PdfView();
    }


}

8.2.2.2 xls

8.2.2.2.1 view
package com.wisely.view;

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 com.wisely.domain.DemoObj;

public class XlsView extends AbstractExcelView{

    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
         DemoObj demoObj = (DemoObj) model.get("demoObj");

            Sheet sheet = workbook.createSheet("sheet1");
            CellStyle style = workbook.createCellStyle();
            style.setFillForegroundColor(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;

            // 创建头部
            row = sheet.createRow(rowCount++);

            cell = row.createCell(colCount++);
            cell.setCellStyle(style);
            cell.setCellValue("ID");

            cell = row.createCell(colCount++);
            cell.setCellStyle(style);
            cell.setCellValue("NAME");


            // 创建数据
            row = sheet.createRow(rowCount++);
            colCount = 0;
            row.createCell(colCount++).setCellValue(demoObj.getId());
            row.createCell(colCount++).setCellValue(demoObj.getName());
            for (int i = 0; i < 3; i++)
                sheet.autoSizeColumn(i, true);

    }

}
8.2.2.2.2 viewResolver
package com.wisely.viewresolver;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import com.wisely.view.XlsView;

public class XlsViewResolver implements ViewResolver{

    @Override
    public View resolveViewName(String viewName, Locale locale)
            throws Exception {
        return new XlsView();
    }

}

8.2.2.3 json

8.2.2.3.1 view

使用的是MappingJackson2JsonView

8.2.2.3.2 viewResolver
package com.wisely.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{

    @Override
    public View resolveViewName(String viewName, Locale locale)
            throws Exception {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setPrettyPrint(true);
        return view;
    }

}

8.2.2.4 xml

8.2.2.4.1 DemoBean的额外配置
package com.wisely.domain;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "demo")
public class DemoObj {
    private Long id;
    private String name;

    public DemoObj() {
        super();
    }

    public DemoObj(Long id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    @XmlElement
    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

}
8.2.2.4.2 view

使用的是MarshallingView

8.2.2.4.3 viewResolver
package com.wisely.viewresolver;

import java.util.Locale;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.xml.MarshallingView;

import com.wisely.domain.DemoObj;

public class XmlViewResolver implements ViewResolver {

    @Override
    public View resolveViewName(String viewName, Locale locale)
            throws Exception {
        MarshallingView view = new MarshallingView();
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setClassesToBeBound(DemoObj.class);
        marshaller.setPackagesToScan("com.wisely.domain");
        view.setMarshaller(marshaller);
        return view;
    }

}

8.2.2.5 jsp

8.2.2.5.1 view

WEB-INF/views/demoObj.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

</head>
<body>
        id/name <br/>
        ${demoObj.id}/${demoObj.name}
</body>
</html>
8.2.2.5.2 viewResolver

UrlBasedViewResolverInternalResourceViewResolver

8.2.3 配置resolver

package com.wisely;

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.web.accept.ContentNegotiationManager;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
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.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import com.wisely.interceptors.DemoInteceptor;
import com.wisely.viewresolver.JsonViewResolver;
import com.wisely.viewresolver.PdfViewResolver;
import com.wisely.viewresolver.XlsViewResolver;
import com.wisely.viewresolver.XmlViewResolver;

@Configuration
@ComponentScan("com.wisely")
@EnableWebMvc
public class DemoMVCConfig extends WebMvcConfigurerAdapter {

    //在此---jsp viewResolver
    @Bean
    public UrlBasedViewResolver viewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    // 注册自定义拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInteceptor());
    }

    // 自定义拦截器
    @Bean
    public DemoInteceptor demoInteceptor() {
        return new DemoInteceptor();
    }

    // 静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
    }

    // 文件上传设置
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(1000000);
        return multipartResolver;
    }

    // 在此---配置ContentNegotiationManager,在无后缀名情况下默认为jsp view resolver
    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer) {
        configurer.ignoreAcceptHeader(true).defaultContentType(
                MediaType.TEXT_HTML);
    }

    // 在此---配置ContentNegotiatingViewResolver,通过此代理到不同的viewResolover
    @Bean
    public ViewResolver contentNegotiatingViewResolver(
            ContentNegotiationManager manager) {

        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        resolver.setContentNegotiationManager(manager);
        List<ViewResolver> resolvers = new ArrayList<ViewResolver>();

        resolvers.add(xmlViewResolver());
        resolvers.add(jsonViewResolver());
        resolvers.add(viewResolver());// jsp view resolver
        resolvers.add(pdfViewResolver());
        resolvers.add(xlsViewResolver());

        resolver.setViewResolvers(resolvers);
        return resolver;
    }

    //在此---xml viewResolver
    @Bean
    public ViewResolver xmlViewResolver() {
        return new XmlViewResolver();
    }

    //在此---json viewResolver
    @Bean
    public ViewResolver jsonViewResolver() {
        return new JsonViewResolver();
    }
    //在此---pdf viewResolver
    @Bean
    public ViewResolver pdfViewResolver() {
        return new PdfViewResolver();
    }
    //在此---excel viewResolver
    @Bean
    ViewResolver xlsViewResolver() {
        return new XlsViewResolver();
    }

}

8.2.4 演示控制器

package com.wisely.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wisely.domain.DemoObj;

@Controller
public class ContentController {
    @RequestMapping(value = "/getdemo",method = RequestMethod.GET)
    public String getDemo(Model model){
        DemoObj demoObj = new DemoObj(333l, "WYF");
        model.addAttribute("demoObj",demoObj);
        return "demoObj";

    }

}

8.2.5 结果

8.2.5.1 jsp

8.2.5.2 json

8.2.5.3 pdf

8.2.5.4 xml

Spring事物管理理解

数据库事务概述 数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完整地执行,要么完全地不执行。 事务处理可以确保除非事务性单元...
  • WMY1230
  • WMY1230
  • 2016年11月29日 14:28
  • 441

数据库 连接池的深入理解

一、应用程序直接获取数据库连接的缺点   用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长。假设网站一天10万访问量,数据库服务器就需要创建10万次...
  • yanlove_jing
  • yanlove_jing
  • 2016年05月23日 16:42
  • 3596

Android开发记录八之ContentProvider的使用方法

1.什么是ContentProvider  数据库在Android当中是私有的,当然这些数据包括文件数据和数据库数据以及一些其他类型的数据。  不能将数据库设为WORLD_READABLE,每个数...
  • u010467643
  • u010467643
  • 2014年07月11日 21:19
  • 1269

怎样提高网站用户体验

对于任何一个网站来说,无论是企业网站、行业门户,还是B2C或者B2B,抓住用户体验是我们提升网站竞争力的一个重要指标。怎样才能抓住用户体验,可以从这五个方面来把握:  1、感官体验:呈现给用户视听上...
  • vigor512
  • vigor512
  • 2015年04月20日 11:24
  • 251

8.玩转Spring Boot 日志配置

玩转Spring Boot 日志配置 Spring Boot 使用Commons Logging作为内部日志记录。对Java Util Logging, Log4J2 and Logback. 提供...
  • cl_andywin
  • cl_andywin
  • 2016年12月21日 12:32
  • 443

【前端】Node.js 9.0来了_有哪些不一样的体验?

点击有惊喜 Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。 Node.js 的...
  • yunqishequ1
  • yunqishequ1
  • 2017年11月15日 14:12
  • 199

Java基础之(二十六)对象与垃圾回收

说明 当程序创建对象、数组等引用类型实体时,系统会在堆内存中为之分配一块内存用以保存对象,当这块内存不再被任何引用变量引用时,这块内存就变成垃圾,等待垃圾回收机制回收。 垃圾回收机制只回收堆内存中的...
  • jxq1994
  • jxq1994
  • 2016年08月16日 14:47
  • 352

8.关于看门狗

关于看门狗啊,这个东西之前挺不常用的,因为这些东西都是一些防御型的外设什么的,平时没事谁会用 他们啊,刚开始肯定都会认为自己写的代码无懈可击,也不算是吧,反正就是绝大多数下都不会出什么问题 但是真等到...
  • zhiyu_buliang
  • zhiyu_buliang
  • 2018年01月03日 09:03
  • 25

说说struts1与struts2的区别。

1.都是MVC的WEB框架,      2 struts1的老牌框架,应用很广泛,有很好的群众基础,使用它开发风险很小,成本更低!struts2虽然基于这个框架,但是应用群众并多,相对不成熟,未知...
  • u012927417
  • u012927417
  • 2014年08月06日 16:49
  • 920

Hibernate中对象的三种状态,以及三种状态间的转化方法

在Hibernate中有三种状态,对它的深入理解,才能更好的理解hibernate的运行机理,刚开始不太注意这些概念,后来被别人问到了,说是面试题,才发现它是重要的。对于需要持久化的JAVA对象,在它...
  • fangleijiang
  • fangleijiang
  • 2014年09月12日 10:55
  • 1715
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:8. Spring MVC4.1-ContentNegotiatingViewResolver
举报原因:
原因补充:

(最多只允许输入30个字)