iLeichun

当前位置:首页Jsp

jsp中各种url的获取方法

分类:Jsp  来源:网络  时间:2017-12-15 22:52:52

1、获取项目名称,如:myproject

String path = request.getContextPath();


2、获取项目根目录地址,如:http://localhost:8080/myproject/

String basePath = request.getScheme()+"://"+request.getServerName()

+":"+request.getServerPort()+path+"/";


3、获取当前访问的文件所在目录,如http://localhost:8080/myproject/book/

String nowPath = basePath + 

request.getServletPath().substring(0,request.getServletPath().lastIndexOf("/")+1);


4、获取当前访问文件,如http://localhost:8080/myproject/book/book.jsp

String nowPath = basePath + request.getServletPath();


JSP网页源码中空行的去除方法

分类:Jsp  来源:网络  时间:2012-4-20 19:07:39

在jsp使用了很多的Tag,虽然使用方便,页面也很整洁,但是所带来的问题也很令人头疼。例如,编译后输出的页面源码中会有很多的空白和空行,看上去既不美观,又占带宽,同时也不利于seo。

JSP2.1其实提供了一个很有用的命令,简单实用,Tomcat要6.0以上的版本支持:

<%@ page trimDirectiveWhitespaces="true" %>

 

或者

//顶部 接着代码处

<%out.clear();%>

//继续下面的代码

这种方法是把前面的输出全部清除,但是这种方法会把它自己本身留下一个空行,所以不能完全清除。

JSP报错:Attribute value request.getAttribute(

分类:Jsp  来源:网络  时间:2012-3-23 22:46:59

错误提示:
org.apache.jasper.JasperException: /index1.jsp (line: 14, column: 38) Attribute value Request.getParameter("username") is quoted with " which must be escaped when used within the value
        org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
        org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:408)
        org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:89)
        org.apache.jasper.compiler.Parser.parseAttributeValue(Parser.java:280)
        org.apache.jasper.compiler.Parser.parseAttribute(Parser.java:229)
        org.apache.jasper.compiler.Parser.parseAttributes(Parser.java:162)
        org.apache.jasper.compiler.Parser.parseAttributes(Parser.java:153)
        org.apache.jasper.compiler.Parser.parseParam(Parser.java:827)
        org.apache.jasper.compiler.Parser.parseBody(Parser.java:1672)
        org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1002)
        org.apache.jasper.compiler.Parser.parseInclude(Parser.java:854)
        org.apache.jasper.compiler.Parser.parseStandardAction(Parser.java:1116)
        org.apache.jasper.compiler.Parser.parseElements(Parser.java:1451)
        org.apache.jasper.compiler.Parser.parse(Parser.java:138)
        org.apache.jasper.compiler.ParserController.doParse(ParserController.java:242)
        org.apache.jasper.compiler.ParserController.parse(ParserController.java:102)
        org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
        org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
        org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
        org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
        org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
        org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
        org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
        org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

代码如下:
<jsp:include page="login.jsp" flush="true">
        <jsp:param name="username" value="<%=Request.getParameter("username")%>" />
        <jsp:param name="password" value="<%=Request.getParameter("password")%>" />
</jsp:include>
 

具体原由有可能是tomcat的版本不同导致的。jsp在编译jsp页面时,将 <%=request.getParameter("username")%>作为变量进行处理。因此,遇到里面的"会报错。”

 

解决以上问题有两种解决方案:

方案一
这么改写: 
<%=request.getParameter("username")%>

方案二
归根结底是tomcat版本的问题,更换tomcat版本吧。

JSP自动生成静态页面类

分类:Jsp  来源:网络  时间:2011-4-3 23:48:27

public class JspToHtml {
 
 private static String title = "标题1";
 private static String context = "标题2";
 private static String editer = "标题3";
 
 public static boolean jspToHtmlFile(String filePath,String htmlFile){
  
  String str = "";
  try {
   FileInputStream is = new FileInputStream(filePath);
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   String tempStr = "";
   while((tempStr = br.readLine()) != null){
    str = str + tempStr;
   }
   
   br.close();
   is.close();
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }
  
  try {
   str = str.replaceAll("##title##", title);
   str = str.replaceAll("##context##", context);
   str = str.replaceAll("##editer##", editer);
   System.out.println(str);
   File file = new File(htmlFile);
   BufferedWriter writer = new BufferedWriter(new FileWriter(file));
   writer.write(str);
   writer.close();   
   
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }
  
  return true;
  
 }
 
