0

我正在尝试显示我的 iReport 生成的 pdf 文件,但我只收到以下错误页面:

“HTTP 状态 404 -

类型状态报告

信息

描述 请求的资源 () 不可用。

Apache Tomcat/7.0.27"

这是代码:

package containerweb.reports;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap; 
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import java.math.BigDecimal;


public class AutorizacaoTransportadores extends HttpServlet{
public static Connection con;
public static String banco = "DESENV"; // Nome do banco de dados
public static String usuario = "SCV20"; // Usuario do banco
public static String senha = "SCV20"; // Senha

protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    conexao(); 


    String pathJasper = getServletContext().getRealPath(
            "/WEB-INF/relatorios/") + "/";
    String path = getServletContext().getRealPath("/");

    Map parametros = new HashMap();

    parametros.put("codEmpresa", new BigDecimal(26));
    try {
        // Aqui ele cria o relatório
        JasperPrint impressao = JasperFillManager.fillReport(pathJasper
                + "AutorizacaoTransportadores.jasper", parametros ,con);
        // Grava o relatório em disco em pdf
        JasperExportManager.exportReportToPdfFile(impressao, path
                + "/AutorizacaoTransportadores.pdf");
        // Redireciona para o pdf gerado
        res.sendRedirect("AutorizacaoTransportadores.pdf");
    } catch (JRException | IOException e) {
        res.getWriter().println("Erro ao gerar o relatório: " + e);
    }
}

// Cria a conexão
public void conexao() {
    try {
        if (con == null || con.isClosed()) {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(                        
                    "jdbc:oracle:thin:@10.0.0.200:1521:DESENV" /*+ banco*/, usuario, senha);
            System.out.println("Conexão bem sucedida");
        }
    } catch (SQLException | ClassNotFoundException e) {
        System.out.println("não foi possível conectar ao banco ->");
        e.printStackTrace();
    }
}

@Override
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
        throws ServletException, IOException {
    doPost(arg0, arg1);
}

}

这是 web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" si:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>containerweb.listener.MyHttpSessionListener</listener-class>
</listener>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>


<!-- <welcome-file-list>
    <welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>  -->
<error-page>
    <location>/error.html</location>
</error-page>

<servlet>
    <servlet-name>ReportServlet</servlet-name>
    <servlet-class>containerweb.reports.AutorizacaoTransportadores</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ReportServlet</servlet-name>
    <url-pattern>/AutorizacaoTransportadores</url-pattern>
</servlet-mapping>

我在其他项目中有其他使用基本相同方法的报告,它们都在工作。我不知道只有这一个可能有什么问题。

提前致谢。

4

1 回答 1

0

在 pdf 中显示错误此文档可能无法正确显示**

enter code here 



import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;




public class test extends HttpServlet {


protected void processRequest(HttpServletRequest request,
  HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet test</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet test at " + request.getContextPath() + "  
  </h1>");
        out.println("</body>");
        out.println("</html>");

response.setHeader("Content-Disposition", "inline; filename=\"print.pdf\"");
response.setContentType("application/pdf");
String host = "jdbc:mysql://localhost:3306/youare";
String uname = "root";
String upass = "";
String user = request.getParameter("rollnum");
String userdob = request.getParameter("date_of_birth");
   try {   
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(host, uname, upass);



// an example date with format MM-dd-yyyy
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY_MM_DD_DASH");
Date d =    (Date) sdf.parse(userdob);
// exactly after here is useful for you
sdf.applyPattern("YYYY_MM_DD_DASH");
newDateString = sdf.format(d);

HashMap map = new HashMap();
map.put("Regno",user); 
map.put("dob",newDateString);



ServletContext context = request.getServletContext();
String report = context.getRealPath("/report.jrxml");

 InputStream input=new FileInputStream(new File(report));

JasperReport jr= JasperCompileManager.compileReport(input);
JasperPrint jasperPrint = JasperFillManager.fillReport(jr,map,con);
//JasperExportManager.exportReportToPdfFile(jasperPrint,"print.pdf");

          JasperExportManager.exportReportToPdfStream(jasperPrint,
       response.getOutputStream ());
 response.getOutputStream().flush();
 response.getOutputStream().close();

 JasperViewer.viewReport(jasperPrint);

    con.close();
    } 
 catch (Exception ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
    }
    }


   }
于 2015-10-15T06:18:41.913 回答