Tutorials Scripts Free Q&A Books


 







:שמתשמ
:המסיס
  

1 :םויה תוסינכ
52 :שדוחה תוסינכ
1 :ןיילנוא םישלוג
רחא PHP CGI ASP JavaScript Cold Fusion JSP

JSPב םיטפירקס


ילמודנאר 'גמיא
םיזיע בלוח :רבחמה םש
http://www.builder.co.il :תיב-רתא

:תורעה\תויחנה
.השדח הרוש לכב םי'גמיאה לש םוקימה םע טסקט ץבוק ורצי
.םדוק םתרציש טסקטה ץבוק םשל הטמל דוקב טסקטה םש תא ונש
> img src="
> servlet CODE="CSRandomImage">
> param name=name value=changeme.txt>
param name=type value=tex>

:דוק

File 1
##################################
/**
* CSRandomImage.java
* Matt Tucker
* CoolServlets.com
* July 10, 1999
* Version 1.0
*
* Copyright (C) 1999 Matt Tucker
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.coolservlets.randomimage.*;

/**
* A Servlet that displays random images.
*
* The servlet has two modes: text output and binary image output. If using,
* SSI or JSP, text output should be used. Binary output is great for normal
* webpages and can be used with something like:
* <img src="/servlet/CSRandomImage?name=animals">
*
* In that case, the servlet attempts to load up images from a file named
* animals.
*
* A user can specify the main directory of image collection text files as
* a servlet init parameter. A subdirectory can be specified at run time.
*/
public class CSRandomImage extends HttpServlet {

/**
* Initialize the servlet variables.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
database = new Hashtable();
// The path to where images are read from can be specified in two ways:
// *It can be given as an init parameter to the servlet as
// "path"
// *The servlet will default to "coolservlets/files/images/"
// in the working directory as defined by you JVM.
//
// Additionally, users can specify a subdirectory to use as a param
// when calling the servlet. Using symbolic links in the file system,
// this basically allows quote files to exist anywhere.
path = config.getInitParameter("path");
if (path == null) {
path = "coolservlets/files/images/";
}
}

/**
* Processes the HTTP get request. As you can see, all it does is call
* the doPost function.
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

/**
* HTTP post request.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//A flag that will indicate the program was unable to load the
//specified image file or if there is some other error.
boolean error = false;

//Find out if the user wants a binary image or just the text path
//and name of the image. Default is binary.
String type = request.getParameter("type");
if (type == null) {
type = "binary";
}

//See if the user tried to add their own subdirectory to the path.
String subdirectory = "";
if (request.getParameter("sudirectory") != null)
subdirectory = request.getParameter("sudirectory");

// A user can specify any text file to read as a parameter.
// If no specific file is requested, the "default.txt" file is used.
String fileName = request.getParameter("name");
if (fileName == null) {
error = true;
}
//Now, we need to make sure that servlet users can ONLY access files in
//the directory we want them too. So, "..","/" or "\" characters
//mean we'll reject the string and print an error. If there's some
//other way to bypass security, let us know. Basically, we don't want
//anyone printing out random lines of /etc/passwd :)
if (!error && (fileName.indexOf("..") > 0 || fileName.indexOf("/") > 0
|| fileName.indexOf("\\") > 0)) {
error = true;
}

//Caching! Checks to see whether the file is in in memory
//(hashtable). If not, put the textfile into a ImageCollection
//object and add it to the database.
try {
//We'll read in the text file from disk and put the
//images into a new image collection.
Vector tempVector = new Vector();
BufferedReader in = new BufferedReader(new FileReader(path + fileName));
String aLine;
while ((aLine = in.readLine()) != null) {
//Blank lines are ignored
if (!aLine.equals("")) {
tempVector.addElement(aLine);
}
}
//done reading lines into a vector so close file.
in.close();
//Copy vector contents into a String array
String [] images = new String[tempVector.size()];
tempVector.copyInto(images);
//Construct the image collection using the data and put
//the collection into the database.
ImageCollection newCollection = new ImageCollection(fileName,images);
database.put(fileName, newCollection);
}
catch (Exception e) { error = true; }

//Now, if there were no errors, pull specified collection from the
//hashtable and print a random image.
if (!error) {
//Now find a random element in the array. We'll either print out
//text if the user requests that, or give binary image output.
if (type.equals("text")) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String imageName = ((ImageCollection)database.get(fileName)).getImage();
out.println(imageName);
out.close();
}
//We want to return the actual binary image to the browser.
else {
ServletOutputStream out = response.getOutputStream();
BufferedOutputStream imageout = new BufferedOutputStream(out);
// Get the file to view
String imageName = ((ImageCollection)database.get(fileName)).getImage();
String imageFile = getServletContext().getRealPath("/")+imageName;
// Get and set the type of the file
String contentType = getServletContext().getMimeType(imageFile);
response.setContentType(contentType);
//Set headers to try to make browser not cache image
response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setHeader( "Cache-Control", "no-store" );
response.setDateHeader( "Expires", 0 );
try { writeImage(imageFile,imageout); } catch (Exception e) { }
imageout.close();
}
}
else {
//There was some error so print out an error message.
if (type.equals("text")) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>Error!</b> Could not load " + fileName +
". Please notify the webmaster.");
out.close();
}
//The user has requested binary data but there was some error.
//We should return some sort of binary error message, but will
//simply do nothing for now. Future versions of the servlet will
//implement this.
else {

}
}
}

/**
* Returns Servlet information
*/
public String getServletInfo() {
return "CSRandomImage 1.0 - CoolServlets.com";
}

/**
* Writes binary data to an output stream.
*/
public void writeImage(String filename, BufferedOutputStream out)
throws FileNotFoundException, IOException {
FileInputStream in = null;
try {
in = new FileInputStream(filename);
//Create a buffer that we can read data into
byte [] buf = new byte[4*1024];
int bytesRead;
//Keep writing data until we no longer can.
while((bytesRead = in.read(buf)) != 1) {
out.write(buf,0,bytesRead);
}
}
//Make sure to close the stream even if some error occured.
finally {
if (in != null) in.close();
}
}

private String path;
private Hashtable database;
}

File 2
#################################
/**
* ImageCollection.java
* Matt Tucker
* CoolServlets.com
* July 10, 1999
* Version 1.0
*
* Copyright (C) 1999 Matt Tucker
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.coolservlets.randomimage;

import java.util.Vector;

/**
* A data structure that represents a collection of images.
*
* Basically, a named array of image names that supports random access.
*/
public class ImageCollection {

private String key;
private String[] images;

/**
* An object that takes in a filename, and creates a String array out
* of the text from the file.
*/
public ImageCollection(String newKey, String [] newImages) {
//The "name" (key) of the object is the file name used to make it.
key = newKey;
images = newImages;
}

/**
* Returns the key for this image collection.
*/
public String getKey() {
return key;
}

/**
* Gets a random image out of the data.
*/
public String getImage() {
return images[(int)(Math.random()*100)%images.length];
}
}

 

הרזח >>
...