Spring内容协商以及视图解析

概念

1)MediaType,即是Internet Media Type,互联网媒体类型;也叫做MIME类型。
2)Content-Type代表发送端(客户端|服务器)发送的实体数据的数据类型。
3)Accept代表发送端(客户端)希望接受的数据类型。
4)常见的MediaType
text/html、text/xml、image/png
application/json、application/x-www-form-urlencoded (表单默认的提交数据的格式)、multipart/form-data (文件上传)
5)导出excel,返回字节数组response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("中文url编码","UTF-8") + ".xls");
6)类型格式:type/subtype(;parameter)

1,Spring视图解析

1)jsp视图解析

@Bean//配置视图解析viewResolver(spring mvc的9大组件)
public InternalResourceViewResolver internalResourceViewResolver(){
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
        internalResourceViewResolver.setSuffix(".jsp");

        return internalResourceViewResolver;
}

2)thymeleaf视图解析(需要引入compile 'org.thymeleaf:thymeleaf-spring4:3.0.3.RELEASE'和compile 'org.thymeleaf:thymeleaf:3.0.3.RELEASE')

@Bean
    public ThymeleafViewResolver thymeleafViewResolver(){
        ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
        thymeleafViewResolver.setOrder(1);
        thymeleafViewResolver.setCharacterEncoding("utf-8");
        thymeleafViewResolver.setTemplateEngine(templateEngine());

        return thymeleafViewResolver;
    }

@Bean
    public SpringTemplateEngine templateEngine(){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        templateEngine.addDialect("shiro", new ShiroDialect());

        return templateEngine;
    }

@Bean
    public SpringResourceTemplateResolver templateResolver(){
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        templateResolver.setCacheable(false);//设置热部署
        templateResolver.setOrder(1);
        templateResolver.setCharacterEncoding("UTF-8");

        return templateResolver;
    }

2,基于视图的method与基于restful的method。

@Controller
class AccountController {
    // RESTful method
    @RequestMapping(value="/accounts", produces={"application/xml", "application/json"})
    @ResponseBody//会经过内容协商,返回具体的视图
    public  List listWithMarshalling(Principal principal) {
        return accountManager.getAccounts(principal);
    }

    // View-based method
    @RequestMapping("/accounts")//`会使用配置的viewResolver`
    public String listWithView(Model model, Principal principal) {
        // Call RESTful method to avoid repeating account lookup logic
        model.addAttribute( listWithMarshalling(principal) );

        // Return the view to use for rendering the response
        return ¨accounts/list¨;
    }
}

3,重写WebMvcConfigurerAdapter的configureContentNegotiation方法,配置内容协商的策略。

    /**
     * 配置内容协商的策略
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        Map mediaTypeMap = new HashMap<>();
        mediaTypeMap.put("html", MediaType.TEXT_HTML);
        mediaTypeMap.put("json", MediaType.APPLICATION_JSON);
        mediaTypeMap.put("atom", MediaType.APPLICATION_ATOM_XML);

        configurer.favorParameter(false)//是否支持format=json参数
                .favorPathExtension(false).useJaf(false)//是否支持.json .xml等扩展名
                .ignoreAcceptHeader(true)//忽视Accept请求头
                .defaultContentType(MediaType.APPLICATION_JSON)//默认返回的context-type
                .mediaTypes(mediaTypeMap);

        super.configureContentNegotiation(configurer);
    }

4,配置内容协商的多视图解析器。

    @Bean
    public ContentNegotiatingViewResolver contentNegotiatingViewResolver(){
        ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
        List viewResolverList = new ArrayList<>();
        viewResolverList.add(thymeleafViewResolver());

        List viewList = new ArrayList<>();
        viewList.add(mappingJackson2JsonView()); // 配置默认视图解析

        contentNegotiatingViewResolver.setOrder(1);
        contentNegotiatingViewResolver.setViewResolvers(viewResolverList);
        contentNegotiatingViewResolver.setDefaultViews(viewList);

        return contentNegotiatingViewResolver;
    }

@Bean
    public MappingJackson2JsonView mappingJackson2JsonView(){
        return new MappingJackson2JsonView();//使用MappingJackson2JsonView 配合@ResponseBody来返回JSON格式
    }

你可能感兴趣的:(Spring内容协商以及视图解析)