I am making a web app that allows you to buy a ticket online. I used a java class called CreatePDF.java to make the PDF(which is what the ticket will be) it works offline but when i try and use it through a servlet the pdf is broken. I have tried to look everywhere that solves this problem using itext7 but no one has
OrderServlet.java
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class OrderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
// HsqlShopDB db = new HsqlShopDB();
String name = request.getParameter("fname");
String mobile = request.getParameter("number");
String email = request.getParameter("email");
String cemail = request.getParameter("cemail");
HsqlShopDB db = new HsqlShopDB();
Event e = db.getEvent("1");
Ticket t = db.getTicket("1");
createPDF c = new createPDF();
try{
c.CreatePDF("10293838458493",89,t,e,name);
}catch (Exception ex) {
System.out.println(ex);
}
if (name!=null){
// db.order(basket, name, email,mobile);
// email e = new email();
// e.orderEmail(basket,name,email,mobile);
// basket.clearBasket();
}else{
System.out.println("name is not here");
}
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Thank you" + name + "for ordering a "+ e +"ticket</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
CreatePDF.java
import java.io.*;
import com.itextpdf.io.image.*;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.font.constants.FontWeights;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.element.Text;
public class createPDF{
public void CreatePDF(String orderID, Integer random, Ticket t, Event e,String customer) throws Exception {
// Creating a PdfWriter
String code = Integer.toString(random);
String dest = "../webapps/EMT/WEB-INF/classes/EMTShop/PDFs/" + code + ".pdf";
PdfWriter writer = new PdfWriter(dest);
String barcodePath= code + ".png";
GenerateQRCode g= new GenerateQRCode();
g.generateQRcode(code);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating a PdfCanvas object
// Creating a new page
PdfPage pdfPage = pdf.addNewPage();
PdfCanvas canvas = new PdfCanvas(pdfPage);
// Setting color to the rectangle
Color color = ColorConstants.BLACK;
canvas.setColor(color, true);
// creating a rectangle
canvas.rectangle(10, 10,600,200 );
// Creating Paragraphs
Text para1 = new Text("EMT Entertainment Presents: "+ e.title +"!");
Text para2 = new Text( t.type + " £"+ t.price + "\n Ordered By: " + customer +" \n Enter Before " + t.entry);
Text para3 = new Text(e.location +", " + e.postcode +"\n "+ e.date + " \n Order ID: "+ orderID);
Text para4 = new Text("Permits 1 x Person(s)");
// Setting font of the text
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
PdfFont font2 = PdfFontFactory.createFont(StandardFonts.HELVETICA);
para1.setFont(font);
para1.setFontSize(17);
para2.setFont(font);
para2.setFontSize(15);
para3.setFont(font2);
para4.setFont(font2);
Paragraph paragraph1 = new Paragraph(para1);
Paragraph paragraph2 = new Paragraph(para2);
Paragraph paragraph3 = new Paragraph(para3);
Paragraph paragraph4 = new Paragraph(para4);
// Setting the position of the paragraph to the page
paragraph1.setMarginLeft(10);
paragraph1.setMarginTop(160);
paragraph2.setMarginLeft(10);
paragraph2.setMarginTop(30);
paragraph3.setMarginLeft(20);
paragraph3.setMarginTop(50);
paragraph4.setMarginLeft(20);
paragraph4.setMarginTop(60);
// Creating an ImageData object
String imFile = "EMTShop/images/EMTLogo.jpeg";
String imFile2 = "EMTShop/images/"+ e.title + ".jpg";
String imFile3 = "EMTShop/barcodes/" + barcodePath;
ImageData data = ImageDataFactory.create(imFile);
ImageData data2 = ImageDataFactory.create(imFile2);
ImageData data3 = ImageDataFactory.create(imFile3);
// Creating an Image object
Image image = new Image(data);
Image image2 = new Image(data2);
Image image3 = new Image(data3);
// Setting the position of the image to the center of the page
image.setFixedPosition(250, 700);
image.setHeight(100);
image.setWidth(100);
image2.setFixedPosition(425, 500);
image2.setHeight(150);
image2.setWidth(100);
// Creating Barcode
image3.setFixedPosition(400, 300);
image3.setHeight(150);
image3.setWidth(150);
// Adding paragraphs to document
document.add(paragraph1);
document.add(paragraph2);
document.add(paragraph3);
document.add(paragraph4);
// Adding image to the document
document.add(image);
document.add(image2);
document.add(image3);
// Closing the document
document.close();
System.out.println("Image added");
}
public static void main(String args[]) throws Exception{
createPDF c = new createPDF();
HsqlShopDB db = new HsqlShopDB();
Event e = db.getEvent("1");
Ticket t = db.getTicketsEvent(e.eventid);
c.CreatePDF("10293838458493",1999,t,e,"tope oshin");
}
}
Details.jsp uses a form to send information to the servlet
<div class= "blog">
<div class= "form">
<h1>Please confirm your details</h1>
<form method="POST" action="OrderServlet">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname">
<label for="number">Phone Number:</label>
<input type="text" id="number" name="number">
<label for="email">E-Mail Address:</label>
<input type="text" id="email" name="email">
<label for="cemail">Confirm E-Mail Address:</label>
<input type="text" id="cemail" name="cemail">
<input type="submit" value="proceed to checkout" name="VIP1">
</form>
</div>
</div>
Related
I am developing a web application using Java. From my index page I need to upload a file with some other fields such as some texts and numbers using input tags.
this is my jsp file.
<select name="category">
<option value="">-Select-</option>
<option value="Mobile Phones">Mobile Phones</option>
<option value="Automobile">Automobile</option>
<option value="Computers">Computers</option>
</select><br/><br/>
<label>Title: </label><input type="text" name="Title"/><br/><br/>
<label>Photo: </label><input type="file" name="photo"/><br/><br/>
<label>Description: </label><input type="text" name="description"/><br/><br/>
<label>Price: </label><input type="text" name="price"/><br/><br/>
<input type="submit" value="Post">
I found some articles which use Apache commons, but in all of that, I can get only the image. All the other values get set to null. The article I followed is this.
I need to know how to get other values as well. (In this case category, title, photo etc.)
How can I do that?
Thank you!
EDIT:
This is my servlet.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.im.dao.PostAdDao;
import com.im.dao.PostAdDaoImpl;
import com.im.entities.Advertiesment;
#WebServlet("/postAd")
#MultipartConfig
public class PostAdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "C:/uploadss";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Advertiesment ad = new Advertiesment();
PostAdDao pad = new PostAdDaoImpl();
PrintWriter out = response.getWriter();
String name = null;
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(item.isFormField()){
String cat = request.getParameter("category");
System.out.println("INFO: Category : "+cat);
if( cat != null ){
ad.setCategory(cat);
}
String title = request.getParameter("adTitle");
if( title != null ){
ad.setTitle(title);
System.out.println("INFO: Title : "+title);
}
String des = request.getParameter("description");
if(des != null){
ad.setDescription(des);
System.out.println("INFO: Description : "+des);
}
try{
Double price = Double.parseDouble(request.getParameter("price"));
if(price != null){
ad.setPrice(price);
System.out.println("INFO: Price : "+price);
}
}catch(Exception e){
System.out.println("ERROR: Occured while setting price in servlet");
}
}else{
name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
//File uploaded successfully
request.setAttribute("message", "Advertiesment Posted Successfully");
System.out.println("INFO: Advertiesment Posted Successfully");
System.out.println("INFO: File name : "+name);
ad.setPhoto(name);
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
System.out.println("\nERROR: Occured while posting the advertiesment! "+ex );
}
}else{
//request.setAttribute("message","Sorry this Servlet only handles file upload request");
}
//request.getRequestDispatcher("/result.jsp").forward(request, response);
String msg = pad.postAd(ad);
}
}
I found some articles which use Apache commons, but in all of that, I
can get only the image
No . you can get other items also from the request .
DiskFileUpload upload = new DiskFileUpload();
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
//get form fields here
}
else {
//process file upload here
}}
Read the documentation here to understand more on this and also a nice thread here values of input text fields in a html multipart form
Update:
String cat = item.getFieldName("category") instead of request.getParameter("category");
Because you are parsing the request object . so you need to get it from FileItem object . similarly for other fields too.
From the Servlet I am generating JPEG image and writing in the outputstream of that servlet.By jsp i am calling this Servlet URL and displaying the image as similar to user profile with photo.
Here the problem is,When first time login it will generate the image dynamically and display but next time if I login with out closing the browser first it will display the privies picture and then it will display the current picture.
JSP:
<div class="sortable">
<div class="box span5" style="margin-left: 50px;">
<div class="box-header well">
<h2><i class="icon-th"></i>Employee Attendance</h2>
<div class="box-icon">
<i class="icon-chevron-up"></i>
</div>
</div>
<div class="box-content" style="height:230px;" >
<img border="0" src="admissionenquirylist.do?method=image" alt="Pulpit rock" width="370" height="240"/>
</div>
</div>
</div>
Servlet:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.treamis.admission.process;
import com.google.gson.Gson;
import com.treamis.entity.Academicyearmaster;
import com.treamis.entity.AdmissionenquiryStudentdetails;
import com.treamis.entity.EmployeeEntity;
import com.treamis.hr.employee.PaginationClass;
import com.treamis.hr.employee.SetPaginationRecords;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.actions.LookupDispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.ServletOutputStream;
/**
*
* #author ranjeeth.g
*/
public class AdmissionEnquiry extends LookupDispatchAction {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
/**
* Provides the mapping from resource key to method name.
*
* #return Resource key / method name map.
*/
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("button.admissionEnqiryList", "admissionEnqiryList");
map.put("button.image", "image");
map.put("button.delete", "delete");
return map;
}
/**
* Action called on Add button click
*/
public void admissionEnqiryList(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
// TODO: implement add method
try {
String stdutendserch = request.getParameter("admissionenquirysearch");
System.out.println("stdutendserch = " + stdutendserch);
Admissionservices as = new Admissionservices();
List<Enquirylistbean> stdserc = as.getStudentEnquirySerch(stdutendserch);
if (stdserc != null) {
response.setContentType("application/json");
String json = new Gson().toJson(stdserc);
System.out.println("json = " + json);
response.getWriter().print(json);
} else {
response.setContentType("application/json");
String json = new Gson().toJson(null);
response.getWriter().print(json);
}
} catch (Exception e) {
e.printStackTrace();
}
// return mapping.findForward(SUCCESS);
// return null;
}
/**
* Action called on Edit button click
*/
public void image(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
try {
System.out.println("Inside the image responce action");
response.setContentType("image/jpeg");
Academicyearmaster academicyearmaster = (Academicyearmaster) request.getSession().getAttribute("academicyear");
// String ss = getServlet().getServletContext().getRealPath("\\");
// String filePath = ss + "img\\paichart.png";
ServletOutputStream out = response.getOutputStream();
// System.out.println("out = " + out);
// String filePath2 = ss + "img\\paichart1.png";
// ExecutorService executor = Executors.newFixedThreadPool(2);
com.treamis.hr.employee.Sendded sendded = new com.treamis.hr.employee.Sendded(out, academicyearmaster);
sendded.image();
// executor.execute(sendded);
} catch (Exception e) {
e.printStackTrace();
}
// TODO: implement edit method
// return mapping.findForward(SUCCESS);
}
/**
* Action called on Delete button click
*/
public ActionForward delete(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws java.lang.Exception {
// TODO:implement delete method
return mapping.findForward(SUCCESS);
}
/* And your JSP would have the following format for submit buttons:
<html:form action="/test">
<html:submit property="method">
<bean:message key="button.add"/>
</html:submit>
<html:submit property="method">
<bean:message key="button.edit"/>
</html:submit>
<html:submit property="method">
<bean:message key="button.delete"/>
</html:submit>
</html:form>
*/
}
Java code to generate image:
try{
ChartUtilities.writeChartAsJPEG(out, chart, 600, 400, info);
// System.out.println("file2 = " + file1);
} catch (Exception e) {
e.printStackTrace();
return "success";
} finally {
out.close();
}
The answer lies in the Life cycle of Servlet. Even though multiple request comes to a servlet only one instance of the Servlet class will be created.
Check if you have any resources that is global and fix it.
Or post full servlet class for better response.
Hope it helps!
I think if you use differents files names to each file save in disk you will not have this problem again.
Using the Rally Java Rest API, after I get the AttachmentContent object, how do I actually get the bytes which hold the content?
You may find the following example to be useful for what you are wanting to do. It's for a User Story rather than a Defect but the process would be identical for a Defect.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.CreateRequest;
import com.rallydev.rest.request.DeleteRequest;
import com.rallydev.rest.request.GetRequest;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.request.UpdateRequest;
import com.rallydev.rest.response.CreateResponse;
import com.rallydev.rest.response.DeleteResponse;
import com.rallydev.rest.response.GetResponse;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.response.UpdateResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import com.rallydev.rest.util.Ref;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.codec.binary.Base64;
public class RestExample_DownloadAttachment {
public static void main(String[] args) throws URISyntaxException, IOException {
// Create and configure a new instance of RallyRestApi
// Connection parameters
String rallyURL = "https://rally1.rallydev.com";
String wsapiVersion = "1.43";
String applicationName = "RestExample_DownloadAttachment";
// Credentials
String userName = "user#company.com";
String userPassword = "topsecret";
RallyRestApi restApi = new RallyRestApi(
new URI(rallyURL),
userName,
userPassword
);
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(applicationName);
// Workspace and Project Settings
String myWorkspace = "My Workspace";
String myProject = "My Project";
// FormattedID of Existing Test Case to Query
String existStoryFormattedID = "US43";
// Get reference to Workspace of interest
QueryRequest workspaceRequest = new QueryRequest("Workspace");
workspaceRequest.setFetch(new Fetch("Name", "Owner", "Projects"));
workspaceRequest.setQueryFilter(new QueryFilter("Name", "=", myWorkspace));
QueryResponse workspaceQueryResponse = restApi.query(workspaceRequest);
String workspaceRef = workspaceQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();
// Get reference to Project of interest
QueryRequest projectRequest = new QueryRequest("Project");
projectRequest.setFetch(new Fetch("Name", "Owner", "Projects"));
projectRequest.setQueryFilter(new QueryFilter("Name", "=", myProject));
QueryResponse projectQueryResponse = restApi.query(projectRequest);
String projectRef = projectQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();
// Query for existing User Story
System.out.println("Querying for User Story: " + existStoryFormattedID);
QueryRequest existUserStoryRequest = new QueryRequest("HierarchicalRequirement");
existUserStoryRequest.setFetch(new Fetch("FormattedID","Name","Attachments"));
existUserStoryRequest.setQueryFilter(new QueryFilter("FormattedID", "=", existStoryFormattedID));
QueryResponse userStoryQueryResponse = restApi.query(existUserStoryRequest);
JsonObject existUserStoryJsonObject = userStoryQueryResponse.getResults().get(0).getAsJsonObject();
String existUserStoryRef = userStoryQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();
JsonArray attachmentsJsonArray = existUserStoryJsonObject.getAsJsonArray("Attachments");
// Take first attachment
JsonObject attachmentObject = attachmentsJsonArray.get(0).getAsJsonObject();
String attachmentRef = attachmentObject.get("_ref").toString();
// Read attachment from Ref
System.out.println("Reading First Attachment: " + attachmentRef);
GetRequest attachmentRequest = new GetRequest(attachmentRef);
attachmentRequest.setFetch(new Fetch("Name","Content"));
GetResponse attachmentResponse = restApi.get(attachmentRequest);
// AttachmentContent object
JsonObject attachmentContentObject = attachmentResponse.getObject().get("Content").getAsJsonObject();
String attachmentContentRef = attachmentContentObject.get("_ref").toString();
// Read Content from Ref
System.out.println("Reading Attachment Content: " + attachmentRef);
GetRequest contentRequest = new GetRequest(attachmentContentRef);
contentRequest.setFetch(new Fetch("Content"));
GetResponse contentResponse = restApi.get(contentRequest);
// Read Content String of AttachmentContent
String attachmentContentBase64String = contentResponse.getObject().get("Content").getAsString();
// Grab attachment name
String attachmentName = attachmentResponse.getObject().get("Name").getAsString();
// Decode base64 string into bytes
byte[] imageBytes = Base64.decodeBase64(attachmentContentBase64String);
// Image output
String imageFilePath = "/Users/username/Desktop/";
String fullImageFile = imageFilePath + attachmentName;
// Write output file
System.out.println("Writing attachment to file: " + attachmentName);
try {
OutputStream imageOutputStream = new FileOutputStream(fullImageFile);
imageOutputStream.write(imageBytes);
imageOutputStream.flush();
imageOutputStream.close();
} catch (Exception e) {
System.out.println("Exception occurred while write image file ");
e.printStackTrace();
}
finally {
//Release all resources
restApi.close();
}
}
}
I have a main form for file uploading. A servlet is doing the upload job. All the files are with the same name structure, so I'm splitting it and getting the parameters. Then I'm placing them into a JSONArray and then I'm passing these parameters to the index page, named test.jsp in my case.
The problem Is, That I have no idea on how to create a table and fill it with the details held in the JSON.
Here my index(test.jsp) page is:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<title>File Upload Demo</title>
</head>
<body>
<center>
<form method="post" action="uploadFile" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="uploadFile" multiple/>
<br/><br/>
<input type="submit" value="Upload" />
</form>
${message}
<br />
${jsonString}
</center>
</body>
</html>
I'm using ${jsonString} to check, if the JSON is passed correctly.
It looks like:
[
{
"MDName": "Angel Bankov",
"MDCode": "2288",
"month": "April",
"year": "2013",
"target/achieved": "Target"
},
{
"MDName": "Angel Bankovsky",
"MDCode": "2289",
"month": "April",
"year": "2015",
"target/achieved": "Achieved"
}
]
Here my servlet is:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* A Java servlet that handles file upload from client.
*
* #author www.codejava.net
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// location to store file uploaded
private static final String UPLOAD_DIRECTORY = "upload";
// upload settings
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
/**
* Upon receiving file upload submission, parses the request to read
* upload data and saves the file on disk.
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
//JSON Declaration
JSONArray splitDetailsArray = new JSONArray();
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
// sets memory threshold - beyond which files are stored in disk
factory.setSizeThreshold(MEMORY_THRESHOLD);
// sets temporary location to store files
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// sets maximum size of upload file
upload.setFileSizeMax(MAX_FILE_SIZE);
// sets maximum size of request (include file + form data)
upload.setSizeMax(MAX_REQUEST_SIZE);
// constructs the directory path to store upload file
// this path is relative to application's directory
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// parses the request's content to extract file data
#SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// iterates over form's fields
for (FileItem item : formItems) {
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
request.setAttribute("message",
"Upload has been done successfully!");
}
}
File folder = new File("D:/Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HDSHubTargetAchieved/upload");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String[] parts = listOfFiles[i].getName().split("[_.']");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
String part5 = parts[4];
// JSON
JSONObject splitDetails = new JSONObject();
splitDetails.put("MDCode", part1);
splitDetails.put("target/achieved", part2);
splitDetails.put("month", part3);
splitDetails.put("year", part4);
splitDetails.put("MDName", part5);
splitDetailsArray.put(splitDetails);
// TEST OUTPUT \\
System.out.println("Code:" + part1 + "\n Target/Achieved: " + part2 + "\n Month: " + part3 + "\n Year: " + part4 + "\n Name: " + part5);
}
}
// TEST OUTPUT \\
System.out.println(splitDetailsArray.toString());
}
} catch (Exception ex) {
request.setAttribute("message",
"There was an error: " + ex.getMessage());
}
// redirects client to message page
request.setAttribute("jsonString", splitDetailsArray.toString());
RequestDispatcher dispatcher = request.getRequestDispatcher("/test.jsp");
dispatcher.forward(request, response);
// getServletContext().getRequestDispatcher("/test.jsp").forward(
// request, response);
}
}
The above codes are running on tomcat 6
Again, I'm looking for a way to pass this JSON to a table in the test.jsp file.
In the most cases I'm asking just for an advice, but this time I will need some code examples, because I really have no idea on how to do it. It's my very first touch to the servlets. I lost 2 hours searching for help, but I was unable to find it.
Basically you would to loop through your JSON array using javascript and printing out html table tags. Here is an example answer below that should help you. I just searched for "print html tables from json" on Google.
Convert json data to a html table
I am trying to parse pages (any page dynamic parser).
code is
Elements title = doc.select("title");
Elements metades = doc.select("meta[name=description]");
As you can see i want to extract title tag.
It is working fine on approx every website for example hinddroid.com
But it unable to parse Title from google.com and youtube.com
I think it is due to no space between two tags.
Most of big website not have space in html to save bandwidth.
Please suggest me - i want to parse html from website.
Full code :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.regex.*;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class post_link extends HttpServlet
{
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{
//out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /><script src=\"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.3.min.js\"></script><script src=\"jquery-social.js\"></script>");
String linktopro = "http://"+request.getParameter("link_topro");
//String linktopro = "http://hinddroid.com";
Document doc = Jsoup.connect(linktopro).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").timeout(3000).get();
Elements png = doc.select("img[src]");
Elements title = doc.select("title:first-child");
//Elements title = doc.title();
Elements metades = doc.select("meta[name=description]");
Pattern p1 = Pattern.compile("http://.*|.com*?.(com)");
out.println("<script> var myCars=new Array(");
for(Element pngs : png)
{
Matcher m1 = p1.matcher(pngs.attr("src"));
boolean url = m1.matches();
String baseurl = "";
//out.println(url+"");
if(url)
{ baseurl = ""; }
else
{ baseurl = linktopro; }
out.println("\""+baseurl+""+pngs.attr("src")+"\",");
}
out.println("\"\"");
out.println(");</script>");
String outlink = "<div class=\"linkembox\">"+
"<div class=\"linkembox-img\">"+
"<img src=\"http://hinddroid.com/img/logo.gif\" width=\"150\" height=\"120\" />"+
"<br/><div id=\"linkimg-left\"><</div><div id=\"linkimg-right\">></div>"+
"</div>"+
"<div class=\"linkembox-text\">"+
"<div class=\"h\">"+title.html()+"</div><br/>"+
"<div class=\"h1\">"+metades.attr("content")+"</div>"+
"</div>"+
"</div>";
out.println(outlink);
out.print("<script> left(myCars); </script>");
}
catch(Exception ex)
{
out.print(ex);
}
finally
{
out.close();
}
}
}
I execute the selectors, it's fine. No problem at all!
public static void main( String[] args ) throws IOException
{
Document doc = Jsoup.connect("http://facebook.com").get();
System.out.println("Title: " + doc.title());
System.out.println("Meta Description: " + doc.select("meta[name=description]").first().attr("content"));
}
With google.com, you can get only <title>, not <meta name=description... because it's not in HTML source.