Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在SpringMVC中下载pdf文件并重定向到主页_Java_Spring_Spring Mvc - Fatal编程技术网

Java 如何在SpringMVC中下载pdf文件并重定向到主页

Java 如何在SpringMVC中下载pdf文件并重定向到主页,java,spring,spring-mvc,Java,Spring,Spring Mvc,下面的代码工作正常,没有错误,但不能按要求工作 问题1:我想下载pdf文件并重定向到主页 页面(url:../)。当我转到url(../admin/generate\u pdf)时 问题2:当我在Pdfdemo.java中取消注释注释注释行时 给我一个404页找不到的错误 Pdfdemo.java public class Pdfdemos { private static String USER_PASSWORD = "password"; private static Str

下面的代码工作正常,没有错误,但不能按要求工作

问题1:我想下载pdf文件并重定向到主页 页面(url:../)。当我转到url(../admin/generate\u pdf)时

问题2:当我在Pdfdemo.java中取消注释注释注释行时 给我一个404页找不到的错误

Pdfdemo.java

public class Pdfdemos {
    private static String USER_PASSWORD = "password";
    private static String OWNER_PASSWORD = "lokesh";

        public String generate_pdf() {
            try {
                String file_name="d:\\sanjeet7.pdf";
                Document document= new Document();
                PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(file_name));

//              writer.setEncryption(USER_PASSWORD.getBytes(),
//                          OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING |PdfWriter.ALLOW_ASSEMBLY|
//                          PdfWriter.ALLOW_COPY|
//                          PdfWriter.ALLOW_DEGRADED_PRINTING|
//                          PdfWriter.ALLOW_FILL_IN|
//                          PdfWriter.ALLOW_MODIFY_ANNOTATIONS|
//                          PdfWriter.ALLOW_MODIFY_CONTENTS|
//                          PdfWriter.ALLOW_SCREENREADERS|
//                          PdfWriter.ALLOW_ASSEMBLY|
//                          PdfWriter.ENCRYPTION_AES_128, 0);


                document.open();
                document.add(new Paragraph(" "));document.add(new Paragraph(" "));
                String days_in_week[]= {"monday","tuesday","webnesday","thursday","friday","saturday"};
                int period=8;
                String user="springstudent";
                String pass="springstudent";
                String jdbcUrl="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false";
                String driver="com.mysql.jdbc.Driver";
                Connection myconn=DriverManager.getConnection(jdbcUrl,user,pass);
                PreparedStatement ps=null;
                ResultSet rs=null;
                String query="select * from class_t";
                ps=myconn.prepareStatement(query);
                rs=ps.executeQuery();
                while(rs.next()) {
                    Paragraph para=new Paragraph("Time table for class"+rs.getString("class")+rs.getString("section"));
                    document.add(para);
                    System.out.println(rs.getInt("id"));
                    PdfPTable table=new PdfPTable(period+1);
                    for(int i=0;i<days_in_week.length;i++) {

                        for(int j=0;j<period+1;j++) {

                            if(j==5) {
                                table.addCell("recess");
                            }else {

                                table.addCell("this is "+j);
                            }


                        }


                    }
                    document.add(table);
                    document.newPage();

                }
                document.close();
                System.out.println("finish");





            return file_name;

            }catch(Exception e) {
                System.out.println(e);
            }
            return null;


        }

}
@Controller
@RequestMapping("/admin/generate_pdf")
public class Generate_pdf_Controller {


    @GetMapping("/online")
    public String generating_pdf(Model theModel) {
        System.out.println("hello");
        CustomerServiceImpl pal=new CustomerServiceImpl();
        Pdfdemos pal1=new Pdfdemos();
        String xx=pal1.generate_pdf();
        return "redirect:/";
    }
}
只需获取pdf(从本地文件系统下载到浏览器中),以下代码就足够了:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin/generate_pdf")
public class PdfController {