 public static void main(String[] args) {
  String url = "D:\Workspaces\base.html";
  String savePath = "d:\" + 11 + ".html";
  
  jspToHtmlFile(url, savePath);
 }

}

JspToHtml可以做为一个工作类使用,动态生成静态页面一般会用在新闻发布系统,网站中的新闻、公告等。之所以以静态页面的方式显示,是为了对搜索引擎更友好并提高页面访问速度。

JSP中用Session实现在线用户统计

分类:Jsp  来源:网络  时间:2011-2-24 14:33:47

作为一个程序员,你可以不介意具体在客户端是如何实现,就方便的实现简单的基于session的用户管理。现在对于处理在线用户,有几种不同的处理方法。

 

一种是页面刷新由用户控制,服务器端控制一个超时时间比如30分钟,到了时间之后用户没有动作就被踢出。这种方法的优点是,如果用户忘了退出,可以防止别人恶意操作。缺点是,如果你在做一件很耗时间的事情,超过了这个时间限制,submit的时候可能要再次面临登陆。如果原来的叶面又是强制失效的话,就有可能丢失你做的工作。在实现的角度来看,这是最简单的,Server端默认实现的就是这样的模式。

 

另一种方式是,站点采用框架结构,有一个Frame或者隐藏的iframe在不断刷新,这样你永远不会被踢出,但是服务器端为了判断你是否在线,需要定一个发呆时间,如果超过这个发呆时间你除了这个自动刷新的页面外没有刷新其他页面的话,就认为你已经不在线了。采取这种方式的典型是xici.net。 他的优点是可以可以利用不断的刷新实现一些类似server-push的功能,比如网友之间发送消息。

 

不管哪一种模式,为了实现浏览当前所有的在线用户,还需要做一些额外的工作。Servlet API中没有得到Session列表的API。

 

可以利用的是Listener. Servlet 2.2和2.3规范在这里略微有一些不一样。2.2中HttpSessionBindingListener可以实现当一个HTTPSession中的Attribute变化的时候通知你的类。而2.3中还引入了HttpSessionAttributeListener.鉴于我使用的环境是Visual age for Java 4和JRun server 3.1,他们还不直接支持Servlet 2.3的编程,这里我用的是HttpSessionBindingListener.

 

需要做的事情包括做一个新的类来实现HttpSessionBindingListener接口。这个接口有两个方法:

 

public void valueBound(HttpSessionBindingEvent event)

public void valueUnbound(HttpSessionBindingEvent event)

 

当你执行Session.addAttribute(String,Object)的时候,如果你已经把一个实现了HttpSessionBindingListener接口的类加入为Attribute,Session会通知你的类,调用你的valueBound方法。相反,Session.removeAttribute方法对应的是valueUndound方法。

 

public class HttpSessionBinding implements javax.servlet.http.HttpSessionBindingListener

{

 ServletContext application = null;

 

 public HttpSessionBinding(ServletContext application)

 {

super();

if (application ==null)

 throw new IllegalArgumentException("Null application is not accept.");

this.application = application;

 }

 

 public void valueBound(javax.servlet.http.HttpSessionBindingEvent e)

 {

Vector activeSessions = (Vector) application.getAttribute("activeSessions");

if (activeSessions == null)

{

 activeSessions = new Vector();

}

 

JDBCUser sessionUser = (JDBCUser)e.getSession().getAttribute("user");

if (sessionUser != null)

{

 activeSessions.add(e.getSession());

}

application.setAttribute("activeSessions",activeSessions);

 }

 

 public void valueUnbound(javax.servlet.http.HttpSessionBindingEvent e)

 {

JDBCUser sessionUser = (JDBCUser)e.getSession().getAttribute("user");

if (sessionUser == null)

{

 Vector activeSessions = (Vector) application.getAttribute("activeSessions");

 if (activeSessions != null)

 {

activeSessions.remove(e.getSession().getId());

application.setAttribute("activeSessions",activeSessions);

 }

}

 }

}

 

假设其中的JDBCUser类是一个任意User类。在执行用户登录时,把User类和HttpSessionBinding类都加入到Session中去。

 

