0

我正在尝试使用 jnlp.FileSaveService 来“saveAs”在 Java Web 应用程序的控制器中生成的 .txt 文件。我在这里找到了一些示例 http://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/usingJNLPAPI.html 我不完全理解它是如何工作的,我在这一行得到空指针异常:

fc = fss.saveFileDialog(null, null, new ByteArrayInputStream(txt.getBytes()), null);

我是否将某些错误传递给方法 saveFileDialog 或者是其他什么?我将不胜感激任何帮助。

static private FileOpenService fos = null;
static private FileSaveService fss = null;
static private FileContents fc = null;

private static synchronized void initialize() {
    try {
        fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
        fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
    }
}

public static void save(String txt) {
    initialize();
    try {
        // Show save dialog if no name is already given
        if (fc == null) {
            fc = fss.saveFileDialog(null, null, new ByteArrayInputStream(txt.getBytes()), null);
            // file saved, done
            return;
        }
        // use this only when filename is known
        if (fc != null) {
            writeToFile(txt, fc);
        }
    } catch (IOException ioe) {ioe.printStackTrace(System.out);
    }
}

public static void saveAs(String txt) {
    initialize();
    try {
        if (fc == null) {
            // If not already saved. Save-as is like save
            save(txt);
        } else {
            fc = fss.saveAsFileDialog(null, null, fc);
            save(txt);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace(System.out);
    }
}

private static void writeToFile(String txt, FileContents fc) throws IOException {
    int sizeNeeded = txt.length() * 2;
    if (sizeNeeded > fc.getMaxLength()) {
        fc.setMaxLength(sizeNeeded);
    }
    BufferedWriter os = new BufferedWriter(new OutputStreamWriter(fc.getOutputStream(true)));
    os.write(txt);
    os.close();
}

@RequestMapping(value = "/exportPhonebook.html", method = RequestMethod.POST)
public String exportPhonebook(Model model) {

    List<User> listOfAllUsers = phoneBookSer.fetchAllUsers();
    String phonebook = "";

    for (User user : listOfAllUsers) {
        phonebook = phonebook + user.getSurname() + " " + user.getName() + 
        ", Phone Number: " + user.getPhoneNumber() + ";\r\n" ;
    }

    saveAs(phonebook);
}

这是堆栈跟踪

20.03.2013. 13:19:41 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [springDipatcher] in context with path [/phonebook] threw exception [Request processing failed; nested exception is     java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at phonebook.controllers.ExportPhonebook.save(ExportPhonebook.java:80)
at phonebook.controllers.ExportPhonebook.saveAs(ExportPhonebook.java:97)
at phonebook.controllers.ExportPhonebook.exportPhonebook(ExportPhonebook.java:129)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:328)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:95)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:175)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
4

1 回答 1

0

我采取了不同的方法来解决我的问题。我曾经content-disposition保存在 Controller 中生成的.txt文件。你可以在下面看到我的代码。

private void setResponseHeaderTXT(HttpServletResponse response) {
    response.setContentType("text/plain; charset=UTF-8");
    response.setHeader("content-disposition", "attachment; filename=imenik.txt" );
} 
@RequestMapping(value = "/exportPhonebook.html", method = RequestMethod.POST)
public void exportPhonebook(Model model, HttpServletResponse response) {

    List<User> listOfAllUsers = phoneBookSer.fetchAllUsers();
    String phonebook = "";

    for (User user : listOfAllUsers) {
        phonebook = phonebook + user.getSurname() + " " + user.getName() + ", + 
        ", Phone number: " + user.getPhoneNumber() + ";\r\n" ;
    }

    try {
        setResponseHeaderTXT(response);
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(phonebook.getBytes(Charset.forName("UTF-8")));
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }   
}

我使用IText将我的电话簿导出为pdf格式做了类似的事情。

private void setResponseHeaderPDF(HttpServletResponse response) {
    response.setContentType("application/pdf");
    response.setHeader("content-disposition", "attachment; filename=imenik.pdf" );
} 

