共 90篇 前 10 页: 10    每页5篇 下一页  

JSP学习


<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%
String[] timefirs=new String[3];
String timefir=
"2006-9-28";
timefirs=timefir.split(
"-");
    String mydate1=timefirs[0]+
"年"+timefirs[1]+"月"+timefirs[2]+"日";
out.print(mydate1);
%>
lunzi   2006-09-28 08:57:08 阅读:622  评论:1  引用:0
请求地址:
http://localhost:8888/index.jsp?s=%E6%96%97%E5%9C%B0%E4%B8%BB&nau=http://xxxx/file/gd/2010-09/02/4004320.apk%3Fid=3463%26wf=0,2%26softName=%E6%96%97%E5%9C%B0%E4%B8%BB%26pstyle=s

index.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page import="java.util.regex.Pattern" %>
<%@ page import="java.util.regex.Matcher" %>

<%
    /*<Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8"
               connectionTimeout="20000"
               redirectPort="8443" />
      特别引起我注意的是 URIEncoding="UTF-8" ,如果不设置,url上传递的中文就不能被正确解码    
    */

    //http://localhost:8888/index.jsp?s=%E6%96%97%E5%9C%B0%E4%B8%BB&nau=http://xxxx/file/gd/2010-09/02/4004320.apk%3Fid=3463%26wf=0,2%26softName=%E6%96%97%E5%9C%B0%E4%B8%BB%26pstyle=s

    String s = request.getParameter("s");
    String str = request.getParameter("nau");

    //out.println(URLDecoder.decode(s,"UTF-8"));  
    out.println(str+"<br/>");

    Pattern p = Pattern.compile("softName=(.*)[&$]");
    Matcher m = p.matcher(str);
    String softName = "";
    while(m.find()){

       softName =  m.group(1);
       out.println("softName=" + softName);
        
    }

   // out.println("decode:"+URLEncoder.encode(softName,"UTF-8"));

    out.println(str.replace(softName,URLEncoder.encode(softName,"UTF-8")));

    //out.println(s);
    //str = URLDecoder.decode(str,"UTF-8");
    //out.println("test="+str);



%>


lunzi   2010-09-02 23:03:35 阅读:853  评论:0  引用:0

导航的单独文件nav.jsp

<%@ page contentType=
"text/html; charset=utf-8" language="java"%>
<%@taglib prefix=
"c"  uri="http://java.sun.com/jsp/jstl/core" %>
<div id=
"navbox">
<ul>
<c:choose>
<c:when test=
"${param.view=='nav1'}"><font color=red>导航一</font></c:when>
<c:otherwise>导航一</c:otherwise>
</c:choose>

<c:choose>
<c:when test=
"${param.view=='nav2'}"><font color=red>导航二</font></c:when>
<c:otherwise>导航二</c:otherwise>
</c:choose>
</ul>
  </div>

调用导航的文件show.jsp

<%@ page language=
"java"  pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'show.jsp' starting page</title>
  </head>
  
  <body>
    <jsp:include page=
"/nav.jsp">
<jsp:param name=
"view" value="nav1"/>
</jsp:include>
  </body>
</html>


效果:
lunzi   2008-11-11 11:12:40 阅读:1680  评论:0  引用:0

JSP文件下载类整理完成。可以在JSP页面中实现简单的下载,支持文件打包下载功能。支持将字符串或者流生成文件提供下载的功能。但是也有一些缺点。现把这个类的基本介绍总结如下。

名称:jsp页面下载类
作者:SinNeR
Mail:vogoals[at]hotmail.com

特点及功能介绍:

支持单文件下载。支持多文件zip压缩下载。多文件zip压缩可在服务器保留或者删除副本。支持将特定的字符串或者byte数组以指定的文件名提供下载。
在下载过程中需要提供response对象。并且选择下载形式。
下载处理前先进行check,避免出现错误。
下载处理过程中出错时,会报告错误信息。
日文系统下文件名是中文时出现乱码问题。
处理前需要进行相对繁琐的设定。
现介绍下使用者可见的方法的功能。