这样,每次用户登录后,在application中的attribute "activeSessions"这个vector中都会增加一条记录。每当session超时,valueUnbound被触发,在这个vector中删去将要被超时的session.

 

public void login()

throws ACLException,SQLException,IOException

{

 /* get JDBC User Class */

 if (user != null)

 {

logout();

 }

 {

// if session time out, or user didn¹t login, save the target url temporary.

 

JDBCUserFactory uf = new JDBCUserFactory();

 

if ( (this.request.getParameter("userID")==null) || (this.request.getParameter("password")==null) )

{

 throw new ACLException("Please input a valid userName and password.");

}

 

JDBCUser user = (JDBCUser) uf.UserLogin(

 this.request.getParameter("userID"),

 this.request.getParameter("password") );

 user.touchLoginTime();

 this.session.setAttribute("user",user);

 this.session.setAttribute("BindingNotify",new HttpSessionBinding(application));

}

 }

 

Login的时候,把User和这个BindingNotofy目的的类都加入到session中去。logout的时候,就要主动在activeSessions这个vector中删去这个session.

 

public void logout()

throws SQLException,ACLException

{

 if (this.user == null && this.session.getAttribute("user")==null)

 {

return;

 }

 

 Vector activeSessions = (Vector) this.application.getAttribute("activeSessions");

 if (activeSessions != null)

 {

activeSessions.remove(this.session);

application.setAttribute("activeSessions",activeSessions);

 }

 

 java.util.Enumeration e = this.session.getAttributeNames();

 

 while (e.hasMoreElements())

 {

String s = (String)e.nextElement();

this.session.removeAttribute(s);

 }

 this.user.touchLogoutTime();

 this.user = null;

}

 

这两个函数位于一个HttpSessionManager类中.这个类引用了jsp里面的application全局对象。这个类的其他代码和本文无关且相当长,我就不贴出来了。

下面来看看JSP里面怎么用。

 

假设一个登录用的表单被提交到doLogin.jsp, 表单中包含UserName和password域。节选部分片段:

 

<%

HttpSessionManager hsm = new HttpSessionManager(application,request,response);

try

{

 hsm.login();

}

catch ( UserNotFoundException e)

{

 response.sendRedirect("InsufficientPrivilege.jsp?detail=User%20does%20not%20exist.");

 return;

}

catch ( InvalidPasswordException e2)

{

 response.sendRedirect("InsufficientPrivilege.jsp?detail=Invalid%20Password");

 return;

}

catch ( Exception e3)

{

 %> Error:<%=e3.toString() %><br>

 Press <a href="login.jsp">Here</a> to relogin.

 <% return;

}

response.sendRedirect("index.jsp");

%>

 

再来看看现在我们怎么得到一个当前在线的用户列表。

 

<body bgcolor="#FFFFFF">

<table cellspacing="0" cellpadding="0" width="100%">

 

<tr >

<td style="width:24px">SessionId

</td>

<td style="width:80px" >User

</td>

<td style="width:80px" >Login Time

</td>

<td style="width:80px" >Last Access Time

</td>

</tr>

<%

Vector activeSessions = (Vector) application.getAttribute("activeSessions");

if (activeSessions == null)

{

 activeSessions = new Vector();

 application.setAttribute("activeSessions",activeSessions);

}

 

Iterator it = activeSessions.iterator();

while (it.hasNext())

{

 HttpSession sess = (HttpSession)it.next();

 JDBCUser sessionUser = (JDBCUser)sess.getAttribute("user");

 String userId = (sessionUser!=null)?sessionUser.getUserID():"None";

%>

<tr>

<td nowrap=¹¹><%= sess.getId() %></td>

<td nowrap=¹¹><%= userId %></td>

<td nowrap=¹¹>

<%= BeaconDate.getInstance( new Java.util.Date(sess.getCreationTime())).getDateTimeString()%></td>

<td class="<%= stl %>3" nowrap=¹¹>

<%= BeaconDate.getInstance( new java.util.Date(sess.getLastAccessedTime())).getDateTimeString()%></td>

</tr>

<%

}

%>

</table>

</body>

 

以上的代码从application中取出activeSessions,并且显示出具体的时间。其中BeaconDate类假设为格式化时间的类。

 

这样,我们得到了一个察看在线用户的列表的框架。至于在线用户列表分页等功能,与本文无关,不予讨论。

 

