文章导航PC6首页软件下载单机游戏安卓资源苹果资源

pc软件新闻网络操作系统办公工具编程服务器软件评测

安卓新闻资讯应用教程刷机教程安卓游戏攻略tv资讯深度阅读综合安卓评测

苹果ios资讯苹果手机越狱备份教程美化教程ios软件教程mac教程

单机游戏角色扮演即时战略动作射击棋牌游戏体育竞技模拟经营其它游戏游戏工具

网游cf活动dnf活动lol周免英雄lol礼包

手游最新动态手游评测手游活动新游预告手游问答

您的位置:首页网页设计JSP技巧 → jsp技巧大全

jsp技巧大全

时间:2011/5/16 14:45:55来源:飓风整理作者:痴苶(nié)呆傻我要评论(0)

jsp html编辑器
授权:免费软件 大小:38KB 语言: 简体中文

测 试环境为 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/html;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(" can't 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 boundary=""; //分界线
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 {
System.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.createGraphics( );
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!!!");
}

相关视频

    没有数据

相关阅读 召唤与合成怎么玩 召唤与合成新手攻略大全h1z1枪法怎么练 h1z1枪法技巧h1z1怎么开车 h1z1车辆获得方法及驾驶技巧龙之谷手游BossRush怎么过 BossRush通关技巧不思议迷宫命运石柱有什么奖励 不思议迷宫命运石柱奖励大全狙击精英4武器大全 狙击精英4全枪械武器及物品介绍命运冠位指定抽卡技巧有哪些 稀有英灵玄学抽卡方法教学狙击精英4怎么暗杀 狙击精英4暗杀技巧一览

文章评论
发表评论

热门文章 没有查询到任何记录。

最新文章 没有查询到任何记录。 java排序集锦源码Spring技术内幕jsp运行时我们常遇到的几个问题?NteBeans下JSP连接MySQL示例

人气排行 Java语言中内存泄漏及如何检测问题详解JSP中errorPage设置方法在JSP页面中实现检索数据的分页显示JAVA实现屏幕抓图 远程桌面控制用JSP下载word文件(不会直接用IE打开)如何直接在浏览器内运行SQL命令无边框窗口代码详解Spring技术内幕