Spring Boot为不同的视图自定义ViewResolver。查看json,xml,pdf,xls

时间:2017-09-15 12:27:56

标签: java xml spring spring-boot xml-parsing

我有两个观点(用户,事故)。构建适用于用户的应用程序。我需要修改的地方,它适用于许多视图。

对于Json,我得到两个观点的结果。

正在努力:

本地主机:9001 / user_data.xml

本地主机:9001 / user_data.json

本地主机:9001 / user_data.pdf

本地主机:9001 / user_data.xls

本地主机:9001 / accident_data.json

我想为以下内容呈现数据:

本地主机:9001 / accident_data.xml

本地主机:9001 / accident_data.pdf

本地主机:9001 / accident_data.xls

我将pdf,xls和xml的代码分别放入AbstractView扩展的相应视图中。

我需要更新代码,任何人都可以指导我吗?我收集视图名称并修改响应的位置。

对于XML,我编码如下:

公共抽象类AbstractXmlView扩展了AbstractView {

public AbstractXmlView() {
    setContentType("application/xml");
}

@Override
protected boolean generatesDownloadContent() {
    return true;
}

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,HttpServletResponse response) throws Exception {
     response.setContentType(getContentType());
     buildXmlDocument(model, request, response);
     System.out.println(response);

}

public abstract void buildXmlDocument(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response);

}

@Component 公共类XmlView扩展了AbstractXmlView {

@SuppressWarnings("unchecked")
@Override
public void buildXmlDocument(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
    // TODO Auto-generated method stub
     response.setContentType("application/xml");
     response.setCharacterEncoding("UTF-8");

    JAXBContext jaxbContext = null;
    Marshaller jaxbMarshaller = null;
    try {
        jaxbContext = JAXBContext.newInstance(Users.class);
        jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
        Users users=new Users();
        users.setUser( (List<User>) model.get("users"));
        System.out.println("Users Object: "+users.getUser());
        jaxbMarshaller.marshal(users, response.getWriter());
    } catch (Exception e) {
        e.printStackTrace();
    }


    //jaxbMarshaller.marshal(Users, System.out);

}

}

添加到解析器中:

@Bean
public ViewResolver xmlViewResolver() {

    return new XmlViewResolver();
}

@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
    resolver.setContentNegotiationManager(manager);

    // Define all possible view resolvers
    List<ViewResolver> resolvers = new ArrayList<>();
    resolvers.add(xmlViewResolver());
    resolvers.add(csvViewResolver());
    resolvers.add(excelViewResolver());
    resolvers.add(pdfViewResolver());
    resolvers.add(jsonViewResolver());
    resolver.setViewResolvers(resolvers);
    return resolver;
}

0 个答案:

没有答案