I created two files
1)index.html
2)player.jsp
I am using Tomcat Server.
In the index.html i created some checkboxes in a form and assigned the values...
After clicking submit i forwarded these values to player.jsp...
In player.jsp i dynamically generated an xml file named "generate.xml" .
This XML file changes according to the user request.
For each new request xml file should be overwritten.
if one check box is selected in the form ,structure in generate.xml will be in one form
if two check box's are selected in the form ,structure in generate.xml will be of another form.
I embedded a flash player in the jsp page which takes generate.xml as input and plays the songs accordingly...
The code of the player.jsp is
<%# page import="java.io.*" %>
<%# page contentType="text/html;charset=ISO-8859-1" %>
<%
int iLf = 10;
char cLf = (char)iLf;
String myfile = application.getRealPath("/") + "generate.xml";
File outputFile = new File(myfile);
outputFile.createNewFile();
FileWriter outfile = new FileWriter(outputFile);
outfile.write(" <?xml version='1.0' encoding='UTF-8'?> "+cLf);
outfile.write(" <playlist version='1' xmlns = 'http://xspf.org/ns/0/' > " +cLf);
outfile.write(" <title>My Band Rocks Your Socks</title> "+cLf);
outfile.write("<trackList>"+cLf);
%>
<%! String[] sports; %>
<%
sports = request.getParameterValues("sports");
out.println("<html><body><h1>hello</h1></body></html>");
if (sports != null)
{
for (int i = 0; i < sports.length; i++)
{
// outfile.writeln (sports[i]);
String total=sports[i];
String[] sa=total.split("[,]");
// String[] sub=new String();
outfile.write("<track>"+cLf);
for (int j=0;j<sa.length;j++)
{
// outfile.writeln(sa[j]);
// outfile.writeln("sa["+j+"]="+sa[j]);
if( j == 0)
{
outfile.write("<location>" + sa[0] +"</location>"+cLf);
}
else if (j == 1)
{
outfile.write("<image>" + sa[1] +"</image>"+cLf);
}
else if( j==2)
{
outfile.write("<title>" + sa[2] +"</title>"+cLf);
}
}// end of inner for loop()
outfile.write("</track>"+cLf);
//outfile.writeln();
}// end of outer for()
}
//else outfile.writeln ("<b>none<b>");
outfile.write(" </trackList> "+cLf);
outfile.write(" </playlist> "+cLf);
outfile.close();
%>
<object type="application/x-shockwave-flash" width="400" height="170"
data="xspf_player.swf?playlist_url=generate.xml">
<param name="movie" value="xspf_player.swf?playlist_url=generate.xml" />
</object>
my problem is in my local system all this is working fine
and the generate.xml is overwritten every time for every new request ...
I created ROOT.war and uploaded this file in www.eatj.com
here when 1st request is submitted an generate.xml file created according to the request..
for the next request this generate.xml is NOT OVERWRITTEN.
The player is taking the generate.xml file generated by the first request for all the new requests made.
pls help me in making any changes in the code so that i can overwrite the previous generated xml file..
The method getRealPath() doesn't work under war, and would return null, AFAIR. You must use relative path in order to make it work. Request.getResourceAsStream() is a better option. The use of getRealPath() is very much discouraged for the very reason.
[Edited]
Found a thread of coderanch confirming my doubt.
Related
my problem: i have a jsp where a button press will send a ID to the servlet.
with the iD, my Servlet will send it further to a method, to use a sql statement to fetch data from the database base on the id.
it all works fine, even the chart.
but now i want to include the chart back to my jsp and let the user see it without changing sites. with the outputstream it will stay on the servlet, and if i want to change my data, i need to go back.
i tried going for the saveasPng route, but java always say that path was not found.
any help is appreciated.
OutputStream outputStream = response.getOutputStream();
response.setContentType("image/png");
int width = 500;
int height = 350;
ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
// try {
// final ChartRenderingInfo info = new
// ChartRenderingInfo(new StandardEntityCollection());
//
// final File file1 = new File(request.getContextPath() + "WebContent/images/piechart.png");
// ChartUtilities.saveChartAsPNG(
// file1, chart, 600, 400, info);
// System.out.println("hallo TRue");
// } catch (Exception e) {
// e.printStackTrace();
// }
request.setAttribute("imagePath", request.getContextPath() + "/WebContent/images/piechart.png");
request.setAttribute("chart", chart);
//request.getRequestDispatcher("Diagramm.jsp").forward(request, response);
I see two different approaches here:
Add JavaScript to your JSP page and using AJAX patterns to invoke your servlet and modify dynamically the content of the JSP page within the browser with the result.
Refresh your JSP page adding a static HTML IMG tag where you invoke the servlet with the new ID parameter within the SRC attribute of the IMG tag. Something like <IMG src="/MyServlet?ID=xxx" width="500" height="350">
i want to upload a pdf file by using code given below.It give browsing facility but dont upload file. When i click sendfile button Its display uploadfile.html code page. How can i do that???
where is the error in the given code???
filename-upload.html
<%# page language="java" %>
<HTml>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<% // for uploading the file we used Encrypt type of multipart/
form-data and input of file type to browse and submit the file %>
<BODY> <FORM ENCTYPE="multipart/form-data" ACTION=
"uploadfile.html" METHOD=POST>
<br><br><br>
<center><table border="2" >
<tr><center><td colspan="2"><p align=
"center"><B>PROGRAM FOR UPLOADING THE FILE</B><center></td></tr>
<tr><td><b>Choose the file To Upload:</b>
</td>
<td><INPUT NAME="F1" TYPE="file"></td></tr>
<tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
<table>
</center>
</FORM>
</BODY>
</HTML>
filename--uploadfile.html
<%# page import="java.io.*" %>
<%
//to get the content type information from JSP Request Header
String contentType = request.getContentType();
//here we are checking the content type is not equal to Null and
as well as the passed data from mulitpart/form-data is greater than or
equal to 0
if ((contentType != null) && (contentType.indexOf("multipart/
form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.
getInputStream());
//we are taking the length of Content type data
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
//this loop converting the uploaded file into byte code
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,
formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
//for saving the file name
String saveFile = file.substring(file.indexOf("filename=\
"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")
+ 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,
contentType.length());
int pos;
//extracting the index of file
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation))
.getBytes()).length;
// creating a new file with the same name and writing the
content in new file
FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%><Br><table border="2"><tr><td><b>You have successfully
upload the file by the name of:</b>
<% out.println(saveFile); %></td></tr></table> <%
}
%>
This is clearly a Roseindia code snippet. First of all, it is the worst learning resource ever. Don't use it. It only teaches bad practices. Add that site to your blacklist. In fact, any "tutorial" site which is littered with advertisement banners and hopelessly outdated low quality code snippets are clearly maintained by amateurs with primary focus on advertisement income instead of on serious teaching. Other examples of such crap "tutorial" sites are javabeat, tutorialspoint, journaldev, javatpoint, etc. Remarkable common thing which those sites have is that they are originated in India.
Apart from the fact that you incorrectly used .html file extension instead of .jsp (even though they presented their examples correctly with .jsp extensions), there are several major problems with the code snippet:
The HTML is using '90s style uppercased tags. This is discouraged.
The HTML is using <font> and <center> tags which are deprecated since 1998.
The business logic is mingled with the presentation logic in a single JSP file. The Java code belongs in a Java class, not in a JSP file.
The parser is relying on Content-Length request header which is not always present per se. If this header is absent, the code breaks.
The parser is creating a byte array of that length. This may crash the server when the content length is larger than available server memory.
The parser is creating a String based on the byte array using server platform default character encoding instead of the one specified in multi part header. This may malform/corrupt the result bytes.
The DataInputStream wrapper is unnecessary, the code is not taking any benefit of it.
Etc..
Etc..
It's simply terrible.
The right way to upload a file from JSP is to submit the form to a #MultipartConfig annotated servlet class and then use request.getPart() to get the file. You can find a snippet in this answer: How to upload files to server using JSP/Servlet?
The right way to learn Java EE is elaborated in this answer: Java EE web development, where do I start and what skills do I need?
I have a two textboxes, namely LVPL_name and Email_ID.
If I select any name from the dropdown list of the LVPL_name it should automatically generate the respective email ID from the CSV file and display it in the JSP page.
My sample code:
try {
String fileName = "LVPL_names.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));
String[] rows = new CSVReader(reader).readEmail_ID();
if (x == Aarthi) {
System.out.println("Selected LVPL_name"+name.index of (Email_ID));
} else {
System.out.println("Enter the Email_ID");
}
} catch() {
}
And my Excel sheet is:
LVPL_name Email ID
-----------------------
aaaaa1 aaaaa1#sap.com
aaaaa2 aaaaa2#sap.com
aaaaa3 aaaaa3#sap.com
aaaaa4 aaaaa4#sap.com
aaaaa5 aaaaa5#sap.com
I think something is wrong in my code.
You have to do this through ajax / servlet / xhr requests. Here's an example of xhr request.
For following code to work properly as it as(unedited), You must have your CSV file in C: drive. Your CSV filename must be mydata.csv. And, also, you should place index.jsp and getEmail.jsp in the same folder.
index.jsp
<%#page import="java.io.File"%>
<%#page import="java.io.FileReader"%>
<%#page import="com.opencsv.CSVReader"%>
<%#page import="java.util.ArrayList"%>
<html>
<head>
<script>
function selected(value){
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "getEmail.jsp?lvpl=" + value, false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
document.getElementById('textbox').value = serverResponse;
}
</script>
</head>
<body>
<%
// Varaibles
String lvpl, email;
int counter = 0;
CSVReader reader = new CSVReader(new FileReader(new File("C://mydata.csv")));
String[] data;
%>
<select onchange="selected(this.value)">
<%
// READING TO CSV TO CREATE DATA IN SELECT BOX
while ((data = reader.readNext()) != null) {
// Skips CSV File Headings: LVPL and EMAIL_ID
if(counter == 0){
counter++; // Increase it so that it can't come in this block again
continue;
}
// CSV FILE DATA AS READ BY CSVREADER
lvpl = data[0]; // LVPL
email = data[1]; // EMAIL
%>
<option><%=lvpl%></option>
<%
}
%>
</select>
<input id="textbox" type="text" placeholder="email will show in here">
</body>
</html>
getEmail.jsp
<%#page import="java.io.FileReader"%>
<%#page import="java.io.File"%>
<%#page import="com.opencsv.CSVReader"%>
<%#page import="java.util.ArrayList"%>
<%
// get lvpl from received request
String lvplReceived = request.getParameter("lvpl");
// Reading CSV
String lvpl = "", email = "";
int counter = 0;
boolean lvplFound = false; // becomes true when lvpl matches selected lvpl
CSVReader reader = new CSVReader(new FileReader(new File("C://mydata.csv")));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
/* Skips CSV File Headers: LVPL and EMAIL_ID */
if(counter == 0){
counter++;
continue;
}
// CSV FILE DATA
lvpl = nextLine[0]; // LVPL
email = nextLine[1]; // EMAIL
if(lvpl.equals(lvplReceived)){ // if this lvpl matches with selected lvpl
lvplFound = true;
break;
}
}
if(lvplFound){ // print email of matched lvpl
out.print(email);
} else {
out.print("not found");
}
%>
tested with mydata.csv
LVPL EMAIL
aaaaa1 aaaaa1#sap.com
aaaaa2 aaaaa2#sap.com
aaaaa3 aaaaa3#sap.com
aaaaa4 aaaaa4#sap.com
aaaaa5 aaaaa5#sap.com
If this didn't work the way you wanted or if you don't understand this code, please feel free to contact me through comments
Useful Links:
Ajax Video Tutorials
OpenCSV Usage Guide
Ajax Example for Java Web Applications
Note: If you're learning JSP now, I suggest you to move to JSTL. JSP is no longer used and it was deprecated 10 years ago because it couln't match Microsoft's ASP. If you continue to learn JSP, it will not benefit you in future especially in India, I can't believe people there are still teaching a 10 year old technology. Here's a JSTL book to get you started.
I have an web application that uses JSF for form submission. I have a user select an image from a list followed by filling out and submitting a form. I then use the selected image and form input to annotate the image with the information. I then process a pdf file using the annotated images and email it to the user. After processing, I give the user the option to navigate back to the image selection page, or use the same images and go back to the form. Here is the jsf/html for the form that allows the user to navigate to their new page:
<h:form id="form" method="post">
<div>
<h:commandButton value="images" action="#{artwork.backToArt}"/>
</div>
<div>
<h:commandButton value="Form" action="#{artwork.backToForm}"/>
</div>
<div>
<h:commandButton value="Upload" action="#{artwork.backToUpload}"/>
</div>
</h:form>
It seems that IE caches the annotated images and keeps those images on display regardless of my method calls.
Here are my methods:
public String backToArt()
{
log.info("========= Setting back to art page ==========");
this.backToForm();
this.selectedValue = "";
this.resizedArt = "";
this.backArt = "";
return "loginSuccess.xhtml";
}
public String backToUpload()
{ log.info("========= Setting back to upload ==========");
this.backToForm();
this.selectedValue = "";
this.resizedArt = "";
this.backArt = "";
return "CSVSubmit.xhtml";
}
public String backToForm()
{
log.info("============ Reseting all variables ==========");
String temp = null;
if (this.selectedValue != null)
{
temp = this.selectedValue;
temp=temp.substring(temp.lastIndexOf(Dir.getDir("\\")) + 1, temp.length() - 4);
this.selectedValue = temp;
}
log.info("Setting input variables");
//set all previous values to blank
//this.jobNum = "";
this.quantity = null;
this.headLine = null;
this.codeNum = null;
this.pass = null;
this.expir = null;
this.website = null;
log.info("Setting front art to old image");
//setting previous images to non-text
if (temp.length() > 0)
{
temp = this.resizedArt;
temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
this.resizedArt=temp;
log.info("Setting back art to old image");
temp = this.backArt;
temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
this.backArt = temp;
log.info("Deleting old text images");
//start to delete text images
File folderOne = new File(Env.textDestOne);
this.deleteFiles(folderOne);
File folderTwo = new File(Env.textDestTwo);
this.deleteFiles(folderTwo);
}
log.info("============ Reset Complete ==========");
return "FormSubmission.xhtml";
}
These methods reset the input variables and the images selected as well as deletes my annotated images depending on which button is pressed on that page. Looking at my logging, the methods are called and are processed, but no updating occurs for the images. When I process my pdf, the correct images and input are outputed, but what is viewed still shows old values. This means that my values are being stored properly and my methods are being called correctly. When I go to cancel and reprocess using Google Chrome, the images are updated properly.
Using all of this information, I have concluded that IE must be caching my images and not updating them with the correct values. I'm not sure how to override this, but I need to somehow clear the cache so that the images are updated to the correct values.
Edit: I noticed that when I refresh the page hitting F5, the pictures would update. Not sure what this means.
I need to use Authorize.net AIM method to charge credit cards online. As a starting point, I've created a java servlet to call Authorize.net's sample JSP code. I'm a Java newbie and this is my first experience using JSP.
The servlet compiles fine, but when I access the servlet in a browser, it returns a blank screen. I was expecting to see the output generated by sample.jsp (even though it's not a real transaction). Anyone know why it's not showing up?
I'm guessing it's got something to do with the servlet using the variable res and the JSP file simply using out to write to the screen. Don't I need something like PrintWriter out = res.getWriter(); in the JSP file? Or, how does variable res get passed into the JSP file such that the JSP file can write the browser, etc? I'm not clear on this. Can someone give me a sanity check?
-------- Java Servlet -------
public class Payment extends HttpServlet {
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
// call sample.jsp
req.getRequestDispatcher("/sample.jsp").include(req,res);
} catch (Exception e) {
...
} finally {
...
}
}
}
-------- sample.jsp from Authorize.net; sits in same directory as Payment.class ---------
<!-- This sample code is designed to connect to Authorize.net using the AIM method.
For API documentation or additional sample code, please visit: http://developer.authorize.net -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML lang='en'>
<HEAD>
<TITLE> Sample AIM Implementation </TITLE>
</HEAD>
<BODY>
<P> This sample code is designed to generate a post using Authorize.net
Advanced Integration Method (AIM) and display the results of this post to
the screen. </P>
<P> For details on how this is accomplished, please review the readme file,
the comments in the sample code, and the Authorize.net AIM API documentation
found at http://developer.authorize.net </P>
<HR />
<%# page import="java.util.*" %>
<%# page import="java.net.*" %>
<%# page import="java.io.*" %>
<%# page import="javax.net.ssl.*" %>
<%# page import="java.net.URLEncoder" %>
<%
// By default, this sample code is designed to post to our test server for
// developer accounts: https://test.authorize.net/gateway/transact.dll
// for real accounts (even in test mode), please make sure that you are
// posting to: https://secure.authorize.net/gateway/transact.dll
URL post_url = new URL("https://test.authorize.net/gateway/transact.dll");
Hashtable post_values = new Hashtable();
// the API Login ID and Transaction Key must be replaced with valid values
post_values.put ("x_login", "API_LOGIN_ID");
post_values.put ("x_tran_key", "TRANSACTION_KEY");
post_values.put ("x_version", "3.1");
post_values.put ("x_delim_data", "TRUE");
post_values.put ("x_delim_char", "|");
post_values.put ("x_relay_response", "FALSE");
post_values.put ("x_type", "AUTH_CAPTURE");
post_values.put ("x_method", "CC");
post_values.put ("x_card_num", "4111111111111111");
post_values.put ("x_exp_date", "0115");
post_values.put ("x_amount", "19.99");
post_values.put ("x_description", "Sample Transaction");
post_values.put ("x_first_name", "John");
post_values.put ("x_last_name", "Doe");
post_values.put ("x_address", "1234 Street");
post_values.put ("x_state", "WA");
post_values.put ("x_zip", "98004");
// Additional fields can be added here as outlined in the AIM integration
// guide at: http://developer.authorize.net
// This section takes the input fields and converts them to the proper format
// for an http post. For example: "x_login=username&x_tran_key=a1B2c3D4"
StringBuffer post_string = new StringBuffer();
Enumeration keys = post_values.keys();
while( keys.hasMoreElements() ) {
String key = URLEncoder.encode(keys.nextElement().toString(),"UTF-8");
String value = URLEncoder.encode(post_values.get(key).toString(),"UTF-8");
post_string.append(key + "=" + value + "&");
}
// The following section provides an example of how to add line item details to
// the post string. Because line items may consist of multiple values with the
// same key/name, they cannot be simply added into the above array.
//
// This section is commented out by default.
/*
String[] line_items = {
"item1<|>golf balls<|><|>2<|>18.95<|>Y",
"item2<|>golf bag<|>Wilson golf carry bag, red<|>1<|>39.99<|>Y",
"item3<|>book<|>Golf for Dummies<|>1<|>21.99<|>Y"};
for (int i = 0; i < line_items.length; i++) {
String value = line_items[i];
post_string.append("&x_line_item=" + URLEncoder.encode(value));
}
*/
// Open a URLConnection to the specified post url
URLConnection connection = post_url.openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
// this line is not necessarily required but fixes a bug with some servers
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// submit the post_string and close the connection
DataOutputStream requestObject = new DataOutputStream( connection.getOutputStream() );
requestObject.write(post_string.toString().getBytes());
requestObject.flush();
requestObject.close();
// process and read the gateway response
BufferedReader rawResponse = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
String responseData = rawResponse.readLine();
rawResponse.close(); // no more data
// split the response into an array
String [] responses = responseData.split("\\|");
// The results are output to the screen in the form of an html numbered list.
out.println("<OL>");
for(Iterator iter=Arrays.asList(responses).iterator(); iter.hasNext();) {
out.println("<LI>" + iter.next() + " </LI>");
}
out.println("</OL>");
// individual elements of the array could be accessed to read certain response
// fields. For example, response_array[0] would return the Response Code,
// response_array[2] would return the Response Reason Code.
// for a list of response fields, please review the AIM Implementation Guide
%>
</BODY>
</HTML>
UPDATE 1
If I replace sample.jsp above with sampleJustHTML.jsp, it still gives a blank page.
---------- sampleJustHTML.jsp -----------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML lang='en'>
<HEAD>
<TITLE> Sample AIM Implementation </TITLE>
</HEAD>
<BODY>
<P> This sample code is designed to generate a post using Authorize.net
Advanced Integration Method (AIM) and display the results of this post to
the screen. </P>
</BODY>
</HTML>
If you put jsp file under WEB-INF folder you can use like :req.getRequestDispatcher("/WEB-INF/sample.jsp").include(req,res);
Now I will guess : req.getRequestDispatcher("/WEB-INF/classes/sample.jsp").include(req,res);