    @GetMapping(value = "/online", /*this is "nice to have" ->*/ produces = MediaType.APPLICATION_PDF_VALUE)
    @ResponseBody // this is important, as the return type byte[]
    public byte[] generating_pdf() throws IOException {//exception handling...
        System.out.println("hello");//logging
        // re-generate new file if needed (thread-safety!)...
        // ..and dump the content as byte[] response body:
        return Files.readAllBytes(Paths.get("d:\\sanjeet7.pdf"));
    }
}
。。。如果您需要“刷新”,您可以“重写”文件/重新调用您的服务,但仍然可能不是“线程最安全”的解决方案

编辑:无需进一步配置(端口/上下文根/…),您应在以下位置访问:


如果您想“操作更接近字节”,并使用
void
返回类型/no
@ResponseBody
想要额外的重定向(待测试),我认为这应该仍然有效:

@Controller
public class ... {

   @GetMapping(value = ..., produces ...)
   //no request body, void return type, response will be autowired and can be handled
   public void generatePdf(javax.servlet.http.HttpServletResponse response) throws ... {
      java.io.OutputStream outStr = response.getOutputStream();
      // dump from "somewhere" into outStr, "finally" close.
      outStr.close();
      //TO BE TESTED:
      response.sendRedirect("/");
   }
}
..甚至(返回“视图名称”+操作outputStream):

只需获取pdf(从本地文件系统下载到浏览器中),以下代码就足够了:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin/generate_pdf")
public class PdfController {

    @GetMapping(value = "/online", /*this is "nice to have" ->*/ produces = MediaType.APPLICATION_PDF_VALUE)
    @ResponseBody // this is important, as the return type byte[]
    public byte[] generating_pdf() throws IOException {//exception handling...
        System.out.println("hello");//logging
        // re-generate new file if needed (thread-safety!)...
        // ..and dump the content as byte[] response body:
        return Files.readAllBytes(Paths.get("d:\\sanjeet7.pdf"));
    }
}
。。。如果您需要“刷新”,您可以“重写”文件/重新调用您的服务,但仍然可能不是“线程最安全”的解决方案

编辑:无需进一步配置(端口/上下文根/…),您应在以下位置访问:


如果您想“操作更接近字节”,并使用
void
返回类型/no
@ResponseBody
想要额外的重定向(待测试),我认为这应该仍然有效:

@Controller
public class ... {

   @GetMapping(value = ..., produces ...)
   //no request body, void return type, response will be autowired and can be handled
   public void generatePdf(javax.servlet.http.HttpServletResponse response) throws ... {
      java.io.OutputStream outStr = response.getOutputStream();
      // dump from "somewhere" into outStr, "finally" close.
      outStr.close();
      //TO BE TESTED:
      response.sendRedirect("/");
   }
}
..甚至(返回“视图名称”+操作outputStream):


创建和下载PDF的简化版本:

@Service
public class PdfService {

    public InputStream createPdf() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, out);

        writer.setEncryption("user_password".getBytes(), "owner_password".getBytes(),
                    PdfWriter.ALLOW_PRINTING |
                    PdfWriter.ALLOW_ASSEMBLY |
                    PdfWriter.ALLOW_COPY |
                    PdfWriter.ALLOW_DEGRADED_PRINTING |
                    PdfWriter.ALLOW_FILL_IN |
                    PdfWriter.ALLOW_MODIFY_ANNOTATIONS |
                    PdfWriter.ALLOW_MODIFY_CONTENTS |
                    PdfWriter.ALLOW_SCREENREADERS |
                    PdfWriter.ALLOW_ASSEMBLY |
                    PdfWriter.ENCRYPTION_AES_128, 0);

        document.open();

        document.add(new Paragraph("My example PDF document"));
        // some logic here

        document.close();

        return new ByteArrayInputStream(out.toByteArray());
    }
}


@Controller
@RequestMapping("/admin/generate_pdf")
public class PdfController {

    @Autowired
    private PdfService pdfService;

    @GetMapping("/online")
    public void generatePdf(HttpServletResponse response) throws Exception {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"mydocument.pdf\"");

