`
wiselyman
  • 浏览: 2093962 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
博客专栏
Group-logo
点睛Spring4.1
浏览量:82327
74ae1471-94c5-3ae2-b227-779326b57435
点睛Spring MVC4...
浏览量:130798
社区版块
存档分类
最新评论

07点睛Spring MVC4.1-ContentNegotiatingViewResolver

 
阅读更多

7.1 ContentNegotiatingViewResolver

  • 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

7.2 示例

7.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>

7.2.2 定制view和viewResolve

7.2.2.1 pdf

7.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);
    }

}
7.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();
    }


}

7.2.2.2 xls

7.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);

    }

}
7.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();
    }

}

7.2.2.3 json

7.2.2.3.1 view

使用的是MappingJackson2JsonView

7.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;
    }

}

7.2.2.4 xml

7.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;
    }

}
7.2.2.4.2 view

使用的是MarshallingView

7.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;
    }

}

7.2.2.5 jsp

7.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>
7.2.2.5.2 viewResolver

UrlBasedViewResolverInternalResourceViewResolver

7.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();
    }

}

7.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";

    }

}

7.2.5 结果

7.2.5.1 jsp

7.2.5.2 json

7.2.5.3 pdf

7.2.5.4 xml

7.2.5.5 xls

 

 

 

新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

 

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


4
0
分享到:
评论
2 楼 wiselyman 2015-07-01  
FondaWu 写道
pdf和xls还都是调用浏览器本地插件显示的吧
另外
DemoObj demoObj = new DemoObj(333l, "WYF");
这句应该改成“DemoObj demoObj = new DemoObj(333, "WYF")”;吧?



DemoObj的id是long型的,所以加了l
1 楼 FondaWu 2015-07-01  
pdf和xls还都是调用浏览器本地插件显示的吧
另外
DemoObj demoObj = new DemoObj(333l, "WYF");
这句应该改成“DemoObj demoObj = new DemoObj(333, "WYF")”;吧?

相关推荐

    4.1-细胞分化形成组织.pptx

    细胞分化是生物体发育过程中的关键环节,它使得单一的受精卵细胞逐渐发展成为具有各种不同特性的细胞群体,最终构建出复杂的生命体。在医学领域,理解细胞分化对于研究胚胎发育、组织修复和疾病的发生机制至关重要。...

    国元点睛-20230825-国元期货-23页.pdf

    国元点睛-20230825-国元期货-23页

    JavaEE开发的颠覆者SpringBoot实战[完整版].part3

    第二部分 点睛Spring MVC 4.x 第4 章 Spring MVC 基础 72 4.1 Spring MVC 概述 73 4.2 Spring MVC 项目快速搭建 74 4.2.1 点睛 74 4.2.2 示例 74 4.3 Spring MVC 的常用注解 82 4.3.1 点睛 82 4.3.2 示例 83 4.4 ...

    stasm4.1版本-人脸识别77个特征点提取

    **STASM4.1版本-人脸识别77个特征点提取** STASM,全称为Shape Tracking and Analysis by Shape Models,是一种广泛应用于人脸识别领域的算法,尤其在面部特征点定位方面表现出色。该算法的核心在于通过形状模型来...

    JavaEE开发的颠覆者SpringBoot实战[完整版].part2

    第二部分 点睛Spring MVC 4.x 第4 章 Spring MVC 基础 72 4.1 Spring MVC 概述 73 4.2 Spring MVC 项目快速搭建 74 4.2.1 点睛 74 4.2.2 示例 74 4.3 Spring MVC 的常用注解 82 4.3.1 点睛 82 4.3.2 示例 83 4.4 ...

    JavaEE开发的颠覆者SpringBoot实战[完整版].part1

    第二部分 点睛Spring MVC 4.x 第4 章 Spring MVC 基础 72 4.1 Spring MVC 概述 73 4.2 Spring MVC 项目快速搭建 74 4.2.1 点睛 74 4.2.2 示例 74 4.3 Spring MVC 的常用注解 82 4.3.1 点睛 82 4.3.2 示例 83 4.4 ...

    BugScan圈子沙龙之议题点睛(2015) - 安全技术资料汇总(共5份).zip

    bugscan发展历程以及框架改进.pdf 基于正则类sql注入防御的绕过技巧.pdf 如何优雅的穿透linux内网.pdf 花式玩转bugscan插件.pdf 过滤型插件与反向代理的火花.pdf

    PS眼睛糖果滤镜eye-candy-7.1.0.1203汉化破解版(附安装视频)

    alien skin Eye Candy 7是一款非常强大的PS滤镜插件。包含了金属字、火焰、闪电、纹理等30多种实用特效,是设计师必备的插件之一。

    司机眼睛状态标记---应用OpenCV人脸检测与模板匹配方法

    使用OpenCV1.0实现了眼睛状态识别,首先用harr检测眼睛,然后用模板匹配的方法标记眼睛状态。 程序需要使用Eyes45x11.xml Mouth25x15.xml Nose25x15.xml,将其放到C:\Program Files\OpenCV\data\haarcascades目录下...

    眼睛穴位图-睛明穴-取穴方法

    眼睛穴位图-睛明穴-取穴方法 方便经常上网的朋友使用

    chrome 眼睛护航插件 Care-your-Eyes_v7.1.12.crx

    把网页背景变成眼睛保护色或适合夜晚阅读的夜间模式,一些无法变色的小区块可以通过单击进行变色;

    点睛文本编码查询(文本的字符串转换工具)

    软件名:点睛文本编码查询 功能:本软件用于将文本的字符串转换为 Text、ASCII、Default、Unicode、BigEndianUnicode、UTF-8、UTF-7、GBK、BIG5 之间的互相转换,用于文本查询。转换结果使用十六进制表示。

    点睛网赚论坛源码整站程序+10W数据【送主动推送工具】

    点睛网赚论坛源码整站程序+10W数据【送主动推送工具】 安装教程https://www.ygwzjs.cn/post/260.html 百度推送工具https://www.ygwzjs.cn/post/181.html 效果演示:z-www.seoheimao.cn 【全新优化】点睛网论坛整站...

    360点睛多语言加密示例和密码加密调试工具.zip

    《360点睛营销平台多语言加密及调试技术详解》 360点睛营销开放平台是一款由360公司推出的广告投放和营销管理工具,它为开发者提供了丰富的API接口,以帮助开发者构建和优化自己的广告系统。在这个名为"360点睛多...

    api-document:java spring-mvc文件收集

    中文说明 | |说明维护过项目的人应该都有体会, 如果接口文档是单独编写的(org-mode、markdown、rap 甚至是 word 等), 随着项目周期的推进, 接口文档和真实代码之间的差距会越来越远.基于 swagger 的一些细节不那么让...

    360点睛使用手册(2019.08).pdf

    360点睛使用手册是360官方于2019年推出的移动客户端软件,主要功能是推广管理。该手册详细介绍了软件的使用方法和功能特点,适用于广告主进行随时随地的账户投放管理。 首先,手册中的产品介绍部分指出,360点睛是...

    点睛 内码转换器

    "点睛内码转换器"是一款专为处理文本编码问题设计的工具,它能够帮助用户在不同的字符编码之间进行转换,以解决由于编码不匹配导致的乱码问题。在计算机科学领域,字符编码是用于表示文本的一系列规则,常见的有...

    点睛字符替换器 v1.05特别修正版.rar

    点睛字符替换器v1.05特别修正版是一款针对文本处理的专业软件,主要用于批量替换文本中的特定字符或字符串。这个特别修正版可能是对原始版本的优化和改进,以解决某些问题或添加新功能。在IT领域,字符替换工具是...

    点睛网赚论坛整站程序+全套数据.zip

    【标题】"点睛网赚论坛整站程序+全套数据.zip"所涵盖的知识点主要集中在网站建设和运营领域,特别是关于论坛程序和数据管理方面。这个压缩包文件提供了一个完整的网络赚钱论坛的源代码和所有相关数据,对于想要搭建...

    点睛字串替换器

    点睛字串替换器

Global site tag (gtag.js) - Google Analytics