@RequestMapping(value = "/exportPhonebook.html", method = RequestMethod.POST)
public void exportPhonebook(Model model, @RequestParam("buttonSpremiImenik") String buttonSpremiImenik, HttpServletResponse response, HttpServletRequest request) {

    try {
        setResponseHeaderPDF(response);
        Document document = new Document();
        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
        PdfWriter pdfWriter = null;
        pdfWriter = PdfWriter.getInstance(document, baosPDF);
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document);
        document.close();
        pdfWriter.close();
        OutputStream os = response.getOutputStream();
        baosPDF.writeTo(os);
        os.flush();
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.BOLD);
private static Font tableHeaderFont = new Font(Font.FontFamily.TIMES_ROMAN, 10,Font.BOLD);
public static String[][] FONTS = {{"c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H}};


private static void addMetaData(Document document) {
    document.addTitle("Phonebook");
    document.addSubject("phonebook");
    document.addKeywords("phonebook");
    document.addAuthor("John Smith");
    document.addCreator("John Smith");
}
private static void addTitlePage(Document document) throws DocumentException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);
    preface.add(new Paragraph("Phonebook", catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph("Generated: " + new Date(), smallBold));
    addEmptyLine(preface, 1);
    document.add(preface);
}

private void addContent(Document document) throws DocumentException {

    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 1);

    // Add a table
    createTable(paragraph);

    // Now add all this to the document
    document.add(paragraph);
}


private static void addEmptyLine(Paragraph paragraph, int number) {
    for (int i = 0; i < number; i++) {
        paragraph.add(new Paragraph(" "));
    }
}
private void createTable(Paragraph paragraf) throws DocumentException {

    PdfPTable table = new PdfPTable(9);
    table.setTotalWidth(new float[]{ 58, 50, 95, 60, 60, 135, 60, 42, 30 });
    table.setLockedWidth(true);

    List<User> listOfAllUsers = phoneBookSer.fetchAllUsers();

    PdfPCell c1 = new PdfPCell(new Phrase("Prezime", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Ime", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Organizacijska jedinica", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Telefon", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Telefaks", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("E-mail", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Lokacija", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Kat", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Soba", tableHeaderFont));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    table.setHeaderRows(1);


    BaseFont bf = null;
    try {
        bf = BaseFont.createFont(FONTS[0][0], FONTS[0][1], BaseFont.EMBEDDED);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Font fontArial = new Font(bf, 9);

    //Automatically detects fonts
    //FontFactory.registerDirectories();
    //Font fontArial9 = FontFactory.getFont("Arial", 9);

    for (User user : listOfAllUsers) {
        PdfPCell cell1 = new PdfPCell(new Phrase(user.getPrezime(), fontArial));
        table.addCell(cell1);
        PdfPCell cell2 = new PdfPCell(new Phrase(user.getIme(), fontArial));
        table.addCell(cell2);
        PdfPCell cell3 = new PdfPCell(new Phrase(user.getOrganizacijskaJedinica(), fontArial));
        table.addCell(cell3);
        PdfPCell cell4 = new PdfPCell(new Phrase(user.getTelefon(), fontArial));
        table.addCell(cell4);
        PdfPCell cell5 = new PdfPCell(new Phrase(user.getTelefaks(), fontArial));
        table.addCell(cell5);
        PdfPCell cell6 = new PdfPCell(new Phrase(user.getEmail(), fontArial));
        table.addCell(cell6);
        PdfPCell cell7 = new PdfPCell(new Phrase(user.getLokacija(), fontArial));
        table.addCell(cell7);
        PdfPCell cell8 = new PdfPCell(new Phrase(user.getKat(), fontArial));
        table.addCell(cell8);
        PdfPCell cell9 = new PdfPCell(new Phrase(user.getBrojSobe(), fontArial));
        table.addCell(cell9);
    }

    paragraf.add(table);
}
于 2013-03-25T11:55:34.517 回答