这是一个非刷新模型的例子,依赖于session的超时机制。我的同事sonymusic指出很多时候由于各个厂商思想的不同,这有可能是不可信赖的。考虑到这种需求,需要在每个叶面刷新的时候都判断当前用户距离上次使用的时间是否超过某一个预定时间值。这实质上就是自己实现session超时。如果需要实现刷新模型,就必须使用这种每个叶面进行刷新判断的方法。

Jsp中getAttribute和getParameter的区别

分类:Jsp  来源:网络  时间:2010-12-17 23:31:04

1.getAttribute是取得jsp中用setAttribute設定的attribute
2.parameter得到的是string;attribute得到的是object
3.request.getParameter()方法传递的数据,会从Web客户端传到Web服务器端,代表HTTP请求数据;request.setAttribute()和getAttribute()方法传递的数据只会存在于Web容器内部,在具有转发关系的Web组件之间共享。即request.getAttribute()方法返回request范围内存在的对象,而request.getParameter()方法是获取http提交过来的数据。
——getParameter得到的都是String类型的。或者是http://a.jsp?id=123中的123,或者是某个表单提交过去的数据。
——getAttribute则可以是对象。
——getParameter()是获取POST/GET传递的参数值;
——getAttribute()是获取对象容器中的数据值;
——getParameter:用于客户端重定向时,即点击了链接或提交按扭时传值用,即用于在用表单或url重定向传值时接收数据用。
——getAttribute:用于服务器端重定向时,即在sevlet中使用了forward函数,或struts中使用了mapping.findForward。getAttribute只能收到程序用setAttribute传过来的值。
——getParameter()是获取POST/GET传递的参数值;
——getAttribute()是获取SESSION的值;
另外,可以用setAttribute,getAttribute发送接收对象.而getParameter显然只能传字符串。
setAttribute 是应用服务器把这个对象放在该页面所对应的一块内存中去,当你的页面服务器重定向到另一个页面时,应用服务器会把这块内存拷贝另一个页面所对应的内存中。这样getAttribute就能取得你所设下的值,当然这种方法可以传对象。session也一样,只是对象在内存中的生命周期不一样而已。
getParameter只是应用服务器在分析你送上来的request页面的文本时,取得你设在表单或url重定向时的值。
getParameter   返回的是String,   用于读取提交的表单中的值;      
getAttribute   返回的是Object,需进行转换,可用setAttribute设置成任意对象,使用很灵活,可随时用。
 

jsp分页显示案例

分类:Jsp  来源:网络  时间:2010-12-17 23:23:34

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

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


< script language="javascript" >

function newwin(url) {

var


newwin=window.open(url,"newwin","toolbar=no,location=no,directories=no,status=no,


menubar=no,scrollbars=yes,resizable=yes,width=600,height=450");

newwin.focus();

return false;

}

< /script >

< script LANGUAGE="javascript" >

function submit10()

{

self.location.replace("fenye1.jsp")

}

< /script >

< %//变量声明

java.sql.Connection sqlCon; //数据库连接对象

java.sql.Statement sqlStmt; //SQL语句对象

java.sql.ResultSet sqlRst; //结果集对象

java.lang.String strCon; //数据库连接字符串

java.lang.String strSQL; //SQL语句

int intPageSize; //一页显示的记录数

int intRowCount; //记录总数

int intPageCount; //总页数

int intPage; //待显示页码

java.lang.String strPage;

int i;

//设置一页显示的记录数

intPageSize = 4;

//取得待显示页码

strPage = request.getParameter("page");

if(strPage==null){//表明在QueryString中没有page这一个参数,此时显示第一页数据

intPage = 1;

}

else{//将字符串转换成整型

intPage = java.lang.Integer.parseInt(strPage);

if(intPage< 1) intPage = 1;

}

//装载JDBC驱动程序

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//设置数据库连接字符串

strCon = "jdbc:odbc:heyang";

//连接数据库

sqlCon = java.sql.DriverManager.getConnection(strCon,"sa","");

//创建一个可以滚动的只读的SQL语句对象

sqlStmt =


sqlCon.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.Result


Set.CONCUR_READ_ONLY);//准备SQL语句

strSQL = "select user_id,user_name from userinfo order by user_id desc";

//执行SQL语句并获取结果集

sqlRst = sqlStmt.executeQuery(strSQL);

//获取记录总数

