欢迎光临
我们一直在努力

初学jsp心得-JSP教程,Jsp/Servlet

建站超值云服务器,限时71元/月

测试环境为 jdk1.2.2 jswdk-1.0 winnt4.0中文版。

1。java是大小写敏感的,用过其他编程语言的人最容易犯这个错误,尤其是刚上手的时候。我刚开始调试jsp的时50%以上的编译错误是都是因为这个。

2。java的调用过程都是要加括号的,一开始比较容易忽视,如title=request.getparameter(\"title\").trim();

3。jsp中对应asp中的request.form()和request.querystring()的解决方法。

jsp中取得参数没有form和querystring之分,都是通过request.getparameter(\"xxxx\")来取得。虽然jsp也有request.getquerystring()方法,但测试结果是 test.jsp?id=1&page=20 得到 id=1&page=20。

  如果url和form有相同的参数名称呢?下面是一段测试代码:

<form method=\"post\" action=\"query.jsp?id=2\">

 <input type=\"text\" name=\"id\" value=\"1\" size=\"60\">

</form>

name都是id,结果是url的参数优先得到,jsp的这种处理方式和asp相比我觉的各有所长。

4。头疼的汉字处理问题。

在其他的文章里曾说到在中文nt环境下如下语句输出会得到乱码,

<%=\"你好\"%> 及 out.print(\"你好\");等。解决方法是只要对字符串变量进行编码就可以得到正确结果,如下代码可以得到正确的输出:

<% string title=\"你好\";

 byte[] tmpbyte=title.getbytes(\"iso8859_1\");

 title=new string(tmpbyte);

 out.print(title); %>

或者<%=title%>

关于sql语句汉字问题,例句为 select * from test where title=谁是傻瓜

在jdbc-odbc驱动下连db2,不管是原句还是对sql语句进行编码后都死活通不过。

换了ibm的jdbc直接驱动后,对sql语句编码后程序可以通过。

这个问题的产生大概是中文nt的原因,在其他环境下可能就没汉字处理问题了,据说ibm的web sphere对中文支持的很好,这也给jsp的开发带来一定的通用性问题。据说对字符串编码是一种通用的解决方法,不过没有这么多环境来测试。

5。在asp中经常使用到字符串判断语句如 if state=\"真是傻瓜\" then…..

  在java中string变量不是一个简单的变量而是一个类实例,不同的方法会得到不同的结果

a.

string str1=\"我是傻瓜\";

string str2=\"我是傻瓜\"; (or string str2=\"我是\"+\"傻瓜\"; )

if (str1==str2)

 out.print(\"yes\");

else 

 out.print(\"no\");

结果是\"yes\"。

大概是编译优化,str1,str2指向同一个类实例;

b.

string str1,str2,str3;

str1=\"我是傻瓜\";

str2=\"我是\";

str3=str2+\"傻瓜\";

if (str1==str3)

 out.print(\"yes\");

else

 out.print(\"no\");

结果是\"no\"。

string str1=new string(\"我是傻瓜\");

string str2=new string(\"我是傻瓜\");

if (str1==str2)

 out.print(\"yes\");

else

 out.print(\"no\");

结果是\"no\"。

string str1=new string(\"我是傻瓜\");

string str2=new string(\"我是傻瓜\");

if (str1.compareto(str2)==0)

 out.print(\"yes\");

else

 out.print(\"no\");

结果是\"yes\"。

所以在jsp中判断字符串要使用compareto方法,用惯传统语言还真一下子适应不过来,熟悉java的朋友应该没这个问题。

6。如何判断数据库为空?

  result = stmt.executequery(sql);

  if (result.next())

   ……

  result执行后游标出于一个未明的状态,不能进行状态判断,也不能取值,一定要next()一下才可以用。

 

7。在jsp中实现分页。

page是关键字,不能当变量。

conn.jsp

<%

  string sdbdriver = \"com.ibm.db2.jdbc.app.db2driver\";

  string sconnstr = \"jdbc:db2:faq\";

  connection conn = null;

  statement stmt = null;

  resultset rs=null;

    try {

        class.forname(sdbdriver);  

  }

    catch(java.lang.classnotfoundexception e)   {

    out.print(\"faq(): \" + e.getmessage());

  }

  

  try{

    conn = drivermanager.getconnection(sconnstr,\"wsdemo\",\"wsdemo1\");    

    stmt = conn.createstatement();

  }catch(sqlexception e){

    out.print(e.tostring());

  }

%>

query.jsp

<%@ page language=\"java\" import=\"java.sql.*\" %>

<%@ page contenttype=\"text/html; charset=gb2312\" %>

<%@ include file=\"conn.jsp\" %>

<%

…….

int pages=0;

int pagesize=10;

resultset result = null;

resultset rcount = null;

pages = new integer(request.getparameter(\"pages\")).intvalue();

if (pages>0)

{

string sql=\" state=我不傻\";

int count=0;

try {

rcount = stmt.executequery(\"select count(id) as id from user where \"+sql);

catch(sqlexception ex) {

 out.print(\"aq.executequery: \" + ex.getmessage());

 }

if(rcount.next())

 count = rcount.getint(\"id\");

rcount.close();

if (count>0)

{

sql=\"select * from user where \"+sql;

try {

result = stmt.executequery(sql);

  }

catch(sqlexception ex) {

 out.print(\"aq.executequery: \" + ex.getmessage());

 }

int i;

string name;

// result.first();

// result.absolute((pages-1)*pagesize);

// 此方法jdbc2.0支持。编译通过,但执行不过,不知是不是跟驱动有关,只好用下面的笨办法。

for(i=1;i<=(pages-1)*pagesize;i++)

 result.next();

for(i=1;i<=pagesize;i++) {

 if (result.next()) {

 name=result.getstring(\"name\");

 out.print(name);

 }

result.close();

int n= (int)(count/pagesize);

if (n*pagesize<count) n++;

if (n>1)

{

for(i=1;i<=n;i++)

  out.print(\"<a href=query.jsp?pages=\"+i+\">\"+i+\" </a>\");

}

}

}

%>

数据库怎么连接,怎么老出错啊?所以我集中的在这写篇文章供大家参考,其实这种把数据库逻辑全部放在jsp里未必是好的做法,但是有利于初学者学习,所以我就这样做了,当大家学到一定程度的时候,可以考虑用mvc的模式开发。在练习这些代码的时候,你一定将jdbc的驱动程序放到服务器的类路径里,然后要在数据库里建一个表test,有两个字段比如为test1,test2,可以用下面sql建

create table test(test1 varchar(20),test2 varchar(20)

然后向这个表写入一条测试纪录

那么现在开始我们的jsp和数据库之旅吧。

一、jsp连接oracle8/8i/9i数据库(用thin模式)

testoracle.jsp如下:

<%@ page contenttype="text/html;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<html>

<body>

<%class.forname("oracle.jdbc.driver.oracledriver").newinstance();

string url="jdbc:oracle:thin:@localhost:1521:orcl";

//orcl为你的数据库的sid

string user="scott";

string password="tiger";

connection conn= drivermanager.getconnection(url,user,password);

statement stmt=conn.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);

string sql="select * from test";

resultset rs=stmt.executequery(sql);

while(rs.next()) {%>

您的第一字段内容为:<%=rs.getstring(1)%>

您的第二个字段内容为:<%=rs.getstring(2)%>

<%}%>

<%out.print("数据库操作成功,恭喜你");%>

<%rs.close();

stmt.close();

conn.close();

%>

</body>

</html>

二、jsp连接sql server7.0/2000数据库

testsqlserver.jsp如下:

<%@ page contenttype="text/html;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<html>

<body>

<%class.forname("com.microsoft.jdbc.sqlserver.sqlserverdriver").newinstance();

string url="jdbc:microsoft:sqlserver://localhost:1433;databasename=pubs";

//pubs为你的数据库的

string user="sa";

string password="";

connection conn= drivermanager.getconnection(url,user,password);

statement stmt=conn.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);

string sql="select * from test";

resultset rs=stmt.executequery(sql);

while(rs.next()) {%>

您的第一个字段内容为:<%=rs.getstring(1)%>

您的第二个字段内容为:<%=rs.getstring(2)%>

<%}%>

<%out.print("数据库操作成功,恭喜你");%>

<%rs.close();

stmt.close();

conn.close();

%>

</body>

</html>

三、jsp连接db2数据库

testdb2.jsp如下:

<%@ page contenttype="text/html;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<html>

<body>

<%class.forname("com.ibm.db2.jdbc.app.db2driver ").newinstance();

string url="jdbc:db2://localhost:5000/sample";

//sample为你的数据库名

string user="admin";

string password="";

connection conn= drivermanager.getconnection(url,user,password);

statement stmt=conn.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);

string sql="select * from test";

resultset rs=stmt.executequery(sql);

while(rs.next()) {%>

您的第一个字段内容为:<%=rs.getstring(1)%>

您的第二个字段内容为:<%=rs.getstring(2)%>

<%}%>

<%out.print("数据库操作成功,恭喜你");%>

<%rs.close();

stmt.close();

conn.close();

%>

</body>

</html>

四、jsp连接informix数据库

testinformix.jsp如下:

<%@ page contenttype="text/html;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<html>

<body>

<%class.forname("com.informix.jdbc.ifxdriver").newinstance();

string url =

"jdbc:informix-sqli://123.45.67.89:1533/testdb:informixserver=myserver;

user=testuser;password=testpassword";

//testdb为你的数据库名

connection conn= drivermanager.getconnection(url);

statement stmt=conn.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);

string sql="select * from test";

resultset rs=stmt.executequery(sql);

while(rs.next()) {%>

您的第一个字段内容为:<%=rs.getstring(1)%>

您的第二个字段内容为:<%=rs.getstring(2)%>

<%}%>

<%out.print("数据库操作成功,恭喜你");%>

<%rs.close();

stmt.close();

conn.close();

%>

</body>

</html>

五、jsp连接sybase数据库

testmysql.jsp如下:

<%@ page contenttype="text/html;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<html>

<body>

<%class.forname("com.sybase.jdbc.sybdriver").newinstance();

string url =" jdbc:sybase:tds:localhost:5007/tsdata";

//tsdata为你的数据库名

properties sysprops = system.getproperties();

sysprops.put("user","userid");

sysprops.put("password","user_password");

connection conn= drivermanager.getconnection(url, sysprops);

statement stmt=conn.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);

string sql="select * from test";

resultset rs=stmt.executequery(sql);

while(rs.next()) {%>

您的第一个字段内容为:<%=rs.getstring(1)%>

您的第二个字段内容为:<%=rs.getstring(2)%>

<%}%>

<%out.print("数据库操作成功,恭喜你");%>

<%rs.close();

stmt.close();

conn.close();

%>

</body>

</html>

六、jsp连接mysql数据库

testmysql.jsp如下:

<%@ page contenttype="text/html;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<html>

<body>

<%class.forname("org.gjt.mm.mysql.driver").newinstance();

string url ="jdbc:mysql://localhost/softforum?user=soft&password=soft1234&useunicode=true&characterencoding=8859_1"

//testdb为你的数据库名

connection conn= drivermanager.getconnection(url);

statement stmt=conn.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);

string sql="select * from test";

resultset rs=stmt.executequery(sql);

while(rs.next()) {%>

您的第一个字段内容为:<%=rs.getstring(1)%>

您的第二个字段内容为:<%=rs.getstring(2)%>

<%}%>

<%out.print("数据库操作成功,恭喜你");%>

<%rs.close();

stmt.close();

conn.close();

%>

</body>

</html>

七、jsp连接postgresql数据库

testmysql.jsp如下:

<%@ page contenttype="text/html;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<html>

<body>

<%class.forname("org.postgresql.driver").newinstance();

string url ="jdbc:postgresql://localhost/soft"

//soft为你的数据库名

string user="myuser";

string password="mypassword";

connection conn= drivermanager.getconnection(url,user,password);

statement stmt=conn.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);

string sql="select * from test";

resultset rs=stmt.executequery(sql);

while(rs.next()) {%>

您的第一个字段内容为:<%=rs.getstring(1)%>

您的第二个字段内容为:<%=rs.getstring(2)%>

<%}%>

<%out.print("数据库操作成功,恭喜你");%>

<%rs.close();

stmt.close();

conn.close();

%>

</body>

</html>

在jsp中使用smartupload组件上传文件

jsp对上传文件的支持不象php中支持的那么好,直接做成了函数,也不象asp中要通过组件才能实现。jsp中可以通过javabean来实现。但是我们没有必要自己去写一个上载的bean,在网上已经有了很多成型的技术,smartupload就是其中的一个。但是smartupload是将文件先读到服务器的内存中,所以上传太大的文件(超过100兆)有可能会出问题,也算是一个美中不足吧:)

先说一下提交的页面,smartupload组件要求用字节流的方式来提交<form action="upload.jsp" enctype=multipart/form-data method=post>。下面就是个例子upload.htm:

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">

<!– saved from url=(0057)http://localhost:8080/jspsmartfile/jsp/uploadtemplate.jsp –>

<html><head>

<meta content="text/html; charset=gb2312" http-equiv=content-type>

<meta content="mshtml 5.00.2920.0" name=generator></head>

<body bgcolor=#e6e6e6><br>

<form action="upload.jsp" enctype=multipart/form-data method=post>

<table>

<tbody>

<tr>

<td><font color=#000000 face=helv,helvetica size=1> file

: </font> <input size=60 type=file name="file"></td></tr>

<tr>

<tr>

<td><font color=#000000 face=helv,helvetica size=1> file

: </font> <input size=60 type=file name="file1"></td></tr>

<tr>

<td><font color=#000000 face=helv,helvetica size=1> file

: </font> <input size=60 type=text name="text"></td></tr>

<tr>

<td

align=right><input type=submit value=send name="send"></td></tr></tbody></table></form></body></html>

再来看一下接收的页面 ,我们把文件上传到服务器以后就直接把它再存入数据库中:upload.jsp

<%@ page contenttype="text/hml;charset=gb2312"%>

<%@ page import="java.sql.*"%>

<%@ page import="com.jspsmart.upload.*" %>

<%@ page import="dbstep.idbmanager2000.*"%>

<%

//实例化上载bean

com.jspsmart.upload.smartupload mysmartupload=new com.jspsmart.upload.smartupload();

//初始化

mysmartupload.initialize(pagecontext);

//设置上载的最大值

mysmartupload.setmaxfilesize(500 * 1024*1024);

//上载文件

mysmartupload.upload();

//循环取得所有上载的文件

for (int i=0;i<mysmartupload.getfiles().getcount();i++){

//取得上载的文件

com.jspsmart.upload.file myfile = mysmartupload.getfiles().getfile(i);

if (!myfile.ismissing())

{

//取得上载的文件的文件名

string myfilename=myfile.getfilename();

//取得不带后缀的文件名

string suffix=myfilename.substring(0,myfilename.lastindexof(.));

//取得后缀名

string ext= mysmartupload.getfiles().getfile(0).getfileext();

//取得文件的大小

int filesize=myfile.getsize();

//保存路径

string aa=getservletcontext().getrealpath("/")+"jsp\\";

string trace=aa+myfilename;

//取得别的参数

string explain=(string)mysmartupload.getrequest().getparameter("text");

string send=(string)mysmartupload.getrequest().getparameter("send");

//将文件保存在服务器端

myfile.saveas(trace,mysmartupload.save_physical);

//下面的是将上载的文件保存到数据库中

//将文件读到流中

java.io.file file = new java.io.file(trace);

java.io.fileinputstream fis = new java.io.fileinputstream(file);

out.println(file.length());

//打开数据库

resultset result=null;

string msql=null;

preparedstatement prestmt=null;

dbstep.idbmanager2000 dbaobj=new dbstep.idbmanager2000();

dbaobj.openconnection();

//将文件写到数据库中

msql="insert into marklist (markname,password,marksize,markdate,markbody) values (?,?,?,?,?)";

prestmt =dbaobj.conn.preparestatement(msql);

prestmt.setstring(1, "aaa1");

prestmt.setstring(2, "0000");

prestmt.setint(3, filesize);

prestmt.setstring(4, dbaobj.getdatetime());

prestmt.setbinarystream(5,fis,(int)file.length());

dbaobj.conn.setautocommit(true) ;

prestmt.executeupdate();

dbaobj.conn.commit();

out.println(("上载成功!!!").tostring());

}

else

{ out.println(("上载失败!!!").tostring()); }

}//与前面的if对应

%>

再说一下下载,下载分两种情况1。从数据库直接下载2。从服务器上下载

先说从数据库直接下载的情形:就是把输入流从数据库里读出来,然后转存为文件

<%@ page contenttype="text/html; charset=gb2312" %>

<%@ page import="java.sql.*"%>

<%@ page import="java.io.*" %>

<%@ page import="dbstep.idbmanager2000.*"%>

<%

int bytesum=0;

int byteread=0;

//打开数据库

resultset result=null;

string sql=null;

preparedstatement prestmt=null;

dbstep.idbmanager2000 dbaobj=new dbstep.idbmanager2000();

dbaobj.openconnection();

//取得数据库中的数据

sql="select * from t_local_zhongzhuan ";

result=dbaobj.executequery(sql);

result.next();

//将数据库中的数据读到流中

inputstream instream=result.getbinarystream("content");

fileoutputstream fs=new fileoutputstream( "c:/dffdsafd.doc");

byte[] buffer =new byte[1444];

int length;

while ((byteread=instream.read(buffer))!=-1)

{

out.println("<dt><b>"+byteread+"</b></dt>");

bytesum+=byteread;

system.out.println(bytesum);

fs.write(buffer,0,byteread);

}

%>

再说从服务器上下载的情形:

<%@ page contenttype="text/html; charset=gb2312" %>

<%@ page import="java.io.*" %>

<%

string filename = "zsc104.swf".tostring();

f//读到流中

inputstream instream=new fileinputstream("c:/zsc104.swf");

//设置输出的格式

response.reset();

response.setcontenttype("bin");

response.addheader("content-disposition","attachment; filename=\"" + filename + "\"");

//循环取出流中的数据

byte[] b = new byte[100];

int len;

while((len=instream.read(b)) >0)

response.getoutputstream().write(b,0,len);

instream.close();

%>

好了,到这里只要不是太大的文件的上传下载的操作都可以完成了。

缩略图实现,将图片(jpg,gif,bmp等等)真实的变成想要的大小

import java.io.*;

import java.util.*;

import com.sun.image.codec.jpeg.*;

import java.awt.image.*;

import java.awt.*;

import java.net.*;

import java.applet.*;

import java.sql.*;

//缩略图类,

//本java类能将jpg图片文件,进行等比或非等比的大小转换。

//具体使用方法

//s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))

public class small_pic{

string inputdir; //输入图路径

string outputdir; //输出图路径

string inputfilename; //输入图文件名

string outputfilename; //输出图文件名

int outputwidth=80; //默认输出图片宽

int outputheight=80; //默认输出图片高

int rate=0;

boolean proportion=true; //是否等比缩放标记(默认为等比缩放)

public small_pic(){

//初始化变量

inputdir="";

outputdir="";

inputfilename="";

outputfilename="";

outputwidth=80;

outputheight=80;

rate=0;

}

public void setinputdir(string inputdir){

this.inputdir=inputdir;

}

public void setoutputdir(string outputdir){

this.outputdir=outputdir;

}

public void setinputfilename(string inputfilename){

this.inputfilename=inputfilename;

}

public void setoutputfilename(string outputfilename){

this.outputfilename=outputfilename;

}

public void setoutputwidth(int outputwidth){

this.outputwidth=outputwidth;

}

public void setoutputheight(int outputheight){

this.outputheight=outputheight;

}

public void setw_h(int width,int height){

this.outputwidth=width;

this.outputheight=height;

}

public string s_pic(){

bufferedimage image;

string newfilename;

//建立输出文件对象

file file = new file(outputdir+outputfilename);

fileoutputstream tempout =null;

try{

tempout= new fileoutputstream(file);

}catch(exception ex){

system.out.println(ex.tostring());

}

image img=null;

toolkit tk=toolkit.getdefaulttoolkit();

applet app=new applet();

mediatracker mt = new mediatracker(app);

try {

img=tk.getimage(inputdir+inputfilename);

mt.addimage(img, 0);

mt.waitforid(0);

}catch(exception e) {

e.printstacktrace();

}

if(img.getwidth(null)==-1){

system.out.println(" cant read,retry!"+"<br>");

return "no";

}else{

int new_w;

int new_h;

if (this.proportion==true) //判断是否是等比缩放.

{

//为等比缩放计算输出的图片宽度及高度

double rate1=((double)img.getwidth(null))/(double)outputwidth+0.1;

double rate2=((double)img.getheight(null))/(double)outputheight+0.1;

double rate=rate1>rate2?rate1:rate2;

new_w=(int)(((double)img.getwidth(null))/rate);

new_h=(int)(((double)img.getheight(null))/rate);

}

else{

new_w=outputwidth; //输出的图片宽度

new_h=outputheight; //输出的图片高度

}

bufferedimage buffimg = new bufferedimage(new_w,new_h,bufferedimage.type_int_rgb);

graphics g = buffimg.creategraphics();

g.setcolor(color.white);

g.fillrect(0,0,new_w,new_h);

g.drawimage(img,0,0,new_w,new_h,null);

g.dispose();

jpegimageencoder encoder = jpegcodec.createjpegencoder(tempout);

try{

encoder.encode(buffimg);

tempout.close();

}catch(ioexception ex){

system.out.println(ex.tostring());

}

}

return "ok";

}

public string s_pic(string inputdir,string outputdir,string inputfilename,string outputfilename){

//输入图路径

this.inputdir=inputdir;

//输出图路径

this.outputdir=outputdir;

//输入图文件名

this.inputfilename=inputfilename;

//输出图文件名

this.outputfilename=outputfilename;

return s_pic();

}

public string s_pic(string inputdir,string outputdir,string inputfilename,string outputfilename,int width,int height,boolean gp){

//输入图路径

this.inputdir=inputdir;

//输出图路径

this.outputdir=outputdir;

//输入图文件名

this.inputfilename=inputfilename;

//输出图文件名

this.outputfilename=outputfilename

//设置图片长宽

setw_h(width,height);

//是否是等比缩放 标记

this.proportion=gp;

return s_pic();

}

public static void main(string [] a)

{

//s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度)

small_pic mypic =new small_pic();

system.out.println(

mypic.s_pic("e:\\java\\j2eedatum\\王亮jsp资料\\缩图例子\\personal\\",

"e:\\java\\j2eedatum\\酒剑仙jsp资料\\缩图例子\\personal\\",

"1.jpg","new1.jpg",80,80,true)

);

}

在jsp中使用javamail

java中文站

你希望在jsp中建立一个邮件发送收取工具吗?下面将介绍的就是在jsp中建立一个邮件发送收取工具。在这篇文章中你可以了解到javamail api的一些要点以及如何在jsp中使用它。本文中还包括了在jsp中使用javamail的实例。javamail是jsp应用软件中相当强大的api。

阅读这篇文章需要对jsp、javabeans和javamail有一定的初步了解。当然,有关于javamail的知识你可以通过阅读这篇文章来获得。如果你对于以上三项一无所知,但你所使用的服务器支持jsp和javamail的话,你可以仅仅通过复制/粘贴来使用它们。

什么是javamail

javamail是sun发布的用来处理email的api。它可以方便地执行一些常用的邮件传输。

虽然javamail是sun的api之一,但它目前还没有被加在标准的java开发工具包中(java development kit),这就意味着你在使用前必须另外下载javamail文件。除此以外,你还需要有sun的javabeans activation framework (jaf)。javabeans activation framework的运行很复杂,在这里简单的说就是javamail的运行必须得依赖于它的支持。在windows 2000下使用需要指定这些文件的路径,在其它的操作系统上也类似。

接下来要讲解的是这篇指南的最难理解的部分。

这篇指南包括三部分:html表格、关于javamail、javamail和jsp的结合。

第一部分:html表格

第一部分提供了一个最基本的基于html的email发送收取程序的例子。第二部分则讲述javamail的工作原理。第三部分则介绍将javamail加入jsp,创建一个基本的email发送收取程序。

划分组件

jsp最重要的特性是能将整个网页划分成一些细小的组件。这里使用的组件包括:

●一个用来将email的信息发送给jsp的html表格;

●一个jsp页面用来处理和发送信件。

第一步,就是创建一个html表格用来给jsp页面发送信息。你可以将以下的html代码复制到你的电脑上:

用来发送email的html源代码

<html>

<body>

<form action="sendmail.jsp" method="post">

<table align="center">

<tr>

<td width="50%">

to:<br><input name="to" size="25">

</td>

<td width="50%">

from:<br><input name="from" size="25">

</td>

</tr>

<tr>

<td colspan="2">

subject:<br><input name="subject" size="50">

</td>

</tr>

<tr>

<td colspan="2">

<p>message:<br><textarea name="text" rows=25 cols=85></textarea></p>

</td>

</tr>

</table>

<input type="submit" name="cb_submit" value=" send ">

<input type="reset" name="cb_reset" value=" clear ">

</form>

</body>

</html>

以上这段程序将创建一个包含email基本信息(例如:收件地址、发送地址、主题和内容)的文件。当然你可以根据你自己的需要来决定这个文件包含那些信息。

这个html文件的使用有两点要求:第一点是生成的文件必须发送给接下来将介绍的程序使用。在这个例子中就是sendmail.jsp,但在你使用时,必须用这个文件在系统里的url来代替它;第二点是必须有空间来允许用户发送email。

第二部分将对javamail的特征进行一些分析,为在第三部分创建jsp程序作准备。所以接下来我们将学习javamail。

第二部分:关于javamail

文档的使用

下载的javamail api中带的文档是很有用的。你可以在javamail下的/docs/javadocs/index.html找到它。第二部分主要将分析邮件程序的组件。你可以通过阅读文档来获得更多这方面的信息。

组件发送邮件需要使用javamail,它使对邮件的操作变得简单易用。

属性对象

javamail需要创建一个格式为"mail.smtp.host"的文件用来发送信息。

properties props = new properties ();

props.put("mail.smtp.host", "smtp.jspinsider.com"); 对话对象

所有的基于javamail的程序都至少需要一个或全部的对话目标。

session sendmailsession;

sendmailsession = session.getinstance(props, null);

传输

邮件的传输只有送出或受到两种状态。javamail将这两种不同状态描述为传输和储存。传输将送出邮件,而储存将收取邮件。

transport transport;

transport = sendmailsession.gettransport("smtp");

使用javamail能为我们节约大量的时间。javamail能代替所有的smtp的工作。

注意:javamail并不能完全的支持所有的邮件发送收取工作。它目前仅支持imap、smtp和pop3,除此以外你只有等待新的javamail版本或自己开发协议。

信息对象

信息对象将把你所发送的邮件真实的反映出来。

message newmessage = new mimemessage(sendmailsession);

这就是我们所需要的全部四个对象。下一步将是如何将对象加入到jsp中。

第三部分:javamail和jsp的结合

创建jsp

下面我们将开始将他们结合在一起。最重要的一点是要确认根据页面指示分类。还要记得在邮件上标注java.util.date。

<%@ page

import= " javax.mail.*, javax.mail.internet.*, javax.activation.*, java.util.*"

%>

其次,创建邮件发送的确认信息。确认信息可以是任意的,一般常用"你的邮件已经发送出去了(your mail has been sent)。"

信息是如何创建和发送的

我们在第二部分里已经讨论过信息对象的创建。我们下面将对信息进行操作。这就和设置信息对象的属性一样简单。你可以通过下面的程序来实现这项操作。

newmessage.setfrom(new internetaddress(request.getparameter("from")));

newmessage.setrecipient(message.recipienttype.to, new internetaddress(request.getparameter("to")));

newmessage.setsubject(request.getparameter("subject"));

newmessage.setsentdate(new date());

newmessage.settext(request.getparameter("text"));

现在将开始发送信息。通过javamail来实现它非常简单。

transport.send(newmessage);

将所有的组件结合在一起

现在所有的组件都已经齐全了。现在将它们都放在jsp里面。要注意每一个错误信息,并将它反馈给用户。代码如下,你可以通过复制它们直接使用:

sample jsp email utility using javamail

<%@ page

import=" javax.mail.*, javax.mail.internet.*, javax.activation.*,java.util.*"

%>

<html>

<head>

<title>jsp meets javamail, what a sweet combo.</title>

</head>

<body>

<%

try{

properties props = new properties();

session sendmailsession;

store store;

transport transport;

sendmailsession = session.getinstance(props, null);

props.put("mail.smtp.host", "smtp.jspinsider.com");

message newmessage = new mimemessage(sendmailsession);

newmessage.setfrom(new internetaddress(request.getparameter("from")));

newmessage.setrecipient(message.recipienttype.to, new internetaddress(request.getparameter("to")));

newmessage.setsubject(request.getparameter("subject"));

newmessage.setsentdate(new date());

newmessage.settext(request.getparameter("text"));

transport = sendmailsession.gettransport("smtp");

transport.send(newmessage);

%>

<p>your mail has been sent.</p>

<%

}

catch(messagingexception m)

{

out.println(m.tostring());

}

%>

</body>

</html>

你会很快体会到javamail的方便之处,jsp和javamail将是未来的希望。

文件/图片上传

package uploadfile;

import javax.servlet.servletinputstream;

import javax.servlet.http.httpservletrequest;

import java.io.fileoutputstream;

import java.io.*;

import java.util.hashtable;

import java.util.*;

public class fileuploadbean {

private string savepath=null; //文件上传保存的路径

private string contenttype=""; //内容类型

private string charencode=null; //字符编码

private string bounary=""; //分界线

private string filename=null; //本地文件名字

private hashtable dic=new hashtable(); //用于保存"元素名–元素值"对

private int totalsize=0; //上传文件总大小

private string path=""; //保存文件的路径

private string newfilename=""; //存入随机产生的文件名

///////////////////////////////////////////////////

//设置文件上传保存的路径

public void setsavepath(string s) {

s=path+s;

savepath=s;

system.out.println("上传路径:"+savepath);

}

///////////////////////////////////////////////////

//取文件上传保存的路径

public string getsavepath() {

return savepath;

}

////////////////////////////////////////////////////

//设置文件名字,也可以为它命名,暂时先用它原来的名字

public void setfilename(string s) {

int pos=s.indexof("\"; filename=\"");

if (pos>0) {

s=s.substring(pos+13,s.length()-3); //去 " 和 crlf

pos=s.lastindexof("\\");

if (pos<0)

pos=s.lastindexof("/");

if (pos<0)

filename=s;

filename=s.substring(pos+1);

}

}

////////////////////////////////////////////////////

//取得文件名

public string getfilename() {

system.out.println("得到文件名"+newfilename);

return newfilename;

}

///////////////////////////

//以时间为种子数产生新文件名

public string getnewfilename() {

int pos=0; //.的位置

long seed=0; //随机种子数

string ext=""; //存入文件扩展名

system.out.println("upload file name:"+filename);

pos=filename.lastindexof(".");

ext=filename.substring(pos); //得到扩展名

seed=new date().gettime();

random rand=new random(seed);//以时间为种子产生随机数作为文件名

newfilename=long.tostring(math.abs(rand.nextint()))+ext; //生成文件名

system.out.println("new file name:"+newfilename);

return newfilename;

}

//////////////////////////////////////////////////////

//设置字符的编码方式

public void setcharencode(httpservletrequest req) {

charencode=req.getcharacterencoding();

}

/////////////////////////////////////////////////

//设置得contenttype

public void setboundary(httpservletrequest req) {

//传递的参数值类似"multipart/form-data; boundary=—————————7d21441a30013c"

//传过来的分界线比实际显示在上传数据中的要多两个"–"

boundary=req.getcontenttype();

//system.out.println("boundary"+boundary);

int pos=boundary.indexof("boundary=");

//加上这两个"–"

boundary="–"+boundary.substring(pos+9);

}

////////////////////////////////////////////////////

//取得contenttype

public string getboundary(){

//返回值类似"—————————–7d21441a30013c"

return boundary;

}

/////////////////////////////////////////////

//设置contenttype

public void setcontenttype(string s) {

int pos =s.indexof(": ");

if (pos!=-1)

contenttype=s.substring(pos+2);

}

////////////////////////////////////////////

//取得contenttype

public string getcontenttype() {

return contenttype;

}

/////////////////////////////////////////////

//初始化

public void init(httpservletrequest req) {

setcharencode(req);

setboundary(req);

}

////////////////////////////////////////////////////

//取哈希表中的数据

public string getfieldvalue(string s) {

string temp="";

if(dic.containskey(s)) //判断表中是否存在s键,不判断则返回nullpointerexception

{

temp=(string)dic.get(s);

temp=temp.trim();

}else

temp="";

return temp;

}

////////////////////////////////////////////////

////用指定的编码方式生成字符串

public string newline(byte oneline[],int sp,int i,string charencode)

throws java.io.unsupportedencodingexception {

sp=0; // start position

string linestr=null;

if (charencode!=null) {

return linestr=new string(oneline,sp,i,charencode); //用指定的编码方式生成字符串

}

else {

return linestr=new string(oneline,sp,i);

}

}

///////////////////////////////////////////////

//得到上传文件的大小

public int gettotalsize() {

return totalsize/1000;

}

///////////////////////////////////////

//删除指定路径的文件

public boolean delfiles(string fn) //fn为要删除的文件名,不包括路径

{

try

{

file file=new file(savepath+fn);

system.out.println(savepath+fn);

if(file.exists())

{

file.delete();

system.out.println(file.getpath()+"delete file successfully!");

return true;

}else

{

system.out.println("the file is not existed!");

return true;

}

}catch(exception e)

{

system.out.println(e.tostring());

return false;

}

}

////////////////////////////////////////////////

//文件列表

public string[] listfiles(string fp)

{

string[] lf=null;

try{

savepath=path+fp;

file file=new file(savepath);

lf=file.list(new dirfilter());

for(int i=0;i<lf.length;i++)

system.out.println(lf[i]);

}catch(exception e){ e.printstacktrace();}

return lf;

}

/////////////////////////////////////////////////

//开始上传文件

public boolean doupload(httpservletrequest req)

throws java.io.ioexception {

string fieldvalue=""; //表单元素值

string fieldname=""; //表单元名称

int pos=-1; //临时变量,用于记录位置

int pos2=-1; //临时变量,用于记录位置

string linestr=null; //用oneline[]生成的每行字符串

byte oneline[] =new byte[4096]; //用于每次读取的数据

fileoutputstream fos=null; //文件输出流

init(req); //初始化

servletinputstream sis=req.getinputstream();

int i=sis.readline(oneline,0,oneline.length); //返回实际读取的字符数,并把数据写到oneline中

while (i!=-1) {

linestr=newline(oneline,0,i,charencode); //生成字符串

if (linestr.indexof(getboundary()+"–")>=0)

break;

if (linestr.startswith("content-disposition: form-data; name=\"")) {

//分离数据,因为表单元素也一并上传,还有其它数据,对我们有用的只是

//文件的内容,表单元素及表单元素对应的值

if (linestr.indexof("\"; filename=\"")>=0) { //是文件输入域

//设置文件名

setfilename(linestr);

if (!filename.equals("")) { //如果文件名为空则跳过

//提取表单元素名称及表单元素对应的值

pos=linestr.indexof("name=\"");

pos2=linestr.indexof("\"; filename=\"");

//表单元素名字

fieldname=linestr.substring(pos+6,pos2);

//表单元素值

fieldvalue=linestr.substring(pos2+13,linestr.length()-3);

//加入哈希表中

dic.put(fieldname,fieldvalue);

sis.readline(oneline,0,oneline.length); //读取的数据类似"content-type: text/plain"

sis.readline(oneline,0,oneline.length); //空行

//建立文件输出

fos=new fileoutputstream(new file(getsavepath(),getnewfilename()));

//开始读上传文件数据

i=sis.readline(oneline,0,oneline.length);

while(i!=-1) {

totalsize=i+totalsize;

linestr=newline(oneline,0,i,charencode);

if (linestr.indexof(getboundary())>=0)

break; //表明这个文件区的数据读取完毕

fos.write(oneline,0,i);

i=sis.readline(oneline,0,oneline.length);

}//end while

fos.close();

}//end if (!getfilename().equals(""))

}

else { //非文件输入域

pos=linestr.indexof("name=\"");

//表单元素名字

fieldname=linestr.substring(pos+6,linestr.length()-3);

//读空行

sis.readline(oneline,0,oneline.length);

//这行含有元素值,如里元素值为空,则这行也是空行,也要读的

string temp="";

i=sis.readline(oneline,0,oneline.length);

while(i!=-1)

{

temp=newline(oneline,0,i,charencode);

if (temp.indexof(getboundary())>=0)

break;

fieldvalue=fieldvalue+temp;

i=sis.readline(oneline,0,oneline.length);

}

//加入哈希表中

dic.put(fieldname,fieldvalue);

fieldvalue="";

}

}

i=sis.readline(oneline,0,oneline.length);

}//end while

sis.close();

return true;

} //end doupload

//////////////////////////

//清空hashtable

public void cleardic() {

dic.clear();

if (dic.isempty()) {

system.out.println("empty");

}

else {

sstem.out.println("not empty");

}

}

//////////////////////////////////

//测试用的主函数

public static void main(string args[])

{

string[] filelist=null;

try{

fileuploadbean fub=new fileuploadbean();

filelist=fub.listfiles("/avatars/");

for(int i=0;i<filelist.length;i++)

system.out.println(filelist[i]);

}catch(exception e){ e.printstacktrace();}

}

}

///////////////////////////////////

////文件目录过滤内部类

class dirfilter implements filenamefilter {

public boolean accept(file dir, string name) { //dir为目录名,name 为包含路径的文件名

file f = new file(dir,name); //生成文件对象

if(f.isdirectory())

return false;

return true;

}

}

相关类说明篇

㈠ file类

  这个类包装了一个上传文件的所有信息。通过它,可以得到上传文件的文件名、文件大小、扩展名、文件数据等信息。

  file类主要提供以下方法:

1、saveas作用:将文件换名另存。

原型:

public void saveas(java.lang.string destfilepathname)

public void saveas(java.lang.string destfilepathname, int optionsaveas)

其中,destfilepathname是另存的文件名,optionsaveas是另存的选项,该选项有三个值,分别是saveas_physical,saveas_virtual,saveas_auto。saveas_physical表明以操作系统的根目录为文件根目录另存文件,saveas_virtual表明以web应用程序的根目录为文件根目录另存文件,saveas_auto则表示让组件决定,当web应用程序的根目录存在另存文件的目录时,它会选择saveas_virtual,否则会选择saveas_physical。

例如,saveas("/upload/sample.zip",saveas_physical)执行后若web服务器安装在c盘,则另存的文件名实际是c:\upload\sample.zip。而saveas("/upload/sample.zip",saveas_virtual)执行后若web应用程序的根目录是webapps/jspsmartupload,则另存的文件名实际是webapps/jspsmartupload/upload/sample.zip。saveas("/upload/sample.zip",saveas_auto)执行时若web应用程序根目录下存在upload目录,则其效果同saveas("/upload/sample.zip",saveas_virtual),否则同saveas("/upload/sample.zip",saveas_physical)。

建议:对于web程序的开发来说,最好使用saveas_virtual,以便移植。

2、ismissing

作用:这个方法用于判断用户是否选择了文件,也即对应的表单项是否有值。选择了文件时,它返回false。未选文件时,它返回true。

原型:public boolean ismissing()

3、getfieldname

作用:取html表单中对应于此上传文件的表单项的名字。

原型:public string getfieldname()

4、getfilename

作用:取文件名(不含目录信息)

原型:public string getfilename()

5、getfilepathname

作用:取文件全名(带目录)

原型:public string getfilepathname

6、getfileext

作用:取文件扩展名(后缀)

原型:public string getfileext()

7、getsize

作用:取文件长度(以字节计)

原型:public int getsize()

8、getbinarydata

作用:取文件数据中指定位移处的一个字节,用于检测文件等处理。

原型:public byte getbinarydata(int index)。其中,index表示位移,其值在0到getsize()-1之间。

㈡ files类

  这个类表示所有上传文件的集合,通过它可以得到上传文件的数目、大小等信息。有以下方法:

1、getcount

作用:取得上传文件的数目。

原型:public int getcount()

2、getfile

作用:取得指定位移处的文件对象file(这是com.jspsmart.upload.file,不是java.io.file,注意区分)。

原型:public file getfile(int index)。其中,index为指定位移,其值在0到getcount()-1之间。

3、getsize

作用:取得上传文件的总长度,可用于限制一次性上传的数据量大小。

原型:public long getsize()

4、getcollection

作用:将所有上传文件对象以collection的形式返回,以便其它应用程序引用,浏览上传文件信息。

原型:public collection getcollection()

5、getenumeration

作用:将所有上传文件对象以enumeration(枚举)的形式返回,以便其它应用程序浏览上传文件信息。

原型:public enumeration getenumeration()

㈢ request类

  这个类的功能等同于jsp内置的对象request。只所以提供这个类,是因为对于文件上传表单,通过request对象无法获得表单项的值,必须通过jspsmartupload组件提供的request对象来获取。该类提供如下方法:

1、getparameter

作用:获取指定参数之值。当参数不存在时,返回值为null。

原型:public string getparameter(string name)。其中,name为参数的名字。

2、getparametervalues

作用:当一个参数可以有多个值时,用此方法来取其值。它返回的是一个字符串数组。当参数不存在时,返回值为null。

原型:public string[] getparametervalues(string name)。其中,name为参数的名字。

3、getparameternames

作用:取得request对象中所有参数的名字,用于遍历所有参数。它返回的是一个枚举型的对象。

原型:public enumeration getparameternames()

㈣ smartupload类这个类完成上传下载工作。

a.上传与下载共用的方法:

只有一个:initialize。

作用:执行上传下载的初始化工作,必须第一个执行。

原型:有多个,主要使用下面这个:

public final void initialize(javax.servlet.jsp.pagecontext pagecontext)

其中,pagecontext为jsp页面内置对象(页面上下文)。

b.上传文件使用的方法:

1、upload

作用:上传文件数据。对于上传操作,第一步执行initialize方法,第二步就要执行这个方法。

原型:public void upload()

2、save

作用:将全部上传文件保存到指定目录下,并返回保存的文件个数。

原型:public int save(string destpathname)

和public int save(string destpathname,int option)

其中,destpathname为文件保存目录,option为保存选项,它有三个值,分别是save_physical,save_virtual和save_auto。(同file类的saveas方法的选项之值类似)save_physical指示组件将文件保存到以操作系统根目录为文件根目录的目录下,save_virtual指示组件将文件保存到以web应用程序根目录为文件根目录的目录下,而save_auto则表示由组件自动选择。

注:save(destpathname)作用等同于save(destpathname,save_auto)。

3、getsize

作用:取上传文件数据的总长度

原型:public int getsize()

4、getfiles

作用:取全部上传文件,以files对象形式返回,可以利用files类的操作方法来获得上传文件的数目等信息。

原型:public files getfiles()

5、getrequest

作用:取得request对象,以便由此对象获得上传表单参数之值。

原型:public request getrequest()

6、setallowedfileslist

作用:设定允许上传带有指定扩展名的文件,当上传过程中有文件名不允许时,组件将抛出异常。

原型:public void setallowedfileslist(string allowedfileslist)

其中,allowedfileslist为允许上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想允许上传那些没有扩展名的文件,可以用两个逗号表示。例如:setallowedfileslist("doc,txt,,")将允许上传带doc和txt扩展名的文件以及没有扩展名的文件。

7、setdeniedfileslist

作用:用于限制上传那些带有指定扩展名的文件。若有文件扩展名被限制,则上传时组件将抛出异常。

原型:public void setdeniedfileslist(string deniedfileslist)

其中,deniedfileslist为禁止上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想禁止上传那些没有扩展名的文件,可以用两个逗号来表示。例如:setdeniedfileslist("exe,bat,,")将禁止上传带exe和bat扩展名的文件以及没有扩展名的文件。

8、setmaxfilesize

作用:设定每个文件允许上传的最大长度。

原型:public void setmaxfilesize(long maxfilesize)

其中,maxfilesize为为每个文件允许上传的最大长度,当文件超出此长度时,将不被上传。

9、settotalmaxfilesize

作用:设定允许上传的文件的总长度,用于限制一次性上传的数据量大小。

原型:public void settotalmaxfilesize(long totalmaxfilesize)

其中,totalmaxfilesize为允许上传的文件的总长度。

jsp 上传图片并生成缩位图或者加水印

有些网站  动网, 上传图片后加给加上自己的字(是在图片上加的)

 请问在jsp里如何实现??

//添加水印,filepath 源图片路径, watermark 水印图片路径

public static boolean createmark(string filepath,string watermark) {

imageicon imgicon=new imageicon(filepath);

image theimg =imgicon.getimage();

imageicon watericon=new imageicon(watermark);

image waterimg =watericon.getimage();

int width=theimg.getwidth(null);

int height= theimg.getheight(null);

bufferedimage bimage = new bufferedimage(width,height, bufferedimage.type_int_rgb);

graphics2d g=bimage.creatgraphics( );

g.setcolor(color.red);

g.setbackground(color.white);

g.drawimage(theimg, 0, 0, null );

g.drawimage(waterimg, 100, 100, null );

g.drawstring("12233",10,10); //添加文字

g.dispose();

try{

fileoutputstream out=new fileoutputstream(filepath);

jpegimageencoder encoder =jpegcodec.createjpegencoder(out);

jpegencodeparam param = encoder.getdefaultjpegencodeparam(bimage);

param.setquality(50f, true);

encoder.encode(bimage, param);

out.close();

}catch(exception e){ return false; }

return true;

}

/////////////////范例////////////////////

package package;

import java.io.*;

import javax.servlet.servletexception;

import javax.servlet.servletinputstream;

import javax.servlet.http.httpservletrequest;

public class upload

{

private static string newline = "\n";

private string uploaddirectory;

private string contenttype;

private string characterencoding;

public upload()

{

uploaddirectory = ".";

contenttype = "";

characterencoding = "";

}

private string getfilename(string s)

{

int i = s.lastindexof("\\");

if(i < 0 || i >= s.length() – 1)

{

i = s.lastindexof("/");

if(i < 0 || i >= s.length() – 1)

return s;

}

return s.substring(i + 1);

}

public void setuploaddirectory(string s)

{

uploaddirectory = s;

}

public void setcontenttype(string s)

{

contenttype = s;

int i;

if((i = contenttype.indexof("boundary=")) != -1)

{

contenttype = contenttype.substring(i + 9);

contenttype = "–" + contenttype;

}

}

public void setcharacterencoding(string s)

{

characterencoding = s;

}

public string uploadfile(httpservletrequest httpservletrequest)

throws servletexception, ioexception

{

string s = null;

setcharacterencoding(httpservletrequest.getcharacterencoding());

setcontenttype(httpservletrequest.getcontenttype());

s = uploadfile(httpservletrequest.getinputstream());

return s;

}

public string uploadfile(servletinputstream servletinputstream)

throws servletexception, ioexception

{

string s = null;

string s1 = null;

byte abyte0[] = new byte[4096];

byte abyte1[] = new byte[4096];

int ai[] = new int[1];

int ai1[] = new int[1];

string s2;

while((s2 = readline(abyte0, ai, servletinputstream, characterencoding)) != null)

{

int i = s2.indexof("filename=");

if(i >= 0)

{

s2 = s2.substring(i + 10);

if((i = s2.indexof("\"")) > 0)

s2 = s2.substring(0, i);

break;

}

}

s1 = s2;

if(s1 != null && !s1.equals("\""))

{

s1 = getfilename(s1);

string s3 = readline(abyte0, ai, servletinputstream, characterencoding);

if(s3.indexof("content-type") >= 0)

readline(abyte0, ai, servletinputstream, characterencoding);

file file = new file(uploaddirectory, s1);

fileoutputstream fileoutputstream = new fileoutputstream(file);

while((s3 = readline(abyte0, ai, servletinputstream, characterencoding)) != null)

{

if(s3.indexof(contenttype) == 0 && abyte0[0] == 45)

break;

if(s != null)

{

fileoutputstream.write(abyte1, 0, ai1[0]);

fileoutputstream.flush();

}

s = readline(abyte1, ai1, servletinputstream, characterencoding);

if(s == null || s.indexof(contenttype) == 0 && abyte1[0] == 45)

break;

fileoutputstream.write(abyte0, 0, ai[0]);

fileoutputstream.flush();

}

byte byte0;

if(newline.length() == 1)

byte0 = 2;

else

byte0 = 1;

if(s != null && abyte1[0] != 45 && ai1[0] > newline.length() * byte0)

fileoutputstream.write(abyte1, 0, ai1[0] – newline.length() * byte0);

if(s3 != null && abyte0[0] != 45 && ai[0] > newline.length() * byte0)

fileoutputstream.write(abyte0, 0, ai[0] – newline.length() * byte0);

fileoutputstream.close();

}

return s1;

}

private string readline(byte abyte0[], int ai[], servletinputstream servletinputstream, string s)

{

ai[0] = servletinputstream.readline(abyte0, 0, abyte0.length);

if(ai[0] == -1)

return null;

break missing_block_label_27;

object obj;

obj;

return null;

if(s == null)

return new string(abyte0, 0, ai[0]);

return new string(abyte0, 0, ai[0], s);

obj;

return null;

}

}

jsp页:

<%@page contenttype="text/html;charset=gb2312" import="package.upload"%>

<%

string dir = "c:\dir\upload";

string fn="";

upload upload = new upload();

upload.setuploaddirectory(dir);

fn=upload.uploadfile(request);

%>

随机图片名称

<%

mysmartupload.initialize(pagecontext);

mysmartupload.service(request,response);

mysmartupload.upload();

string fn=mysmartupload.getfiles().getfile(0).getfilename();

mysmartupload.save("upload/"); //文件保存的目录为upload

out.println("已经成功上传了文件,请查看<a href=upload/"+fn+">这里</a>");

%>

上面的程序可以上传图片,不过只能上传gif或者jpg图片。

而且保存图片在upload文件夹下面,要想gif或jpg图片的名称变为年+月+日+随机数.gif或年+月+日+随机数.jpg

只允许上传jpg或gif图片,在客户端用javascript控制要好些。

变图片名称可用如下代码:自己看看就明白了。:

//得到实际路径

string realpath = this.masrequest.getrequest().getrealpath("/");

string userphotopath = realpath + "images\\userphoto\\";

userphotopath = masstring.replace(userphotopath,"\\","\\\\");

if (!file.getfilename().trim().equals(""))

{

//根据系统时间生成文件名

date nowtime = new date();

emp_photo = userphotopath + string.valueof(nowtime.gettime()) +"."+ file.getfileext();

file.saveas(emp_photo);

system.out.println("file.saveas() = " + "ok!!!");

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 初学jsp心得-JSP教程,Jsp/Servlet
分享到: 更多 (0)

相关推荐

  • 暂无文章