设定实现下载必须的response对象。
public void setResponse(HttpServletResponse response)

设定下载方式:0 为普通单文件下载。 1 为多文件压缩成zip包下载。 2 为将指定的字符串等拼接成文件内容提供给用户下载。
public void setDownType(int fileType)

设定下载时显示给用的文件名。
public void setDisFileName(String fileName)
    

压缩文件下载时,设定压缩文件暂时保存的路径(路径为绝对路径)
public void setZipFilePath( String path )
    

压缩文件下载时,设定服务器端生成的压缩文件是否删除。True 删除;false 保留。
public void setZipDelFlag(boolean b)
    
压缩文件下载时,设定要压缩的文件的文件路径(路径为绝对路径)
public void setZipFileNames(String[] fileNames)

单文件下载时,设定下载文件的路径(绝对路径)
public void setDownFileName(String fileName)
    

将字符串生成文件内容模拟下载时,设定文件的内容。参数为字符串(可多次调用)
public int setFileContent(String fileContent)

将字符串生成文件内容模拟下载时,设定文件的内容。参数为byte数组(可多次调用)
返回值:0 操作正常; 9 出现IO异常。
public int setFileContent(byte[] fileContent)
    
将字符串生成文件内容模拟下载时,调用此方法结束文件内容设定。
返回值:0 操作正常; 9 出现IO异常。
public int setFileContentEnd()
    
主处理函数。
返回值:    0   处理正常;1  未设定response对象。 2  未设定文件下载方式。  3   未设定要显示的文件名。  4  未设定要下载的文件路径,或者设定的下载的文件路径不存在。  9  IO异常。
public int process()

现在介绍不同下载模式下的简单流程:

单文件下载流程:

//实例初始化
JspFileDownload jfd = new JspFileDownload();
//设定response对象    
jfd.setResponse(response);
//设定文件下载模式 0 单文件下载。
jfd.setDownType(0);
//设定显示的文件名 xxxx.xxx
jfd.setDisFileName(filename);
//设定要下载的文件的路径,绝对路径
jfd.setDownFileName(filePath);
//主处理函数。注意处理返回值。
int result = jfd.process();

多文件压缩成ZIP文件下载:

//实例初始化
JspFileDownload jfd = new JspFileDownload();
//设定response对象。
jfd.setResponse(response);
//设定下载模式 1 多文件压缩成ZIP文件下载。
jfd.setDownType(1);
//设定显示的文件名
jfd.setDisFileName(filename);
//设定要下载的文件的路径(数组,绝对路径)
jfd.setZipFileNames(fileNames);
//设定服务器端生成的zip文件是否保留。 true 删除  false 保留,默认为false
jfd.setZipDelFlag(true);
//设定zip文件暂时保存的路径 (是文件夹)
jfd.setZipFilePath(zipfolder);
//主处理函数 注意返回值
Int result = jfd.process();

将字符串生成为文件内容,模拟文件下载:

//实例初始化
JspFileDownload jfd = new JspFileDownload();
//设定response对象。
jfd.setResponse(response);
//设定下载模式 2 将字符串作为文件内容,实现文件下载。
jfd.setDownType(2);
//设定文件显示的名称。
jfd.setDisFileName(request.getParameter(
"filename"));
//主处理函数,下载前check,注意返回值
out.print(jfd.process());
//设定要写入文件的内容,参数可为字符串或者byte数组。可多次调用。
jfd.setFileContent(request.getParameter(
"name"));
//文件内容设定完了,调用函数。    
jfd.setFileContentEnd();

以上就是简单的使用介绍。下面贴出主处理类的代码。由于在日文系统下编辑的文件。注释只能写英文,英文太差-_-b。多包涵。