sqlRst.last();//??光标在最后一行

intRowCount = sqlRst.getRow();//获得当前行号

//记算总页数

intPageCount = (intRowCount+intPageSize-1) / intPageSize;

//调整待显示的页码

if(intPage >intPageCount) intPage = intPageCount;

% >

< html >

< head >

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

< title >会员管理< /title >

< /head >

< body >

< form method="POST" action="fenye1.jsp" >

第< %=intPage% >页 共< %=intPageCount% >页


< %if(intPage< intPageCount){% >< a


href="fenye1.jsp?page=< %=intPage+1% >" >下一页


< /a >< %}% > < %if(intPage >1){% >< a href="fenye1.jsp?page=< %=intPage-1% >" >


上一页< /a >< %}% >

转到第:< input type="text" size="8" > 页

< span >< input type=′submit′ value=′GO′ >< /span >

< /form >

< table border="1" cellspacing="0" cellpadding="0" >

< tr >

< th >ID< /th >

< th >用户名< /th >

< th width=′8%′ >删除< /th >

< /tr >

< %

if(intPageCount >0){

//将记录指针定位到待显示页的第一条记录上

sqlRst.absolute((intPage-1) * intPageSize + 1);

//显示数据

i = 0;

String user_id,user_name;

while(i< intPageSize && !sqlRst.isAfterLast()){

user_id=sqlRst.getString(1);

user_name=sqlRst.getString(2);

% >

< tr >

< td >< %=user_id% >< /td >

< td >< %=user_name% >< /td >

< td width=′8%′ align=′center′ >< a href="delete.jsp?user_id=< %=user_id% >"


onClick="return newwin(this.href);" >删除< /a >< /td >

< /tr >

< %

sqlRst.next();

i++;

}

}

% >

< /table >

 

< /body >

< /html >

< %

//关闭结果集

sqlRst.close();

//关闭SQL语句对象

sqlStmt.close();

//关闭数据库

sqlCon.close();

% >
 

jsp中commons-fileupload组件实现上传下载

分类:Jsp  来源:网络  时间:2010-11-20 14:54:35

本文以commons-fileupload组件为例,为jsp应用添加文件上传功能。
common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。用该组件可实现一次上传一个或多个文件,并可限制文件大小。
下载后解压zip包,将commons-fileupload-1.0.jar复制到tomcat的webapps你的webappWEB-INFlib下,目录不存在请自建目录。
新建一个servlet: Upload.java用于文件上传:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;

public class Upload extends HttpServlet {

private String uploadPath = “C:upload”; // 上传文件的目录
private String tempPath = “C:upload mp”; // 临时文件目录

public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
}
}
在doPost()方法中,当servlet收到浏览器发出的Post请求后,实现文件上传。以下是示例代码:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置最大文件尺寸,这里是4MB
fu.setSizeMax(4194304);
// 设置缓冲区大小,这里是4kb
fu.setSizeThreshold(4096);
// 设置临时目录:
fu.setRepositoryPath(tempPath);

// 得到所有的文件:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件:
while(i.hasNext()) {
FileItem fi = (FileItem)i.next();
// 获得文件名,这个文件名包括路径:
String fileName = fi.getName();
// 在这里可以记录用户和文件信息
// …
// 写入文件,暂定文件名为a.txt,可以从fileName中提取文件名:
fi.write(new File(uploadPath + “a.txt”));
}
}
catch(Exception e) {
// 可以跳转出错页面
}
}
如果要在配置文件中读取指定的上传文件夹,可以在init()方法中执行:
public void init() throws ServletException {
uploadPath = ….
tempPath = ….
// 文件夹不存在就自动创建:
if(!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs();
if(!new File(tempPath).isDirectory())
new File(tempPath).mkdirs();
}
编译该servlet,注意要指定classpath,确保包含commons-upload-1.0.jar和tomcatcommonlibservlet-api.jar。
配置servlet,用记事本打开tomcatwebapps你的webappWEB-INFweb.xml,没有的话新建一个。
典型配置如下:
<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
“http://java.sun.com/dtd/web-app_2_3.dtd”>

<web-app>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>Upload</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>
配置好servlet后,启动tomcat,写一个简单的html测试:
<form action=”fileupload” method=”post”
enctype=”multipart/form-data” >
<input type=”file” >
<input type=”submit” value=”upload”>
</form>
注意action=”fileupload”其中fileupload是配置servlet时指定的url-pattern。

文件的下载用servlet实现
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
String aFilePath = null;    //要下载的文件路径
String aFileName = null;    //要下载的文件名
FileInputStream in = null;  //输入流
ServletOutputStream out = null;  //输出流

try
{

aFilePath = getFilePath(request);
aFileName = getFileName(request);

response.setContentType(getContentType(aFileName) + “; charset=UTF-8″);
response.setHeader(”Content-disposition”, “attachment; filename=” + aFileName);

in = new  FileInputStream(aFilePath + aFileName); //读入文件
out = response.getOutputStream();
out.flush();
int aRead = 0;
while((aRead = in.read()) != -1 & in != null)
{
out.write(aRead);
}
out.flush();
}
catch(Throwable e)
{
log.error(”FileDownload doGet() IO error!”,e);
}
finally
{
try
{
in.close();
out.close();
}
catch(Throwable e)
{
log.error(”FileDownload doGet() IO close error!”,e);
}
}
}

 

