Java 如何将一个集合变量值传递给另一个pdf生成类

Java 如何将一个集合变量值传递给另一个pdf生成类,java,servlets,collections,Java,Servlets,Collections,我有一个XML解析器类,在这个类中我阅读XML类并进行解析,根据我从数据库中获得的一些值,使用这两个值我计算工资,我现在已经完成了,我想将这个变量传递到另一个pdf类中,当我想为特定ID相关人员生成pdf时 public class XMLParser extends HttpServlet { public static HashMap<String, String> hMap1 = new HashMap<String, String>(); publ

我有一个XML解析器类,在这个类中我阅读XML类并进行解析,根据我从数据库中获得的一些值,使用这两个值我计算工资,我现在已经完成了,我想将这个变量传递到另一个pdf类中,当我想为特定ID相关人员生成pdf时

public class XMLParser extends HttpServlet {
    public static HashMap<String, String> hMap1 = new HashMap<String, String>();
    public static HashMap<String, String> hMap2 = new HashMap<String, String>();
    public static HashMap<String, Double> hMap3 = new HashMap<String, Double>();


    public static String series1, series2, ID;
    int s1, s2;
    double s3;
    static double z;

    public void getAllUserNames(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            File file = new File(fileName);
            if (file.exists()) {
                Document doc = db.parse(file);
                Element docEle = doc.getDocumentElement();
                // Print root element of the document
                System.out.println("Root element of the document: " + docEle.getNodeName());

                NodeList studentList = docEle.getElementsByTagName("emplopyee");
                // NodeList st1 = docEle.getElementsByTagName("emplopyee");

                // Print total student elements in document
                System.out.println("Total emplopyee: " + studentList.getLength());

                if (studentList != null && studentList.getLength() > 0) {
                    for (int i = 0; i < studentList.getLength(); i++) {

                        Node node = studentList.item(i);

                        if (node.getNodeType() == Node.ELEMENT_NODE) {

                            System.out.println("=====================");

                            Element e = (Element)node;


                            NodeList nodeList1 = e.getElementsByTagName("ID");
                            ID = nodeList1.item(0).getChildNodes().item(0).getNodeValue();


                            System.out.println("ID: " + nodeList1.item(0).getChildNodes().item(0).getNodeValue());
                            NodeList nodeList2 = e.getElementsByTagName("Name");
                            series1 = nodeList2.item(0).getChildNodes().item(0).getNodeValue();
                            System.out.println("Name: " + nodeList2.item(0).getChildNodes().item(0).getNodeValue());

                            NodeList nodeList3 = e.getElementsByTagName("Days");


                            String series2 = nodeList3.item(0).getChildNodes().item(0).getNodeValue();
                            s3 = Double.parseDouble(series2);
                            System.out.println(s3);
                            Class.forName("com.mysql.jdbc.Driver");
                            Connection con =
                                DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", null);
                            Statement st = con.createStatement();
                            ResultSet rs = st.executeQuery("Select * from emp1 where eid = '" + ID + "' ");

                            while (rs.next()) {
                                int n1 = Integer.parseInt(rs.getString(1));
                                String n2 = rs.getString(2);
                                int n3 = Integer.parseInt(rs.getString(3));
                                int n4 = Integer.parseInt(rs.getString(4));
                                System.out.println(n1);
                                System.out.println(n2);
                                System.out.println(n3);
                                System.out.println(n4);
                                z = s3 * n3;

                                System.out.println(z);
                            }
                        }
                    }

                    hMap3.put(ID, z);
                    System.out.println(hMap3); //----> this thing i want to print in pdf
                }


                else {
                    System.exit(1);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                       java.io.IOException {
        XMLParser parser = new XMLParser();
        parser.getAllUserNames("D:\\employee.xml");
        ServletContext context = this.getServletContext();
        RequestDispatcher dispatcher = context.getRequestDispatcher("/FirstPdf");
        dispatcher.forward(request, response);
    }
}
另一个pdf生成类

public class FirstPdf extends HttpServlet {
    private static String FILE = "c:/temp/SecondPdf.pdf";
    private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
    private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                       java.io.IOException {
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
            document.open();
            addMetaData(document);
            addTitlePage(document);
            addContent(document);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void addMetaData(Document document) {
        document.addTitle("Salary PDF");
        document.addSubject("Using iText");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Saurabh");
        document.addCreator("Saurabh Gupta");
    }

    private static void addTitlePage(Document document) throws DocumentException {
        Paragraph preface = new Paragraph();


        preface.add(new Paragraph("Title of the document", catFont));

        addEmptyLine(preface, 1);

        preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
                                  smallBold));
        addEmptyLine(preface, 3);
        preface.add(new Paragraph("This document describes something which is very important ", smallBold));

        addEmptyLine(preface, 8);

        preface.add(new Paragraph("This document is simple demonstration of generating salry slip).", redFont));

        document.add(preface);

        document.newPage();
    }

    private static void addContent(Document document) throws DocumentException {
        Anchor anchor = new Anchor("First page", catFont);
        anchor.setName("First Page");

        Chapter catPart = new Chapter(new Paragraph(anchor), 1);

        Paragraph subPara = new Paragraph("Subcategory 1", subFont);
        Section subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Here we go"));

        subPara = new Paragraph("Subcategory 2", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Paragraph 1"));
        subCatPart.add(new Paragraph("Paragraph 2"));
        subCatPart.add(new Paragraph("Paragraph 3"));


        createList(subCatPart);
        Paragraph paragraph = new Paragraph();
        addEmptyLine(paragraph, 5);
        subCatPart.add(paragraph);


        createTable(subCatPart);

        now add;
        all;
        this;
        to the;
        document;
        document.add(catPart);


        anchor = new Anchor("Second Chapter", catFont);
        anchor.setName("Second Chapter");

        Second parameter;
        is the;
        number of;
        the chapter;
        catPart = new Chapter(new Paragraph(anchor), 1);

        subPara = new Paragraph("Subcategory", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("This is a very important message"));


        document.add(catPart);

    }

    private static void createTable(Section subCatPart) throws BadElementException {
        PdfPTable table = new PdfPTable(4);


        PdfPCell c1 = new PdfPCell(new Phrase("Employee ID"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Name"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("No of days that person came"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);


        c1 = new PdfPCell(new Phrase("Salary for the month"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);


        table.setHeaderRows(1);

        table.addCell("1.1");
        table.addCell("1.2");
        table.addCell("1.3");
        table.addCell("1.4");
        table.addCell("2.1");
        table.addCell("2.2");
        table.addCell("2.3");
        table.addCell("2.4");
        subCatPart.add(table);
    }

    private static void createList(Section subCatPart) {
        List list = new List(true, false, 10);
        list.add(new ListItem("First point"));
        list.add(new ListItem("Second point"));
        list.add(new ListItem("Third point"));
        subCatPart.add(list);
    }

    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(""));
        }
    }
}
enter code here
使用并将请求中的数据设置为属性

用于从请求中获取数据

示例代码:

public class XMLParser extends HttpServlet {
   ...

    ServletContext context = this.getServletContext();
    RequestDispatcher dispatcher = context.getRequestDispatcher("/FirstPdf");

    request.setAttribute(key,value);
    dispatcher.forward(request, response);

}


public class FirstPdf extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,java.io.IOException {
        Object value = request.getAttribute(key);
        ...
    }  
}

为什么FirstPdf从HttpServlet扩展而来?我不会在servlet中放入任何域逻辑。servlet应该只是其他类提供的服务的客户端。将XML内容提取到类中,将PDF内容提取到类中。然后让servlet使用这些类。

谢谢您,先生,我已经设置了这样的请求;在XMLParser Servlet中以及现在如何在FirstPdf Servlet中打印此值我必须使用的是use request.getAttributeIDsir我可以像此请求一样打印ID;total2是一个保持z值的变量,z是双精度的,所以我将其转换为字符串,但与我尝试打印total2的方式相同,它将以pdf格式显示为空,但ID为打印是否确保您已尝试设置setAttribute以设置第一个servlet中的值,并尝试getAttribute以获取第二个servlet中的值?如果它不起作用,则使用会话属性HttpSessiongetAttribute和HttpSessionsetAttribute。比servlet请求高一级。您可以从servlet requestsir获得http会话,我稍后会做这些事情,因为我想先用正常流程执行这些事情,因为任务很大,我必须创建工资生成器…所以我只需执行第一个简单的步骤,稍后我将使用struts和hibernate完全转换它,首先我想用简单的方法