package com.vogoal.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
/*
* vogoalAPI 1.0
* Auther SinNeR@blueidea.com
* by vogoal.com
* mail: vogoals@hotmail.com
*/

/**
* JSP FILE DOWNLOAD SUPPORT
*
* @author SinNeR
* @version 1.0
*/

public class JspFileDownload {
    
/** request object */
    private HttpServletResponse response = null;
    
/** file type: -1 un-setting; 0 normal file; 1 zip file ;2 stream*/
    private int fileType = -1;
    
    
/** file name to be displayed */
    private String disFileName = null;
    
    
/** zip file path */
    private String zipFilePath = null;
    
    
/** file to be zipped */
    private String[] zipFileNames = null;
    
    private boolean zipDelFlag = false;
    
    
/** file to be downloaded */
    private String downFileName = null;
    
    
/** error code 0 */
    private static final int PROCESS_OK = 0;
    
    
/** error code 1 */
    private static final int RESPONSE_IS_NULL = 1;
    
    
/** error code 2 */
    private static final int UNSET_DOWNLOADTYPE = 2;
    
    
/** error code 3 */
    private static final int UNSET_DIS_FILE_NAME = 3;
    
    
/** error code 4 */
    private static final int UNSET_DOWN_FILE_NAME = 4;
    
    
/** error code 9 */
    private static final int IO_EXCEPTION = 9;
    
    
/**
     * set response object
     * @param response response Object
     */

    public void setResponse(HttpServletResponse response){
        this.response = response;
    }
    
    
/**
     * set file type 0 normal file; 1 zip file ;2 stream
     * @param fileType
     */

    public void setDownType(int fileType){
        this.fileType = fileType;
    }
    
    
/**
     * set display file name
     * @param fileName
     */

    public void setDisFileName(String fileName){
        this.disFileName = fileName;
    }
    
    
/**
     * set zip file path
     * @param fileNames
     */

    public void setZipFilePath( String path ){
        this.zipFilePath = path;
    }
    
    public void setZipDelFlag(boolean b){
        this.zipDelFlag = b;
    }
    
    
/**
     * set zip file names
     * @param fileNames
     */

    public void setZipFileNames(String[] fileNames){
        this.zipFileNames = fileNames;
    }
    
    
/**
     * set download file name
     * @param fileName
     */

    public void setDownFileName(String fileName){
        this.downFileName = fileName;
    }
    
    
/**
     * set file content
     * @param fileContent
     */

    public int setFileContent(String fileContent){    
        try{    
            byte[] buffs = fileContent.getBytes(
"UTF-8");
            response.getOutputStream().write(buffs);
        }catch(IOException e){
            return IO_EXCEPTION;
        }
        return PROCESS_OK;
    }
    
    
/**
     * set file content
     * @param fileContent
     */

    public int setFileContent(byte[] fileContent){
        try{
            response.getOutputStream().write(fileContent);
        }catch(IOException e){
            return IO_EXCEPTION;
        }
        return PROCESS_OK;
    }
    
    
/**
     * set file content end
     *
     */

    public int setFileContentEnd(){
        try{
            response.getOutputStream().close();
        }catch(IOException e){
            return IO_EXCEPTION;
        }
        return PROCESS_OK;
    }
    
    
/**
     * main process
     * @return
     */

