本人联系方式:msn :snowfox_1028@hotmail.com email:snowfox_1028@163.com
学习和使用这么久java,但是还是觉得很茫然,什么都知道一点,但是什么都不精通,如struts ,hibernate ,ejb,ibatis,spring,现在想想,应该选择一个目标,进行深入的学习和应用,这样才能有所成,做了这么长的java开发,最后得到的结论和经验就是这些。也好,有了一个明确的方向,一个目标,呵呵,可以走我自己的路了,日积月累,总会有所成的。现在写下这个帖子,是想感谢那些经常发帖的人,因为我每次遇到问题,总是有一些帖子给我启发,发帖的这些人应该是高尚的,值得学习,今天效仿一次,勿见笑
简要介绍这几个类的作用:XmlTest.java解析xml文件使用的是jdom(获取xml文件时请注意路径的获取),ImageTest.java使用读写图片的,包括远程服务器的图片,TitleService.java这是一个servlet,实现将Image对象写到页面上。以下几个类实现功能是从服务器上获取图片放到本地缓存上,并写到页面上,当下次从默认路径读取图片时,如果本地缓存有,则从本地缓存读取,否则从服务器读取。调用servlet方式是:http://localhost:8080/DemoTitleService/TitleService?X=264&Y=115&LAYERS=hyns:a61030_region&L=0,其中layers这个参数名需要在web.net.xml配置。
请注意图片的类型,png,jpeg,gif这三种格式在下面程序的使用。
如下:
图片读写类
package tool;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
/**
* @param args
* @author ****
* @date 2007-07-16
*/
public class ImageTest {
// get image from local
public BufferedImage readImage(String path_name){
File file = new File(path_name); // 读入文件
try {
BufferedImage img = ImageIO.read(file);// 构造Image对象
System.out.println(" get local image successfully ! ");
return img;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// get image from server
public List readImageFromServer (String HTTPurl){
try {
java.net.URL imageURL = new java.net.URL(HTTPurl);
BufferedImage img = ImageIO.read(imageURL);
InputStream is = imageURL.openStream();
List imageInfo = null;
if(img != null){
imageInfo = new ArrayList();
imageInfo.add(img);
imageInfo.add(is);
return imageInfo;
}else{
System.out.println(" get server image failure ! ");
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// write image to local
public boolean writeImage(InputStream is, String filepath,String filename){
int b = -1 ;
try {
File outfile = new File(filepath); //如果没有创建新的文件夹
if(! outfile.isDirectory()){
outfile.mkdirs();
}
if(! filepath.endsWith("/")){
filepath = filepath +"/" ;
}
FileOutputStream fos = new FileOutputStream(filepath+filename);// 输出到文件流
while((b = is.read())!= -1){
fos.write(b);
}
fos.close();
is.close();
System.out.println(" write image to local successfully ! ");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
xml解析类
package tool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
/**
* @param args
* @throws IOException
* @throws JDOMException
* @author *****
* @date 2007-07-16
*/
public class XmlTest {
public static String[] loadXml(String filepath){
try {
java.io.FileInputStream xmlFile = new java.io.FileInputStream(filepath);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xmlFile);
Element config = doc.getRootElement();
List application = (List) config.getChildren("appSettings");
Element e1 = (Element) application.get(0);
String[] array =new String[4];
array[0] = e1.getChildText("cachePath");
array[1] = e1.getChildText("LZD");
array[2] = e1.getChildText("wmsURL");
array[3] = e1.getChildText("param");
System.out.println("parse web.net.xml successfully ! ");
return array;
} catch (Exception e) {
e.printStackTrace();//
return null;
}
}
}
工具类
package tool;
import java.awt.Image;
import java.awt.image.BufferedImage;
/**
* @param args
* @author ****
* @date 2007-07-16
*/
public class UtilTest {
//number format to "0000"
public static String strFormat(String str){
if(str.length()==1){
str = "000" +str;
}else if(str.length()==2){
str = "00" +str;
}if(str.length()==3){
str = "0" +str;
}
return str;
}
//from image to bufferedimage
public static java.awt.image.BufferedImage fromImageTOBufferimage(Image image){
BufferedImage tag = new BufferedImage(image.getWidth(null) , image.getHeight(null),
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(image, 0, 0, image.getWidth(null) , image.getHeight(null) , null);
System.out.println("change from image to bufferedimage successfully ") ;
return tag;
}
//String split
public static String[] strSplit(String str){
String[] strArray = str.split(":");
return strArray;
}
}
servlet类
package servletTest;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tool.ImageTest;
import tool.UtilTest;
import tool.XmlTest;
public class TitleService extends HttpServlet {
/*
* @author *****
* @date 2007-07-16
* */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*****************************************************/
String[] strName ;
int intLevel;
String strForder = "";
String strPicName = "";
String[] strType ={ "jpg", "jpeg", "png"};
String strPath;
String strFile;
Integer X;
Integer Y;
/* 从配置文件web.net.xml中读取数据 */
double LZD ;//
String cathPath;
String wmsURL ;
String param;
String xmlpath = request.getRealPath("/");
String[] arrxml = XmlTest.loadXml(xmlpath+"Web.net.xml");
cathPath = arrxml[0];
LZD = Double.parseDouble(arrxml[1]);
wmsURL = arrxml[2];
param = arrxml[3];
//从servlet参数获取值
String paramvalue = request.getParameter(param.trim()) ;
strName = UtilTest.strSplit(paramvalue);
intLevel = Integer.parseInt(request.getParameter("L"));
X = Integer.parseInt(request.getParameter("X"));
Y = Integer.parseInt(request.getParameter("Y"));
String temp_strPicName = "";
boolean isRightLevel;
int i = 0;
/* 图片路径信息处理 */
try{
if(Y.toString().length()<= 4){
String str_y = Y.toString();
String str_x = X.toString();
str_y = UtilTest.strFormat(str_y);
str_x = UtilTest.strFormat(str_x);
strForder = str_y;
strPicName = strForder + "_" + str_x;
}else{
strForder = Y.toString();
strPicName = X.toString();
temp_strPicName = strForder + "_" + strPicName;
}
}catch(java.lang.Exception e){
response.setContentType("text/plain");
java.io.PrintWriter out = response.getWriter();
out.println("404 File Not Found");
out.close();
}
if(! cathPath.endsWith("/")){
cathPath = cathPath + "/";
}
strPath = cathPath + strName[0]+"/"+ strName[1] + "/" + intLevel + "/" + strForder + "/"; //E:/数据/广州数据--缓存/T/L/Y/Y_X
strFile = strPath + strPicName + "." + strType[0];
if (intLevel >= 0 && intLevel <= 12){
isRightLevel = true;
}
else{
isRightLevel = false;
}
/* 判断图片是否存在本地缓存上 */
File readFile = new File(strFile);
while(! readFile.isFile()&& i < strType.length - 1){
i++;
strFile = strPath + strPicName + "." + strType[i];
readFile = new File(strFile);
}
if(! readFile.isFile()){
strFile = strPath + temp_strPicName + "." + strType[0];
i = 0;
while (! readFile.isFile() && i < strType.length - 1){
i++;
strFile = strPath + temp_strPicName + "." + strType[i];
readFile = new File(strFile);
}
}
/* 如果在本地缓存中有该图片,那么写到页面上 */
if(readFile.isFile() && isRightLevel ){
try{
ImageTest image = new ImageTest();
response.setContentType("image/png");
ServletOutputStream sos = response.getOutputStream();
BufferedImage bi= image.readImage(strFile);
ImageIO.write(bi,"png",sos);
sos.close();
}catch(java.lang.Exception e){
response.setContentType("text/plain");
java.io.PrintWriter out = response.getWriter();
out.println("404 File Not Found");
out.close();
}
}else if (isRightLevel){
try{
/*如果本地缓存没有该图片 ,那么从指定的服务器上读取该图片*/
String strLatitudeX1;
String strLatitudeX2;
String strLongitudeY1;
String strLongitudeY2;
String strWMSOtherParas;
String strHttpUrl;
double dblUnit;
dblUnit = LZD / (1 << intLevel);
// BigDecimal是用来计算浮点型数据
BigDecimal bigX1 = new BigDecimal(Y).multiply(new BigDecimal(dblUnit)) ;
bigX1 = bigX1.add(new BigDecimal(-90)) ;
strLatitudeX1 = new String(bigX1.setScale(10,1).toString());
BigDecimal bigX2 = new BigDecimal(Y+1).multiply(new BigDecimal(dblUnit)) ;
bigX2 = bigX2.add(new BigDecimal(-90)) ;
strLatitudeX2 = new String(bigX2.setScale(10,1).toString());
BigDecimal bigY1 = new BigDecimal(X).multiply(new BigDecimal(dblUnit)) ;
bigY1 = bigY1.add(new BigDecimal(-180)) ;
strLongitudeY1 = new String(bigY1.setScale(10,1).toString());
BigDecimal bigY2 = new BigDecimal(X+1).multiply(new BigDecimal(dblUnit)) ;
bigY2 = bigY2.add(new BigDecimal(-180)) ;
strLongitudeY2 = new String(bigY2.setScale(10,1).toString());
System.out.println(strLatitudeX1+strLatitudeX2+strLongitudeY1 +strLongitudeY2);
// 从服务器上获取图片
strHttpUrl = wmsURL + "&"+param+"="+paramvalue+"&BBOX=";
strHttpUrl = strHttpUrl + strLongitudeY1 + "," + strLatitudeX1 + "," + strLongitudeY2 + "," + strLatitudeX2 ;
System.out.println("server url : "+strHttpUrl);
ImageTest getServerImage = new ImageTest();
List imageInfo = getServerImage.readImageFromServer(strHttpUrl);
BufferedImage getImage =(BufferedImage) imageInfo.get(0);
String strSaveFile = strPath + strPicName + "." + strType[1];
getServerImage.writeImage((InputStream) imageInfo.get(1), strPath , strPicName + "." + strType[1] );
response.setContentType("image/png");
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(getImage,"png",sos);
sos.close();
}catch (Exception ex){
java.io.PrintWriter out = response.getWriter();
out.println(ex.getMessage());
out.close();
}
}else{
response.setContentType("text/plain");
java.io.PrintWriter out = response.getWriter();
out.println("404 File Not Found");
out.close();
}
}
}
被解析的xml文件
<?xml version="1.0" encoding="gb2312"?>
<configuration>
<appSettings>
<cachePath>D:/temp/</cachePath>
<LZD>1.125</LZD>
<wmsURL><![CDATA[http://192.168.0.4:8080/geoserver/wms?FORMAT=image/gif&TRANSPARENT=TRUE&HEIGHT=406&REQUEST=GetMap&WIDTH=810&STYLES=&SRS=EPSG:4326&VERSION=1.1.1]]></wmsURL>
<param>LAYERS</param>
</appSettings>
</configuration>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>TitleService</servlet-name>
<servlet-class>servletTest.TitleService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TitleService</servlet-name>
<url-pattern>/TitleService</url-pattern>
</servlet-mapping>
</web-app>