下面是某个大虾的代码:

这个Upload比smartUpload好用多了.完全是我一个个byte调试出来的,不象smartUpload的bug具多.
调用方法:
Upload up = new Upload();
up.init(request);
/**
此处可以调用setSaveDir(String saveDir);设置保存路径
调用setMaxFileSize(long size)设置上传文件的最大字节.
调用setTagFileName(String)设置上传后文件的名字(只对第一个文件有效)
*/
up. uploadFile();

然后String[] names = up.getFileName();得到上传的文件名,文件绝对路径应该是
保存的目录saveDir+”/”+names[i];
可以通过up.getParameter(”field”);得到上传的文本或up.getParameterValues(”filed”)
得到同名字段如多个checkBox的值.
其它的自己试试.

源码:____________________________________________________________
package com.inmsg.beans;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Upload {
private String saveDir = “.”; //要保存文件的路径
private String contentType = “”; //文档类型
private String charset = “”; //字符集
private ArrayList tmpFileName = new ArrayList(); //临时存放文件名的数据结构
private Hashtable parameter = new Hashtable(); //存放参数名和值的数据结构
private ServletContext context; //程序上下文,用于初始化
private HttpServletRequest request; //用于传入请求对象的实例
private String boundary = “”; //内存数据的分隔符
private int len = 0; //每次从内在中实际读到的字节长度
private String queryString;
private int count; //上载的文件总数
private String[] fileName; //上载的文件名数组
private long maxFileSize = 1024 * 1024 * 10; //最大文件上载字节;
private String tagFileName = “”;

public final void init(HttpServletRequest request) throws ServletException {
this.request = request;
boundary = request.getContentType().substring(30); //得到内存中数据分界符
queryString = request.getQueryString();
}

public String getParameter(String s) { //用于得到指定字段的参数值,重写request.getParameter(String s)
if (parameter.isEmpty()) {
return null;
}
return (String) parameter.get(s);
}

public String[] getParameterValues(String s) { //用于得到指定同名字段的参数数组,重写request.getParameterValues(String s)
ArrayList al = new ArrayList();
if (parameter.isEmpty()) {
return null;
}
Enumeration e = parameter.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
if ( -1 != key.indexOf(s + “||||||||||”) || key.equals(s)) {
al.add(parameter.get(key));
}
}
if (al.size() == 0) {
return null;
}
String[] value = new String[al.size()];
for (int i = 0; i < value.length; i++) {
value[i] = (String) al.get(i);
}
return value;
}

public String getQueryString() {
return queryString;
}

public int getCount() {
return count;
}

public String[] getFileName() {
return fileName;
}

public void setMaxFileSize(long size) {
maxFileSize = size;
}

public void setTagFileName(String filename) {
tagFileName = filename;
}

public void setSaveDir(String saveDir) { //设置上载文件要保存的路径
this.saveDir = saveDir;
File testdir = new File(saveDir); //为了保证目录存在,如果没有则新建该目录
if (!testdir.exists()) {
testdir.mkdirs();
}
}

public void setCharset(String charset) { //设置字符集
this.charset = charset;
}

public boolean uploadFile() throws ServletException, IOException { //用户调用的上载方法
setCharset(request.getCharacterEncoding());
return uploadFile(request.getInputStream());
}