    public int process(){
        int status = PROCESS_OK;
        
        status = preCheck();
        if ( status != PROCESS_OK )
            return status;
            
        String fileName = disFileName;
        
        response.setContentType(
"APPLICATION/OCTET-STREAM");  
        response.setHeader(
"Content-Disposition","attachment;filename=\"" + fileName + "\"");
        int BUFSIZE = 1024 * 8;        
        int rtnPos = 0;
        byte[] buffs = new byte[ BUFSIZE ];
        FileInputStream inStream = null;
        ZipOutputStream zos = null;
        InputStream is = null;
        String filepath = null;
        try{
          
            if ( fileType == 0 || fileType == 1){
                if ( fileType == 0 ){
                    filepath = downFileName;  
                }else{
                    filepath = zipFilePath + fileName;
                    String[] fileToZip = zipFileNames;
                                    
                    zos=new ZipOutputStream(new FileOutputStream(filepath));
                    ZipEntry ze=null;
                    byte[] buf=new byte[BUFSIZE];
                    int readLen=0;
                    for (int i= 0;i<fileToZip.length;i++){
                        File f= new File(fileToZip<i>);
        
                        ze=new ZipEntry(f.getName());
                        ze.setSize(f.length());
                        ze.setTime(f.lastModified());
        
                        zos.putNextEntry(ze);
                        is=new BufferedInputStream(new FileInputStream(f));
                        while ((readLen=is.read(buf, 0, BUFSIZE))!=-1) {
                            zos.write(buf, 0, readLen);
                        }
                        is.close();
                    }
                    zos.close();
                }
          
                inStream =new FileInputStream(filepath);  
  
                while((rtnPos=inStream.read(buffs)) >0)  
                    response.getOutputStream().write(buffs,0,rtnPos);  
                response.getOutputStream().close();  
                inStream.close();
            }
            if ( zipDelFlag ){
                File fToDel = new File(filepath);
                fToDel.delete();
            }
        }catch(IOException e){
            return IO_EXCEPTION;
        }finally{
            try{
                if ( inStream != null ){
                    inStream.close();
                    inStream = null;
                }
                if ( zos != null ){
                    zos.close();
                    zos = null;
                }
                if ( is != null ){
                    is.close();
                    is = null;
                }
            }catch (IOException e){
            }
        }
        return status;
    }
    
    
/**
     * pre check.
     * @return
     */

    private int preCheck(){
        
        if ( response == null )
            return RESPONSE_IS_NULL;
            
        if ( disFileName == null || disFileName.trim().length() == 0 )
            return UNSET_DIS_FILE_NAME;
        if ( fileType == -1 )
            return UNSET_DOWNLOADTYPE;
        else if ( fileType == 0 ){
            if ( downFileName == null || downFileName.trim().length() == 0 )
                return UNSET_DOWN_FILE_NAME;
            else{
                if ( !isFile( downFileName ) )
                    return UNSET_DOWN_FILE_NAME;
            }
            
        }else if ( fileType == 1 ){
            if ( zipFilePath == null || zipFilePath.length() == 0 )
                return UNSET_DOWN_FILE_NAME;
            else{
                if ( !isDirect(zipFilePath) )
                    return UNSET_DOWN_FILE_NAME;
            }
            if ( zipFileNames == null || zipFileNames.length == 0 )
                return UNSET_DOWN_FILE_NAME;
            else{
                for ( int i=0;i<zipFileNames.length;i++ ){
                    if ( zipFileNames<i> == null || zipFileNames<i>.trim().length() == 0 )
                        return UNSET_DOWN_FILE_NAME;
                    else{
                        if ( !isFile( zipFileNames<i> ) )
                            return UNSET_DOWN_FILE_NAME;
                    }
                }
            }
        }else if ( fileType == 2 ){
            
//doing nothing
        }else{
            return UNSET_DOWNLOADTYPE;
        }
        return PROCESS_OK;
    }
    
    private boolean isFile(String fileName){
        File f = new File(fileName);
        if (!f.exists() || !f.isFile())
            return false;
        return true;
    }
    
    private boolean isDirect(String filePath){
        File f = new File(filePath);
        if (!f.exists() || !f.isDirectory())
            return false;
        return true;
    }
}

至此,jsp页面文件下载介绍完成。


参考资料
lunzi   2008-10-26 00:39:54 阅读:4034  评论:2  引用:0
错误提示:
java.lang.SecurityException: Total File Size exceeded (1110)

原因是:
SmartUpload mySmartUpload =new SmartUpload();
mySmartUpload.setTotalMaxFileSize(1000000);//限制总上传数据的长度