        InputStream pdf = pdfService.createPdf();
        org.apache.commons.io.IOUtils.copy(pdf, response.getOutputStream());
        response.flushBuffer();
    }
}

至于重定向呢,正如我在评论中所说的,你可以在前端使用JS(在调用
/admin/generate\u pdf/online
url之后)进行重定向。您不能同时下载文件和进行刷新/重定向。

创建和下载PDF的简化版本:

@Service
public class PdfService {

    public InputStream createPdf() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, out);

        writer.setEncryption("user_password".getBytes(), "owner_password".getBytes(),
                    PdfWriter.ALLOW_PRINTING |
                    PdfWriter.ALLOW_ASSEMBLY |
                    PdfWriter.ALLOW_COPY |
                    PdfWriter.ALLOW_DEGRADED_PRINTING |
                    PdfWriter.ALLOW_FILL_IN |
                    PdfWriter.ALLOW_MODIFY_ANNOTATIONS |
                    PdfWriter.ALLOW_MODIFY_CONTENTS |
                    PdfWriter.ALLOW_SCREENREADERS |
                    PdfWriter.ALLOW_ASSEMBLY |
                    PdfWriter.ENCRYPTION_AES_128, 0);

        document.open();

        document.add(new Paragraph("My example PDF document"));
        // some logic here

        document.close();

        return new ByteArrayInputStream(out.toByteArray());
    }
}


@Controller
@RequestMapping("/admin/generate_pdf")
public class PdfController {

    @Autowired
    private PdfService pdfService;

    @GetMapping("/online")
    public void generatePdf(HttpServletResponse response) throws Exception {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"mydocument.pdf\"");

        InputStream pdf = pdfService.createPdf();
        org.apache.commons.io.IOUtils.copy(pdf, response.getOutputStream());
        response.flushBuffer();
    }
}

至于重定向呢,正如我在评论中所说的,你可以在前端使用JS(在调用
/admin/generate\u pdf/online
url之后)进行重定向。您不能同时下载文件和进行刷新/重定向。

检查此解决方案:我可以重定向,但不能同时下载和重定向。下载PDF后,您可以使用Java脚本从网页重定向。我如何下载它?第二个问题呢…请参阅下面的答案。检查此解决方案:我可以重定向,但不下载并在sae时间重定向。下载PDF后,您可以使用Java脚本从网页重定向。我如何下载它?第二个问题呢?请参阅下面的答案。#第二个问题:检查/测试我的编辑,@sanjeetpal…在前端,您可能有一些选项。404也可能是“缺少错误页”(针对另一个错误代码/问题)…然后,您还需要(添加到方法签名)
HttpServletRequest请求
,并使用
request.getContextPath()
(=
/project\u name
)(或从“其他地方”获取它)nono,
request.getContextPath()
是否环境安全/在任何地方都可以工作/来自浏览器(请不要告诉我负载平衡和代理案例)…但仍要重新考虑使用重定向来完成此请求。(您提供了一个“重定向代码”,但内容…这与重定向的目的不一致)…可能是一个“新选项卡”“足够好了……对于所有浏览器,
“内容配置”
(文件名、大小……请参见伊利亚的回复)标题的使用也可能对某些浏览器产生一些影响(例如!?)#第二个问题:检查/测试我的编辑,@sanjeetpal…在前端,您可能有一些选项。404也可能是一个“丢失的错误页”(对于另一个错误代码/问题)…然后,您还需要(添加到方法签名)
HttpServletRequest request
,并使用
request.getContextPath()
(=
/project\u name
)(或从“其他地方”获取)不,
请求。getContextPath()
是环境安全的/在任何地方都可以工作/来自浏览器(请不要把我限制在负载平衡和代理案例中)…但仍然重新考虑通过重定向来完成此请求。(您提供了一个“重定向代码”),但内容…这与重定向的目的不一致)…也许一个“新标签”就足够了…对于所有浏览器,
“内容配置”
(文件名、大小,…请参见伊利亚的回复)标题的使用也可能对某些浏览器产生一些影响(例如!?)!