private boolean uploadFile(ServletInputStream servletinputstream) throws //取得央存数据的主方法
ServletException, IOException {
String line = null;
byte[] buffer = new byte[256];
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {
if (line.startsWith(”Content-Dis;”)) {
int i = line.indexOf(”filename=”);
if (i >= 0) { //如果一段分界符内的描述中有filename=,说明是文件的编码内容
String fName = getFileName(line);
if (fName.equals(”")) {
continue;
}
if (count == 0 && tagFileName.length() != 0) {
String ext = fName.substring( (fName.lastIndexOf(”.”) + 1));
fName = tagFileName + “.” + ext;
}
tmpFileName.add(fName);
count++;
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {
if (line.length() <= 2) {
break;
}
}
File f = new File(saveDir, fName);
FileOutputStream dos = new FileOutputStream(f);
long size = 0l;
while ( (line = readLine(buffer, servletinputstream, null)) != null) {
if (line.indexOf(boundary) != -1) {
break;
}
size += len;
if (size > maxFileSize) {
throw new IOException(”文件超过” + maxFileSize + “字节!”);
}
dos.write(buffer, 0, len);
}
dos.close();
}
else { //否则是字段编码的内容
String key = getKey(line);
String value = “”;
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {
if (line.length() <= 2) {
break;
}
}
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {

if (line.indexOf(boundary) != -1) {
break;
}
value += line;
}
put(key, value.trim(), parameter);
}
}
}
if (queryString != null) {
String[] each = split(queryString, “&”);
for (int k = 0; k < each.length; k++) {
String[] nv = split(each[k], “=”);
if (nv.length == 2) {
put(nv[0], nv[1], parameter);
}
}
}
fileName = new String[tmpFileName.size()];
for (int k = 0; k < fileName.length; k++) {
fileName[k] = (String) tmpFileName.get(k); //把ArrayList中临时文件名倒入数据中供用户调用
}
if (fileName.length == 0) {
return false; //如果fileName数据为空说明没有上载任何文件
}
return true;
}

private void put(String key, String value, Hashtable ht) {
if (!ht.containsKey(key)) {
ht.put(key, value);
}
else { //如果已经有了同名的KEY,就要把当前的key更名,同时要注意不能构成和KEY同名
try {
Thread.currentThread().sleep(1); //为了不在同一ms中产生两个相同的key
}
catch (Exception e) {}
key += “||||||||||” + System.currentTimeMillis();
ht.put(key, value);
}
}

/*
调用ServletInputstream.readLine(byte[] b,int offset,length)方法,该方法是从ServletInputstream流中读一行
到指定的byte数组,为了保证能够容纳一行,该byte[]b不应该小于256,重写的readLine中,调用了一个成员变量len为
实际读到的字节数(有的行不满256),则在文件内容写入时应该从byte数组中写入这个len长度的字节而不是整个byte[]
的长度,但重写的这个方法返回的是String以便分析实际内容,不能返回len,所以把len设为成员变量,在每次读操作时
把实际长度赋给它.
也就是说在处理到文件的内容时数据既要以String形式返回以便分析开始和结束标记,又要同时以byte[]的形式写到文件
输出流中.
*/
private String readLine(byte[] Linebyte,
ServletInputStream servletinputstream, String charset) {
try {
len = servletinputstream.readLine(Linebyte, 0, Linebyte.length);
if (len == -1) {
return null;
}
if (charset == null) {
return new String(Linebyte, 0, len);
}
else {
return new String(Linebyte, 0, len, charset);
}

}
catch (Exception _ex) {
return null;
}

}

private String getFileName(String line) { //从描述字符串中分离出文件名
if (line == null) {
return “”;
}
int i = line.indexOf(”filename=”);
line = line.substring(i + 9).trim();
i = line.lastIndexOf(”");
if (i < 0 || i >= line.length() – 1) {
i = line.lastIndexOf(”/”);
if (line.equals(”"”")) {
return “”;
}
if (i < 0 || i >= line.length() – 1) {
return line;
}
}
return line.substring(i + 1, line.length() – 1);
}

private String getKey(String line) { //从描述字符串中分离出字段名
if (line == null) {
return “”;
}
int i = line.indexOf(”>line = line.substring(i + 5).trim();
return line.substring(1, line.length() – 1);
}

public static String[] split(String strOb, String mark) {
if (strOb == null) {
return null;
}
StringTokenizer st = new StringTokenizer(strOb, mark);
ArrayList tmp = new ArrayList();
while (st.hasMoreTokens()) {
tmp.add(st.nextToken());
}
String[] strArr = new String[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
strArr[i] = (String) tmp.get(i);
}
return strArr;
}
}

下载其实非常简单,只要如下处理,就不会发生问题。

public void downLoad(String filePath,HttpServletResponse response,boolean isOnLine)
throws Exception{
File f = new File(filePath);
if(!f.exists()){
response.sendError(404,”File not found!”);
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;

response.reset(); //非常重要
if(isOnLine){ //在线打开方式
URL u = new URL(”file:///”+filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader(”Content-Disposition”, “inline; filename=”+f.getName());
//文件名应该编码成UTF-8
}
else{ //纯下载方式
response.setContentType(”application/x-msdownload”);
response.setHeader(”Content-Disposition”, “attachment; filename=” + f.getName());
}
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) >0)
out.write(buf,0,len);
br.close();
out.close();
}

jsp中FileUpload实现文件上传

分类:Jsp  来源:网络  时间:2010-11-20 14:52:50

要在servlet/jsp环境中实现文件上传功能非常容易,因为网上已经有许多用java开发的组件用于文件上传,本文以commons-fileupload组件为例,为servlet/jsp应用添加文件上传功能。

common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。该组件简单易用,可实现一次上传一个或多个文件,并可限制文件大小。

下载后解压zip包,将commons-fileupload-1.0.jar复制到tomcat的webapps你的webappWEB-INFlib下,如果目录不存在请自建目录。

新建一个servlet: Upload.java用于文件上传:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;

public class Upload extends HttpServlet {

private String uploadPath = “C:upload”; // 用于存放上传文件的目录
private String tempPath = “C:upload mp”; // 用于存放临时文件的目录

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
}
}

当servlet收到浏览器发出的Post请求后,在doPost()方法中实现文件上传。以下是示例代码:

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置最大文件尺寸,这里是4MB
fu.setSizeMax(4194304);
// 设置缓冲区大小,这里是4kb
fu.setSizeThreshold(4096);
// 设置临时目录:
fu.setRepositoryPath(tempPath);

// 得到所有的文件:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件:
while(i.hasNext()) {
FileItem fi = (FileItem)i.next();
// 获得文件名,这个文件名包括路径:
String fileName = fi.getName();
if(fileName!=null) {
// 在这里可以记录用户和文件信息
// …
// 写入文件a.txt,你也可以从fileName中提取文件名:
fi.write(new File(uploadPath + “a.txt”));
}
}
// 跳转到上传成功提示页面
}
catch(Exception e) {
// 可以跳转出错页面
}
}