上传的文件超出了限制总上传数据的长度。



lunzi   2008-10-15 14:19:23 阅读:1228  评论:3  引用:0

一、Driver.properties文件内容

drivers=org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost:3306/lunzi
user=root
password=123456

二、DBConnection.java数据库连接类

/**
 * 通过属性文件加载数据库驱动程序,建立数据库的连接
 */
package apple.lunzi.jdbc;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.log4j.Logger;

public class DBConnection
{
 protected static Logger logger = Logger.getLogger(DBConnection.class.getName());
 private String url;//数据库URL
 private String userName;//登录数据库用户名
 private String password;//用户密码
 
 /**
  * 返回到数据库的一个连接,在一个系统或类中,如果经常进行数据库的相关操作
  * 会把建立数据库的连接作为一个单独的方法。
  */
 public Connection getConnection()
 {
  getProperty();
  Connection con = null;
  try
  {
   con = DriverManager.getConnection(url, userName, password);
  }
  catch(SQLException e)
  {
   //e.printStackTrace();
   logger.error("找不到指定的文件!!!",e);
  }
    
  return con;
 }
 
 /**
  * 读取属性配置文件
  */
 private void getProperty()
 {
  Properties prop = new Properties();
  try
  {
   InputStream in = this.getClass().getResourceAsStream("/Driver.properties");
   prop.load(in);
 
   String driver = prop.getProperty("drivers");
   if(driver != null)
    System.setProperty("jdbc.drivers", driver);
   url = prop.getProperty("url");
   userName = prop.getProperty("user");
   password = prop.getProperty("password");   
  }
  catch(FileNotFoundException e)
  {
   e.printStackTrace();
  }
  catch(IOException e)
  {
   e.printStackTrace();
  }
 }
}
三、JdbcManager.java封装jdbc类文件

package apple.lunzi.jdbc;

import java.sql.*;

public class JdbcManager extends DBConnection {
 
 private Connection conn = null;
 private Statement stmt = null;
 private ResultSet rs = null;

