"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : SpringBootMVC Development Date : 03/12/2024 (Session - 81) _____________________________________________________________________________________________________________________ Today Session ============= 1) Exporting the PDF Document using openpdf library =================================================== PDFGenerator.java ================= package com.ashokit.reports; import java.io.IOException; import java.util.List; import com.ashokit.dao.Enquiry; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.pdf.CMYKColor; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import jakarta.servlet.http.HttpServletResponse; public class PDFGenerator { public void generate(List enquiryList, HttpServletResponse response) throws DocumentException, IOException { // Creating the Object of Document Document document = new Document(PageSize.A4); // Getting instance of PdfWriter PdfWriter.getInstance(document, response.getOutputStream()); // Opening the created document to change it document.open(); /*Image logoImage = Image.getInstance("images/ashokit.jpg"); logoImage.scaleAbsolute(200, 60); logoImage.setAlignment(Element.ALIGN_CENTER); document.add(logoImage);*/ // Creating font Setting font style and size Font headingFontSize = FontFactory.getFont(FontFactory.TIMES_ROMAN,18,Font.BOLD,CMYKColor.RED); // Creating paragraph Paragraph paragraph = new Paragraph("Ashok IT Enquires Information", headingFontSize); // Aligning the paragraph in the document paragraph.setAlignment(Element.ALIGN_CENTER); // Adding the created paragraph in the document document.add(paragraph); //adding two lines of spacing createEmptyLine(paragraph, 2); // Creating a table of the 4 columns PdfPTable table = new PdfPTable(4); // Setting width of the table, its columns and spacing table.setWidthPercentage(100f); table.setWidths(new int[] {20,30,30,20}); table.setSpacingBefore(5); // Creating font Setting font style and size Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN); font.setColor(CMYKColor.WHITE); // Create Table Cells for the table header PdfPCell cell = new PdfPCell(); // Setting the background color and padding of the table cell cell.setBackgroundColor(CMYKColor.RED); cell.setPadding(10); // Adding headings in the created table cell or header // Adding Cell to table cell.setPhrase(new Phrase("Enquiry ID", font)); table.addCell(cell); cell.setPhrase(new Phrase("Name", font)); table.addCell(cell); cell.setPhrase(new Phrase("Email-ID", font)); table.addCell(cell); cell.setPhrase(new Phrase("Contact No", font)); table.addCell(cell); // Iterating the list of Enquires for (Enquiry enquiry : enquiryList) { // Adding Enquiry id table.addCell(String.valueOf(enquiry.getEnquiryId())); // Adding Enquiry name table.addCell(enquiry.getEnquiryName()); // Adding Enquiry email table.addCell(enquiry.getEmailId()); // Adding Enquiry ContactNo table.addCell(enquiry.getContactNo()); } // Adding the created table to the document document.add(table); // Closing the document document.close(); } private static void createEmptyLine(Paragraph paragraph, int number) { for (int i = 0; i < number; i++) { paragraph.add(new Paragraph(" ")); } } } EnquiryController.java ====================== package com.ashokit.controller; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import com.ashokit.dao.Enquiry; import com.ashokit.reports.PDFGenerator; import com.ashokit.services.EnquiryService; import com.lowagie.text.DocumentException; import jakarta.servlet.http.HttpServletResponse; @Controller public class EnquiryController { @Autowired private EnquiryService enquiryService; @Value("${enquires.pageSize}") private int pageSize; // getting the home page when we deployed application into server automatically // will execute this handler method @GetMapping(value = "/") public String showAllEnquires(ModelMap map) { return showEnquiresByPage(1, "enquiryName", "asc", map); } @GetMapping("/page/{pageNo}") public String showEnquiresByPage(@PathVariable(value = "pageNo") int pageNo, @RequestParam("sortField") String sortField, @RequestParam("sortDir") String sortDir, ModelMap modelMap) { Page page = enquiryService.getAllEnquiresSortByPage(pageNo, pageSize, sortField, sortDir); // Getting the list of enquires from page object List enquiresList = page.getContent(); modelMap.addAttribute("title", "Welcome To AshokIT Developing SpringBoot MVC Application......"); // pagination field attributes modelMap.addAttribute("currentPage", pageNo);//Request parameter System.out.println("page.getTotalPages()" + page.getTotalPages()); modelMap.addAttribute("totalPages", page.getTotalPages()); // 4 modelMap.addAttribute("totalItems", page.getTotalElements()); // 11' System.out.println("page.getTotalPages()" + page.getTotalElements()); // sorting fields attributes modelMap.addAttribute("sortField", sortField); //RequestParameter modelMap.addAttribute("sortDir", sortDir);//Request parameter modelMap.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc"); modelMap.addAttribute("enquires", enquiresList); return "enquires"; } @GetMapping("/export-to-pdf") public void generatePdfFile(HttpServletResponse response) throws DocumentException, IOException { response.setContentType("application/pdf"); DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD:HH:MM:SS"); String currentDateTime = dateFormat.format(new Date()); String headerkey = "Content-Disposition"; String headervalue = "attachment; filename=ashokit_enquires_" + currentDateTime +".pdf"; response.setHeader(headerkey, headervalue); List listOfEnquires = enquiryService.getAllEnquires(); PDFGenerator generator = new PDFGenerator(); generator.generate(listOfEnquires, response); } } pom.xml ======= com.github.librepdf openpdf 1.3.26 enquiryDetails.jsp ================== <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> enquires.jsp

${title}


    
S.No Enquiry Name EmailId ContactNo Course Operations
${count.index + 1} ${enquiry.enquiryName} ${enquiry.emailId} ${enquiry.contactNo} ${enquiry.course} |Edit| |Delete|
Exporting the Data as Excel Document ==================================== https://www.youtube.com/watch?v=qe_NrRRsuVg 2) File Uploading & Downloading =============================== * File Uploading is nothing but sending copy of file from client machine to server machine is called "Uploading". * File Downloading is Process of getting file from server machine into client machine is called "Downloading". * Most of the applications in realworld this is common task for File Uploading and Downloading. * In the Standalone application we can store the files into Database Software directly in the form of Lobs(CLOB,BLOB) * In the Web application (or) Distributed application we can store uploaded files into servermachine at particular location (or) we can store the uploaded files into Cloud(AWS(S3)). Java <----------> AWS Service <------------> aws-sdk Python <----------> AWS Service <------------> boto,boto3 libraries * In the current Application we are just storing the files into particular location of Server machine and we can enhance the functionality to store location of file in database column instead of storing file content into database. * During the File Uploading Process if our request contains simple text + uploaded file means that request to be considered as "Multi-part" request. * To Store the Uploaded file into Model class we need to take one multipart property. Steps ===== * When we are doing the file uploading process in webapplication development either by Servlets & JSP (or) Spring MVC (or) Spring Boot MVC we need to follow the below steps 1) In the view page either html page (or) JSP Page we need to have tag which can be used to browse the file from Hard drive. 2) Make sure Html Form method should be used as "POST". 3) Enabling the Multipart Request at form tag level using following attribute enctype="multipart/form-data". Multipart Request means "plain text + Uploaded File Content" * Normally to hold the form data at server side we need to take one model class, Inorder to hold the uploaded file content as programmer we need to take one Multipart Property. FileController.java =================== package com.ashokit.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.ashokit.dto.UserDto; import jakarta.servlet.http.HttpServletResponse; @Controller public class FileController { public FileController() { System.out.println("Request Controller class default constructor!!!"); } //getting home page @RequestMapping(value ="/",method=RequestMethod.GET) public String getHomePage(Model model) { model.addAttribute("user", new UserDto()); //creating the object for command class //creating the content for Dropdown while rendering the registrationForm.jsp List qualificationList = new ArrayList(); qualificationList.add("MCA"); qualificationList.add("CSE"); model.addAttribute("qualificationsList", qualificationList); return "registrationForm"; } @RequestMapping(value="saveProfile",method=RequestMethod.POST) public ModelAndView saveProfileData(@ModelAttribute("user") UserDto user) { ModelAndView mav = new ModelAndView(); MultipartFile uploadFile = user.getProfilePic(); String uploadStatus ="Uploaded Success"; String viewPageName="registrationForm"; File totalFilesList[] = null; // E:\springBootUploadFiles\ File directoryLocation = new File("E:"+File.separator+"springBootUploadFiles"+File.separator); //checking the file location directory is existed or not if(!directoryLocation.exists()) { directoryLocation.mkdir(); } if(!uploadFile.isEmpty()) { String uploadFileName = uploadFile.getOriginalFilename();//uploaded file name System.out.println("Absoulte Path::::" + directoryLocation.getAbsolutePath()); System.out.println("Upload File Name::::::" + uploadFileName); String uploadedFilePath = directoryLocation.getAbsolutePath()+File.separator+uploadFileName; try(FileOutputStream fos = new FileOutputStream(uploadedFilePath)){ byte[] bt = uploadFile.getBytes(); fos.write(bt);//writing the uploaded file data into destination location totalFilesList = directoryLocation.listFiles();//getting the list of files available in directory viewPageName = "fileUploadStatus"; } catch (Exception e) { e.printStackTrace(); } }else { uploadStatus ="Please Browse File To Complete the Form Submission!!!"; } mav.addObject("totalFilesList", totalFilesList); mav.addObject("uploadStatus",uploadStatus); mav.setViewName(viewPageName); return mav; } @RequestMapping(value="downloadFile", method=RequestMethod.GET) public void fileDownload(@RequestParam("filename") String fileName,HttpServletResponse response){ File directoryLocation = new File("E:"+File.separator+"springBootUploadFiles"); try(FileInputStream fis = new FileInputStream(directoryLocation.getAbsolutePath()+File.separator+fileName)) { response.setHeader("Content-Disposition","attachment;filename="+fileName);//getting the popup message to download the file IOUtils.copy(fis, response.getOutputStream()); response.flushBuffer(); } catch (Exception e) { throw new RuntimeException("IO Error Writing file to Output Stream"); } } } UserDto.java ============ package com.ashokit.dto; import org.springframework.web.multipart.MultipartFile; public class UserDto { private String firstName; private String lastName; private String qualification; private MultipartFile profilePic; public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } public void setQualification(String qualification) { this.qualification = qualification; } public String getQualification() { return qualification; } public void setProfilePic(MultipartFile profilePic) { this.profilePic = profilePic; } public MultipartFile getProfilePic() { return profilePic; } } application.properties ====================== # Datasource Configuration spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springboot spring.datasource.username=root spring.datasource.password=root # MVC Configuration server.port=1234 spring.mvc.view.prefix=/views/ spring.mvc.view.suffix=.jsp server.servlet.context-path=/32_SpringBootMVC_File_Uploading_Downloading_App #Hibernate Configuration spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true #MultiPart Configuration spring.servlet.multipart.max-file-size=2MB spring.servlet.multipart.max-request-size=2MB registrationForm.jsp ==================== <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="spring" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> registrationForm.jsp

Welcome To AshokIT Spring Boot MVC File Uploading & Downloading Application!!!!

${uploadStatus}
FirstName
LastName
Qualification Select ${temp}
Profile Pic
  InsertRecord
fileUploadStatus.jsp ==================== <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="spring" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> fileUploadStatus.jsp

Welcome To Ashok IT For Spring Boot MVC File Downloading Application!!!!!

${uploadStatus}
S.No File Name File Location Download
${loopCounter.count} ${file.getName()} ${file.getAbsolutePath()} Download File
OUTPUT ====== S.No File Name File Location Download ==== ========= ============== ========= 1 1692541096322.jpg E:\springBootUploadFiles\1692541096322.jpg Download File 2 Java8Features.txt E:\springBootUploadFiles\Java8Features.txt Download File 3 linux commands cheatsheet.pdf E:\springBootUploadFiles\linux commands cheatsheet.pdf Download File 4 ProfilePic1.png E:\springBootUploadFiles\ProfilePic1.png Download File 5 ProfilePic2.jpg E:\springBootUploadFiles\ProfilePic2.jpg Download File 6 ProfilePic3.jfif E:\springBootUploadFiles\ProfilePic3.jfif Download File 7 raju.docx E:\springBootUploadFiles\raju.docx Download File Spring Boot MVC ============== 1) Thymeleaf 2) Validation 3) Exception Handling <----> Rest API Development ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++