??xml version="1.0" encoding="utf-8" standalone="yes"?>
<head><title>Simple jsp page</title></head>
<body>Place your content here
here is index jsp
get header info
<a href="a.jsp">a.jsp</a>
</body>
</html>
a.jsp面
<html>
<head><title>Simple jsp page</title></head>
<body>Place your content here
here is a. jsp
get header info
<%=request.getHeader("Referer")%>
<%if(null == request.getHeader("Referer") || request.getHeader("Referer").indexOf("yourdomain.com") < 0){%>
做h要厚?br />
<%}else{%>
合法讉K
<%}%>
</body>
</html>
]]>
if (IP != null && IP.length() != 0) {
while ((IP != null) && (IP.equals("unknow"))) {
IP = httpRequest.getHeader("x-forworded-for");
}
}
if (IP == null || IP.length() == 0) {
IP = httpRequest.getHeader("Proxy-Client-IP");
}
if (IP == null || IP.length() == 0) {
IP = httpRequest.getHeader("WL-Proxy-Client-IP");
}
if (IP == null || IP.length() == 0) {
IP = httpRequest.getRemoteAddr();
}
// 得到讉K者所在网D?br />
String subIP = IP.substring(0, IP.lastIndexOf("."));
System.out.println("真实的IP地址Q? + IP+"|段是:(x)"+subIP);
package com.yourcompany.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
public class Add_UpdateAction extends DispatchAction {
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
return mapping.findForward("addOk");
}
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
return mapping.findForward("updateOk");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans >
<form-bean name="add_UpdateForm" type="com.yourcompany.struts.form.Add_UpdateForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="add_UpdateForm"
input="/add.jsp"
name="add_UpdateForm"
parameter="methods"
path="/add_Update"
scope="request"
type="com.yourcompany.struts.action.Add_UpdateAction">
<forward name="addOk" path="/addOk.jsp" />
<forward name="updateOk" path="/updateOk.jsp" />
</action>
</action-mappings>
<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>
<% //讄面不缓?br />
response.setHeader("Pragma","No-cache");
response.setHeader("Cahce-Control","no-cache");
response.setDateHeader("Expires",0);
//在内存(sh)创徏囄
int width=60,height=20;
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//获取囑Ş上下?br />
Graphics g= image.getGraphics();
//生成随机c?br />
Random random= new Random();
//讄背景颜色
g.setColor(new Color(160,200,100));
g.fillRect(0,0,width,height);
//讄字体
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
//随机产生50条干扰线Q囑Ş中的验证码不易被其他的程序探到
g.setColor(new Color(160,200,200));
for(int i=0;i<50;i++)
{
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(width);
int y1=random.nextInt(height);
g.drawLine(x,y,x+x1,y+y1);
}
//随机产生验证码(4为数字)(j)
String sRand="";
for(int i=0;i<4;i++)
{
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
//验证码昄到图?br />
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
g.drawString(rand,13*i+6,16);
}
session.setAttribute("rand",sRand); //////生的验证码存储到sesson?br />
g.dispose();
ImageIO.write(image,"JPEG",response.getOutputStream());
out.clear(); //***********
out=pageContext.pushBody();//**********
%>
*********************************************************************
<img src="yanzhengma.jsp" id="CheckCodeimg" title="看不清请点击囄Q?/><html:errors property="yanzhengma"/>
<a href="#" onclick="document.getElementById('CheckCodeimg').src='yanzhengma.jsp';">看不清?</a><br/>
名称 | cd |
ai | application/postscript |
aif | audio/x-aiff |
aifc | audio/x-aiff |
aiff | audio/x-aiff |
asc | text/plain |
au | audio/basic |
avi | video/x-msvideo |
bcpio | application/x-bcpio |
bin | application/octet-stream |
bmp | image/bmp |
cdf | application/x-netcdf |
class | application/octet-stream |
cpio | application/x-cpio |
cpt | application/mac-compactpro |
csh | application/x-csh |
css | text/css |
dcr | application/x-director |
dir | application/x-director |
djv | image/vnd.djvu |
djvu | image/vnd.djvu |
dll | application/octet-stream |
dms | application/octet-stream |
doc | application/msword |
dvi | application/x-dvi |
dxr | application/x-director |
eps | application/postscript |
etx | text/x-setext |
exe | application/octet-stream |
ez | application/andrew-inset |
gif | image/gif |
gtar | application/x-gtar |
hdf | application/x-hdf |
hqx | application/mac-binhex40 |
htm | text/html |
html | text/html |
ice | x-conference/x-cooltalk |
ief | image/ief |
iges | model/iges |
igs | model/iges |
jpe | image/jpeg |
jpeg | image/jpeg |
jpg | image/jpeg |
js | application/x-javascript |
kar | audio/midi |
latex | application/x-latex |
lha | application/octet-stream |
lzh | application/octet-stream |
m3u | audio/x-mpegurl |
man | application/x-troff-man |
me | application/x-troff-me |
mesh | model/mesh |
mid | audio/midi |
midi | audio/midi |
mif | application/vnd.mif |
mov | video/quicktime |
movie | video/x-sgi-movie |
mp2 | audio/mpeg |
mp3 | audio/mpeg |
mpe | video/mpeg |
mpeg | video/mpeg |
mpg | video/mpeg |
mpga | audio/mpeg |
ms | application/x-troff-ms |
msh | model/mesh |
mxu | video/vnd.mpegurl |
nc | application/x-netcdf |
oda | application/oda |
pbm | image/x-portable-bitmap |
pdb | chemical/x-pdb |
application/pdf | |
pgm | image/x-portable-graymap |
pgn | application/x-chess-pgn |
png | image/png |
pnm | image/x-portable-anymap |
ppm | image/x-portable-pixmap |
ppt | application/vnd.ms-powerpoint |
ps | application/postscript |
qt | video/quicktime |
ra | audio/x-realaudio |
ram | audio/x-pn-realaudio |
ras | image/x-cmu-raster |
rgb | image/x-rgb |
rm | audio/x-pn-realaudio |
roff | application/x-troff |
rpm | audio/x-pn-realaudio-plugin |
rtf | text/rtf |
rtx | text/richtext |
sgm | text/sgml |
sgml | text/sgml |
sh | application/x-sh |
shar | application/x-shar |
silo | model/mesh |
sit | application/x-stuffit |
skd | application/x-koan |
skm | application/x-koan |
skp | application/x-koan |
skt | application/x-koan |
smi | application/smil |
smil | application/smil |
snd | audio/basic |
so | application/octet-stream |
spl | application/x-futuresplash |
src | application/x-wais-source |
sv4cpio | application/x-sv4cpio |
sv4crc | application/x-sv4crc |
swf | application/x-shockwave-flash |
t | application/x-troff |
tar | application/x-tar |
tcl | application/x-tcl |
tex | application/x-tex |
texi | application/x-texinfo |
texinfo | application/x-texinfo |
tif | image/tiff |
tiff | image/tiff |
tr | application/x-troff |
tsv | text/tab-separated-values |
txt | text/plain |
ustar | application/x-ustar |
vcd | application/x-cdlink |
vrml | model/vrml |
wav | audio/x-wav |
wbmp | image/vnd.wap.wbmp |
wbxml | application/vnd.wap.wbxml |
wml | text/vnd.wap.wml |
wmlc | application/vnd.wap.wmlc |
wmls | text/vnd.wap.wmlscript |
wmlsc | application/vnd.wap.wmlscript |
wrl | model/vrml |
xbm | image/x-xbitmap |
xht | application/xhtml+xml |
xhtml | application/xhtml+xml |
xls | application/vnd.ms-excel |
xml | text/xml |
xpm | image/x-xpixmap |
xsl | text/xml |
xwd | image/x-xwindowdump |
xyz | chemical/x-xyz |
zip | application/zip |
<tr>
<th>
ID
</th>
<th>
姓名
</th>
<th>
密码
</th>
<th>
删除?
</th>
</tr>
<logic:present name="userList" scope="request">
<logic:iterate id="User" name="userList" indexId="index">
<tr>
<td>
${User.id}
</td>
<td>
<bean:write name="User" property="username" />
</td>
<td>
<bean:write name="User" property="password" />
</td>
<td>
<html:link action="/deleteUser.do?userId=${User.id}"> 删除</html:link>
</td>
</tr>
</logic:iterate>
</logic:present>
///////////////***********************************//////////////////////////
<body>
<%
HashMap<String,String> mapYear=new HashMap<String,String>();
mapYear.put("0","1980");
mapYear.put("1","1981");
mapYear.put("2","1982");
mapYear.put("3","1983");
request.setAttribute("mapYear",mapYear);
HashMap<String,String> mapMonth=new HashMap<String,String>();
mapMonth.put("0","01");
mapMonth.put("1","02");
mapMonth.put("2","03");
mapMonth.put("3","04");
request.setAttribute("mapMonth",mapMonth);
HashMap<String,String> mapDay=new HashMap<String,String>();
mapDay.put("0","1");
mapDay.put("1","2");
mapDay.put("2","3");
mapDay.put("3","4");
request.setAttribute("mapDay",mapDay);
%>
<html:form action="/addStudent" focus="username">
username : <html:text property="username" />
<html:errors property="username" />
<br />
password : <html:password property="password" />
<html:errors property="password" />
<br />
sex : <html:radio property="sex" value="m" />?
<html:radio property="sex" value="f" />?lt;br />
birthday :<html:select property="birthdayYear" size="1">
<logic:iterate id="map1" name="mapYear" indexId="id">
<html:option value="${map1.value}">${map1.value}</html:option>
</logic:iterate>
</html:select>q?br />
<html:select property="birthdayMonth" size="1">
<logic:iterate id="map2" name="mapMonth" indexId="id">
<html:option value="${map2.value}">${map2.value}</html:option>
</logic:iterate>
</html:select>?br />
<html:select property="birthdayDay" size="1">
<logic:iterate id="map3" name="mapDay" indexId="id">
<html:option value="${map3.value}">${map3.value}</html:option>
</logic:iterate>
</html:select>?lt;br />
grade : <html:text property="grade" />
<br />
<html:submit />
<html:cancel />
</html:form>
</body>
/*********************struts中隔行颜色不同的昄*************************************/
<logic:iterate id="Produt" name="list" indexId="id">
<bean:define id="result" value="${Produt.id%2}"></bean:define>
<logic:equal value="0" name="result">
<tr bgcolor="green">
<td>
${Produt.typeId}
</td>
<td>
${Produt.name}
</td>
<td>
${Produt.price}
</td>
<td>
${Produt.meno}
</td>
</tr>
</logic:equal>
<logic:equal value="1" name="result">
<tr bgcolor="yellow">
<td>
${Produt.typeId}
</td>
<td>
${Produt.name}
</td>
<td>
${Produt.price}
</td>
<td>
${Produt.meno}
</td>
</tr>
</logic:equal>
</logic:iterate>
现在有好多初学jsp的网友经怼(x)问数据库怎么q接啊,怎么老出错啊Q所以我集中的在q写文章供大家参考,其实q种把数据库逻辑全部攑֜jsp里未必是好的做法Q但是有利于初学者学?fn),所以我p样做?jin),当大家学C定程度的时候,可以考虑用MVC的模式开发。在l习(fn)q些代码的时候,你一定将jdbc的驱动程序放到服务器的类路径里,然后要在数据库里Z个表test,有两个字D|如ؓ(f)test1Qtest2Q可以用下面SQL?
create table test(test1 varchar(20),test2 varchar(20)
然后向这个表写入一条测试纪录,那么现在开始我们的jsp和数据库之旅吧?/p>
一、jspq接Oracle8/8i/9i数据库(用thin模式Q?
testoracle.jsp如下Q?
<%@ 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";
//orclZ的数据库的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()) {%>
(zhn)的W一个字D内容ؓ(f)Q?lt;%=rs.getString(1)%>
(zhn)的W二个字D内容ؓ(f)Q?lt;%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜?);%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
二、jspq接Sql Server7.0/2000数据?
testsqlserver.jsp如下Q?
<%@ 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";
//pubsZ的数据库?
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()) {%>
(zhn)的W一个字D内容ؓ(f)Q?lt;%=rs.getString(1)%>
(zhn)的W二个字D内容ؓ(f)Q?lt;%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜?);%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
三、jspq接DB2数据?
testdb2.jsp如下Q?
<%@ 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";
//sampleZ的数据库?
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()) {%>
(zhn)的W一个字D内容ؓ(f)Q?lt;%=rs.getString(1)%>
(zhn)的W二个字D内容ؓ(f)Q?lt;%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜?);%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html> (代码实验?
四、jspq接Informix数据?
testinformix.jsp如下Q?
<%@ 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";
//testDBZ的数据库?
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()) {%>
(zhn)的W一个字D内容ؓ(f)Q?lt;%=rs.getString(1)%>
(zhn)的W二个字D内容ؓ(f)Q?lt;%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜?);%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
五、jspq接Sybase数据?
testmysql.jsp如下Q?
<%@ 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";
//tsdataZ的数据库?
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()) {%>
(zhn)的W一个字D内容ؓ(f)Q?lt;%=rs.getString(1)%>
(zhn)的W二个字D内容ؓ(f)Q?lt;%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜?);%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
六、jspq接MySQL数据?
testmysql.jsp如下Q?
<%@ 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"
//testDBZ的数据库?
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()) {%>
(zhn)的W一个字D内容ؓ(f)Q?lt;%=rs.getString(1)%>
(zhn)的W二个字D内容ؓ(f)Q?lt;%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜?);%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
七、jspq接PostgreSQL数据?
testmysql.jsp如下Q?
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("org.postgresql.Driver").newInstance();
String url ="jdbc:postgresql://localhost/soft"
//softZ的数据库?
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()) {%>
(zhn)的W一个字D内容ؓ(f)Q?lt;%=rs.getString(1)%>
(zhn)的W二个字D内容ؓ(f)Q?lt;%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜?);%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
111
ServletListenerJ2EEHttpSessionJ2EEHttpSessionHttpSessionHttpSessionListenerHttpSessionListenersessionCreatedJ2EEHttpSessionHttpSessionHttpSessionListenersessionDestroyed
sessionCreatedsessionDestroyedHttpSessionListenersessionCreated1sessionDestroyed1
HttpSessionListenerJ2EE
首先Q编写一个简单的计数器,代码如下Q?/span>
1. package accp.onlinecounter;
2. public class OnlineCounter {
3. private static long online = 0;
4. public static long getOnline() {
5. return online;
6. }
7. public static void raise(){
8. online++;
9. }
10. public static void reduce(){
11. online--;
12. }
13. }
HttpSessionListenersessionCreatedOnlineCounterraisesessionDestroyedOnlineCounterreduceҎ(gu)Q代码如下:(x)
1. package accp.onlinecounter;
2. import javax.servlet.http.HttpSessionEvent;
3. import javax.servlet.http.HttpSessionListener;
4. public class OnlineCounterListener implements HttpSessionListener {
5. public void sessionCreated(HttpSessionEvent hse) {
6. OnlineCounter.raise();
7. }
8. public void sessionDestroyed(HttpSessionEvent hse) {
9. OnlineCounter.reduce();
10. }
11. }
HttpSessionListenerweb.xml中加入如下内容:(x)
1. <web-app>
2. ……
3. <listener>
4. <listener-class>
5. accp.OnlineCounterListener
6. </listener-class>
7. </listener>
8. ……
9. </web-app>
OKJSP面中加入下面这L(fng)脚本p昄但前在线人数?jin)?x)
1. <%@ page language="java" pageEncoding="GB2312" %>
2. <%@ page import="accp.OnlineCounter" %>
3. <html>
4. <head><title>On Line Counert</title></head>
5. <body bgcolor="#FFFFFF">
6. On line:<%=OnlineCounter.getOnline()%>
7. </body>
8. </html>
文g的徏?(g)查与删除
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>文g的徏立、检查与删除</title>
</head>
<body>
<%
String path=request.getRealPath("");
//out.println(path);
File f=new File(path,"File.txt");
//out.println(f);
//out.println(f.exists());
if(f.exists()){//(g)查File.txt是否存在
f.delete();//删除File.txt文g
out.println(path + "\\File.txt 存在Q已删除?);
}else{
f.createNewFile();//在当前目录下建立一个名为File.txt的文?
out.println(path + "\\File.txt 不存在,已徏立?);//输出目前所在的目录路径
}
%>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>目录的徏?(g)查与删除</title>
</head>
<body>
<%
String path=request.getRealPath("");
path=path + "\\Sub";//要建立的目录\?
File d=new File(path);//建立代表Sub目录的File对象Qƈ得到它的一个引?
if(d.exists()){//(g)查Sub目录是否存在
d.delete();
out.println("Sub目录存在Q已删除");
}else{
d.mkdir();//建立Sub目录
out.println("Sub目录不存在,已徏?);
}
%>
</body>
</html>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>JSP中如何处理虚拟目?lt;/title>
</head>
<body>
取得虚拟目录对应的磁盘\?lt;br>
Web站点ȝ录的位置?lt;font color=#ff0000><%=request.getRealPath("/")%></font><br>
JSP|页所在的目录位置<font color=#ff0000><%=request.getRealPath("./")%></font><br>
JSP|页所在目录上一层目录的位置<font color=#ff0000><%=request.getRealPath("../")%></font><br>
</body>
</html>
文g属性的取得
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.util.Date,java.io.*"%>
<html>
<head>
<title>文g属性的取得</title>
</head>
<body>
<%
String path=request.getRealPath("/");
File f=new File(path,"ReadData.txt");
if(f.exists()){
%>
<%=f.getName()%>的属性如下:(x)<br><br>
文g长度为:(x)<%=f.length()%>
<%=f.isFile()?"是文?:"不是文g"%><br>
<%=f.isDirectory()?"是目?:"不是目录"%><br>
<%=f.canRead()?"可读?:"不可d"%><br>
<%=f.canWrite()?"可写?:"不可写入"%><br>
<%=f.isHidden()?"是隐藏文?:"不是隐藏文g"%><br>
文g的最后修Ҏ(gu)期ؓ(f)Q?lt;%=new Date(f.lastModified())%><br>
<%
}else{
f.createNewFile();//在当前目录下建立一个名为ReaData.txt的文?
%>
<%=f.getName()%>的属性如下:(x)<br><br>
文g长度为:(x)<%=f.length()%>
<%=f.isFile()?"是文?:"不是文g"%><br>
<%=f.isDirectory()?"是目?:"不是目录"%><br>
<%=f.canRead()?"可读?:"不可d"%><br>
<%=f.canWrite()?"可写?:"不可写入"%><br>
<%=f.isHidden()?"是隐藏文?:"不是隐藏文g"%><br>
文g的最后修Ҏ(gu)期ؓ(f)Q?lt;%=new Date(f.lastModified())%><br>
<%
}
%>
</body>
</html>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>取出目录中文件的Ҏ(gu)--列出目录中的文g</title>
</head>
<body>
<%
String path=request.getRealPath("/");
File d=new File(path);//建立当前目录中文件的File对象
File list[]=d.listFiles();//取得代表目录中所有文件的File对象数组
out.println("<font color=#ff0000>" + path + "目录下的文gQ?lt;/font><br>");
for(int i=0;i<list.length;i++){
if(list<I>.isFile()){
out.println(list<I>.getName() + "<br>");
}
}
out.println("<br><font color=#ff0000>" + path + "目录下的目录Q?lt;/font><br>");
for(int i=0;i<list.length;i++){
if(list<I>.isDirectory()){
out.println(list<I>.getName() + "<br>");
}
}
%>
</body>
</html>
判断是否为空白文?
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>判断是否为空白文?lt;/title>
</head>
<body>
<%
String path=request.getRealPath("/");
out.println(path);
FileReader fr=new FileReader(path + "\\AtEnd.txt");//建立FileReader对象Qƈ实例化ؓ(f)fr
//对FileReadercȝ成的对象使用read()Ҏ(gu)Q可以从字符中d下一个字W?
if(fr.read()==-1)//判断是否已读到文件的l尾
{
out.print("AtEnd.txt文g中没有数?lt;br>");
}else{
out.println("AtEnd.txt文g中有数据");
}
fr.close();
%>
</body>
</html>
<B>d所有的文g数据</B>
<ccid_nobr>
<table width="400" border="1" cellspacing="0" cellpadding="2"
bordercolorlight = "black" bordercolordark = "#FFFFFF" align="center">
<tr>
<td bgcolor="e6e6e6" class="code" style="font-size:9pt">
<pre><ccid_code> <%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*,java.lang.*"%>
<html>
<head>
<title>d所有的文g数据</title>
</head>
<body>
<%
String path=request.getRealPath(".");
FileReader fr=new FileReader(path + "\\ReadData.txt");
//关键在于dq程中,要判断所d的字W是否已l到?jin)文件的末尾Q?
q且q个字符是不是文件中的断行符Q即判断该字W值是否ؓ(f)13?
int c=fr.read();//从文件中d一个字W?
//判断是否已读到文件结?
while(c!=-1){
out.print((char)c);//输出d的数?
c=fr.read();//从文件中l箋(hu)d数据
if(c==13){//判断是否为断行字W?
out.print("<br>");//输出分行标签
fr.skip(1);//略过一个字W?
//c=fr.read();//d一个字W?
}
}
fr.close();
%>
</body>
</html>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>文gd</title>
</head>
<body>
<%
String path=request.getRealPath("");//取得当前目录的\?
FileReader fr=new FileReader(path + "\\file\\inc\\t.txt");//建立FileReader对象Qƈ实例化ؓ(f)fr
BufferedReader br=new BufferedReader(fr);//建立BufferedReader对象Qƈ实例化ؓ(f)br
String Line=br.readLine();//从文件读取一行字W串
//判断d到的字符串是否不为空
while(Line!=null){
out.println(Line + "<br>");//输出从文件中d的数?
Line=br.readLine();//从文件中l箋(hu)d一行数?
}
br.close();//关闭BufferedReader对象
fr.close();//关闭文g
%>
</body>
</html>
略过文g中的字符不读?
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>略过字节不读?lt;/title>
</head>
<body>
<%
String path=request.getRealPath(".");
FileReader fr=new FileReader(path + "\\ReadData.txt");
fr.skip(2);//跌2个字?
int c=fr.read();//d一个字?
while(c!=-1){
out.print((char)c);
c=fr.read();
}
fr.close();
%>
</body>
</html>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>数据写入文?lt;/title>
</head>
<body>
<%
String path=request.getRealPath(".");
FileWriter fw=new FileWriter(path + "\\WriteData.txt");//建立FileWriter对象Qƈ实例化fw
//字W串写入文g
fw.write("大家好!");
fw.write("本书是《JSP~程技巧?);
fw.write("请多多指教!");
fw.write("email:stride@sina.com");
fw.close();
FileReader fr=new FileReader(path + "\\WriteData.txt");
BufferedReader br=new BufferedReader(fr);//建立BufferedReader对象Qƈ实例化ؓ(f)br
String Line=br.readLine();
//d一行数?
out.println(Line + "<br>");
br.close();//关闭BufferedReader对象
fr.close();
%>
</body>
</html>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>写入文件的数据分行</title>
</head>
<body>
<%
String path=request.getRealPath(".");
FileWriter fw=new FileWriter(path + "\\WriteData.txt");
BufferedWriter bw=new BufferedWriter(fw);
bw.write("大家好!");
bw.write("本书是《JSP~程技巧》?);
bw.newLine();//断行
bw.write("请多多指教!");
bw.newLine();//断行
bw.write("email: stride@sina.com");
bw.flush();//数据更新至文g
fw.close();//关闭文g?
out.println("写入文g内容为:(x)<br>");
FileReader fr=new FileReader(path + "\\WriteData.txt");
BufferedReader br=new BufferedReader(fr);
String Line=br.readLine();//d一行数?
while(Line!=null){
out.println(Line + "<br>");
Line=br.readLine();
}
fr.close();
%>
</body>
</html>
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>写入文件的数据分行</title>
</head>
<body>
<%
String path=request.getRealPath(".");
RandomAccessFile rf=new RandomAccessFile(path + "\\WriteData.txt","rw");
//定义一个类RandomAccessFile的对象,q实例化
rf.seek(rf.length());//指针移动到文g末尾
rf.writeBytes("\nAppend a line to the file!");
rf.close();//关闭文g?
out.println("写入文g内容为:(x)<br>");
FileReader fr=new FileReader(path + "\\WriteData.txt");
BufferedReader br=new BufferedReader(fr);//d文g的BufferedRead对象
String Line=br.readLine();
while(Line!=null){
out.println(Line + "<br>");
Line=br.readLine();
}
fr.close();//关闭文g
%>
</body>
</html></I></I></I></I>
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
/**
* MyEclipse Struts
* Creation date: 09-17-2007
*
* @author 王世?br />
**/
public class FileForm extends ActionForm {
private static final long serialVersionUID = 1L;
private FormFile myFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public FormFile getMyFile() {
return myFile;
}
public void setMyFile(FormFile myFile) {
this.myFile = myFile;
}
}
package wsq.struts.action;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import wsq.struts.form.FileForm;
public class FileAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException{
FileForm fileForm = (FileForm) form;
FormFile file = fileForm.getMyFile();
if (file == null)
{
return mapping.findForward("error");
}
String dir=servlet.getServletContext().getRealPath("/image");//首先在你的项目下新徏个(?nbsp;webroot下)(j)image文g?br />
/***注释的是按孙卫琴书上来的*************/
// InputStream in=file.getInputStream();
// OutputStream out=new FileOutputStream(dir+"/"+file.getFileName());
// int bytesRead=0;
// byte [] buffer=new byte[8000];
// while((bytesRead=in.read(buffer, 0, 8000))!=-1)
// {
// out.write(buffer,0,bytesRead);
//
// }
FileOutputStream out = new FileOutputStream(dir+"/" + file.getFileName());
out.write(file.getFileData());
out.close();
//in.close();
file.destroy();
System.out.println(file.getFileName()+"上传文g的名?);
return null;
}
}
![]() |
![]() |
![]() |