 public  ResultSet select(String sql){

  try {
   conn = super.getConnection();
   stmt = conn.createStatement();
   rs = stmt.executeQuery(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return rs;
 }

......封装其他的方法(update,insert,delete)

 public void close(){

  try {
   if(rs != null)
    rs.close();
   if(stmt != null)
    stmt.close();
   if(conn != null)
    conn.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
}

lunzi   2007-05-13 12:45:41 阅读:2011  评论:0  引用:0

<%@ page contentType=
"text/html; charset=gb2312" language="java" import="java.sql.*"%>
<%!
StringBuffer optionStr = new StringBuffer();
private void tree(Connection jdbc,int id,int level){
  ResultSet rs = null;
  Statement stmt = null;
  String preStr =
"";
  for(int i=0; i<level; i++) {
   preStr +=
"----";
  }
  String sql =
"select * from news_cat where PARENT_ID = " + id;
  try{
   stmt = jdbc.createStatement();
   rs = stmt.executeQuery(sql);
   while(rs.next()){
    optionStr.append(
"<option value=")    
       .append(rs.getString(
"cat_id"))
        .append(
">")
        .append(preStr)
       .append(rs.getString(
"cat_name"))
       .append(
"</option>");
    if(rs.getInt(
"is_leaf") != 0) {
     tree(jdbc, rs.getInt(
"cat_id"), level+1);
    }
   }
  } catch(SQLException e){
   e.printStackTrace();
  }  finally {
   try {
    if(rs != null) {
     rs.close();
     rs = null;
    }
    if(stmt != null){
      stmt.close();
      stmt = null;
    }
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
}
%>
<%
  Class.forName(
"oracle.jdbc.driver.OracleDriver");
  ResultSet rs = null;
  Statement stmt = null;
  Connection conn = null;
  conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:apple", "lunzi", "121561");
  stmt = conn.createStatement();
  rs = stmt.executeQuery(
"select * from news_cat where PARENT_ID = 0");
  
optionStr.append(
"<select name=\"news_cat\">");
while(rs.next()){
  optionStr.append(
"<option value=")
     .append(rs.getString(
"cat_id"))
     .append(
">")
     .append(rs.getString(
"cat_name"))
     .append(
"</option>");
    if(rs.getInt(
"is_leaf") != 0) {
      tree(conn,rs.getInt(
"cat_id"),1);
    }
}
  optionStr.append(
"</select>");
rs.close();
stmt.close();
conn.close();
out.println(optionStr.toString());
%>
lunzi   2007-05-06 02:50:52 阅读:2564  评论:1  引用:0
<!--copyright_index_start-->
[^~]*<!--copyright_index_end-->
lunzi   2007-01-10 11:20:20 阅读:692  评论:0  引用:0

StringBuffer str=new StringBuffer();
int i=1;
do {
long m=Math.round(Math.random()*4);
int flag=str.indexOf(String.valueOf(m));
if(flag<=-1) {
if(i==1)
{
str.append(m);
}
else{
str.append(
",").append(m);
}
i++;
}
}while(i<6);

lunzi   2006-11-28 16:50:15 阅读:869  评论:0  引用:0

<%@ page contentType=
"text/html; charset=gb2312" language="java" errorPage="" %>
<%@ page import=
"java.util.ArrayList"%>
<%@ page import=
"java.util.Random"%>

<form method=
"post" name="frms" action="check.jsp">
<table width=
"180" height="140"  border="0" align="center" cellpadding="0" cellspacing="0">  
        <%
          
            ArrayList  a = new ArrayList();
            ArrayList  b = new ArrayList();
            StringBuffer ss = new StringBuffer();
            StringBuffer us = new StringBuffer();
            Random r = new Random();
            String gs=
"";
            String logo0[];
            int cn=15;
    
String logos =
"logo";

for(int i = 0;i<15;i++){
                logo0=new String[5];
                logo0[0]=logos+
"0["+i+"]";
                logo0[1]=logos+
"1["+i+"]";
                logo0[2]=logos+
"2["+i+"]";
logo0[3]=logos+
"3["+i+"]";
logo0[04]=logos+
"4["+i+"]";
                a.add(logo0);
            }
            int jc=0;
            while(a.size()>0){
                jc = r.nextInt(a.size());
                b.add(a.get(jc));
                a.remove(jc);
            }
            int is=0;
            for(int j=0;j<5;j++){
        %>
        <tr>
          <td height=
"12">&nbsp;</td>
        </tr>
        <tr>
            <%
                for(int i=0;i<3;i++){
                    is++;
                    logo0=(String[])b.get(j*3+i);

            %>
            <td align=
"center"><table width="160" height="110"  border="0" cellpadding="0" cellspacing="0">
              <tr>
                <td><table width=
"142" height="100"  border="1" align="center" cellpadding="0" cellspacing="0">
                  <tr>
                    <td align=
"center" valign="middle" ><img style="cursor:hand" onClick="subl(<%=is%>,<%=logo0[0]%>)" src="<%=logo0[2]%>" title="点我进行游戏" width="120" height="60" border="0"><br>
                        <br>
                        <a href=
"<%=logo0[4]%>" target="_blank" class="font21"><%=logo0[1]%></a></td>
                  </tr>
                  <tr>
                    <td align=
"center" valign="middle" ><input name="funs" type="checkbox" id="funs" value="<%=logo0[2]%>"></td>
                  </tr>
                </table></td>
              </tr>
            </table></td>
            <%}%>
        </tr>
        <%}%>  
</table>
<div align=
"center"><br>
    <input type=
"submit" name="Submit" value="提交">
</div>
</form>
lunzi   2006-11-26 17:02:43 阅读:1299  评论:0  引用:0
Copyright@2004-2010 powered by YuLog