如果要在配置文件中读取指定的上传文件夹,可以在init()方法中执行:

public void init() throws ServletException {
uploadPath = ….
tempPath = ….
// 文件夹不存在就自动创建:
if(!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs();
if(!new File(tempPath).isDirectory())
new File(tempPath).mkdirs();
}

编译该servlet,注意要指定classpath,确保包含commons-upload-1.0.jar和tomcatcommonlibservlet-api.jar。

配置servlet,用记事本打开tomcatwebapps你的webappWEB-INFweb.xml,没有的话新建一个。典型配置如下:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
“http://java.sun.com/dtd/web-app_2_3.dtd”>
<web-app>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>

配置好servlet后,启动tomcat,写一个简单的html测试:

<form action=”fileupload” method=”post” enctype=”multipart/form-data” name=”form1″>
<input type=”file” name=”file”>
<input type=”submit” name=”Submit” value=”upload”>
</form>

注意action=”fileupload”其中fileupload是配置servlet时指定的url-pattern。

jsp中文文件名无法显示的问题

分类:Jsp  来源:网络  时间:2010-11-20 14:51:27

现象:

http://pjzx.syty.edu.cn/UserFiles/Image/猫.jpg

浏览器中无法显示图象。

解决办法:

编辑TOMCAT配置文件server.xml,找到如下位置,加入红色部分内容,即可解决。

<Connector port=”8080″ protocol=”HTTP/1.1″
connectionTimeout=”20000″
redirectPort=”8443″ URIEncoding=”UTF-8″ useBodyEncodingForURI=”true”/>